repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
Actinium-project/ACM-LN-Desktop
|
app/components/Channels/ChannelCardList.js
|
import React from 'react'
import PropTypes from 'prop-types'
import { Box } from 'rebass'
import styled from 'styled-components'
import { Grid, AutoSizer } from 'react-virtualized'
import { space as baseSpace } from 'themes/base'
import ChannelCardListItem from './ChannelCardListItem'
const StyledList = styled(Grid)`
outline: none;
overflow-y: overlay !important;
overflow-x: hidden !important;
`
const ChannelCardList = ({
channels,
currencyName,
openModal,
setSelectedChannel,
networkInfo,
}) => {
const ROW_PADDING_BOTTOM = 3
// current row height + margin bottom
const ROW_HEIGHT = 396 + baseSpace[ROW_PADDING_BOTTOM]
const renderRow = rowProps => {
const { columnIndex, rowIndex, key, style } = rowProps
const index = rowIndex * 2 + columnIndex
// index may exceed total number of elements because of 2 column layout
if (index >= channels.length) {
return null
}
const channel = channels[index].channel || channels[index]
return (
<Box
key={key}
pb={ROW_PADDING_BOTTOM}
pl={index % 2 ? 3 : 4}
pr={index % 2 ? 4 : 3}
pt={3}
style={style}
width={1 / 2}
>
<ChannelCardListItem
channel={channel}
css={{ height: '100%' }}
currencyName={currencyName}
networkInfo={networkInfo}
openModal={openModal}
setSelectedChannel={setSelectedChannel}
/>
</Box>
)
}
return (
<AutoSizer>
{({ width, height }) => {
return (
<StyledList
cellRenderer={renderRow}
columnCount={2}
columnWidth={width / 2}
height={height}
rowCount={Math.ceil(channels.length / 2)}
rowHeight={ROW_HEIGHT}
width={width}
/>
)
}}
</AutoSizer>
)
}
ChannelCardList.propTypes = {
channels: PropTypes.array,
currencyName: PropTypes.string.isRequired,
networkInfo: PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
}),
openModal: PropTypes.func.isRequired,
setSelectedChannel: PropTypes.func.isRequired,
}
ChannelCardList.defaultProps = {
channels: [],
}
export default ChannelCardList
|
blindsubmissions/icse19replication
|
generated-tests/qmosa/tests/s1020/107_weka/evosuite-tests/weka/filters/unsupervised/attribute/Discretize_ESTest.java
|
/*
* This file was automatically generated by EvoSuite
* Fri Aug 24 13:51:43 GMT 2018
*/
package weka.filters.unsupervised.attribute;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.shaded.org.mockito.Mockito.*;
import static org.evosuite.runtime.EvoAssertions.*;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Properties;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.System;
import org.evosuite.runtime.ViolatedAssumptionAnswer;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.FileSystemHandling;
import org.evosuite.runtime.util.SystemInUtil;
import org.junit.runner.RunWith;
import weka.core.Attribute;
import weka.core.BinarySparseInstance;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.ProtectedProperties;
import weka.core.SparseInstance;
import weka.filters.AllFilter;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Discretize;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class Discretize_ESTest extends Discretize_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.getUseBinNumbers();
discretize0.setDesiredWeightOfInstancesPerInterval((-4577.3789113));
discretize0.desiredWeightOfInstancesPerIntervalTipText();
discretize0.getUseEqualFrequency();
int[] intArray0 = new int[5];
intArray0[0] = (-2778);
intArray0[1] = 10;
intArray0[2] = 0;
intArray0[3] = (-2110);
intArray0[4] = 0;
discretize0.setAttributeIndicesArray(intArray0);
assertEquals((-4577.3789113), discretize0.getDesiredWeightOfInstancesPerInterval(), 0.01);
}
/**
//Test case number: 1
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
String string0 = ";(";
Discretize discretize0 = new Discretize(";(");
discretize0.setUseEqualFrequency(false);
String string1 = "jIzK|8U\"v5F";
discretize0.setAttributeIndices("jIzK|8U\"v5F");
int int0 = (-3589);
discretize0.setBins((-3589));
discretize0.getRevision();
discretize0.m_DesiredWeightOfInstancesPerInterval = 1196.20936604;
discretize0.setAttributeIndices("8964");
discretize0.makeBinaryTipText();
discretize0.listOptions();
StringReader stringReader0 = new StringReader("vc76");
char[] charArray0 = new char[9];
charArray0[0] = 'K';
charArray0[1] = '.';
charArray0[2] = 'L';
charArray0[3] = '=';
charArray0[4] = 'F';
charArray0[5] = 'z';
charArray0[6] = 'e';
charArray0[7] = ';';
charArray0[8] = '0';
// Undeclared exception!
try {
stringReader0.read(charArray0, (-3589), (-3589));
fail("Expecting exception: IndexOutOfBoundsException");
} catch(IndexOutOfBoundsException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.io.StringReader", e);
}
}
/**
//Test case number: 2
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
Discretize discretize0 = new Discretize("");
double[] doubleArray0 = new double[2];
doubleArray0[0] = 2.0;
doubleArray0[1] = 2.0;
int[] intArray0 = new int[8];
intArray0[0] = 0;
intArray0[1] = 492;
intArray0[2] = 637;
intArray0[3] = 699;
intArray0[4] = 82;
intArray0[5] = 79;
intArray0[6] = 472;
intArray0[7] = 0;
SparseInstance sparseInstance0 = new SparseInstance(2.0, doubleArray0, intArray0, 93);
// Undeclared exception!
try {
discretize0.input(sparseInstance0);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// No input instance format defined
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 3
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
Discretize discretize0 = new Discretize("eym1");
discretize0.getRevision();
discretize0.getAttributeIndices();
discretize0.setBins(82);
discretize0.setDesiredWeightOfInstancesPerInterval((-725.1));
// Undeclared exception!
try {
discretize0.batchFinished();
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// No input instance format defined
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 4
/*Coverage entropy=2.2275247137250096
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
Discretize discretize0 = new Discretize("");
int int0 = 743;
discretize0.getOptions();
discretize0.setBins(743);
int int1 = (-148);
discretize0.getOptions();
// Undeclared exception!
try {
discretize0.calculateCutPointsByEqualFrequencyBinning((-148));
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.core.Instances", e);
}
}
/**
//Test case number: 5
/*Coverage entropy=2.1972245773362196
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
int int0 = 2710;
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
doubleArray0[3] = (-1144.72938352);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 2;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
// Undeclared exception!
try {
discretize0.calculateCutPointsByEqualFrequencyBinning(2710);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 6
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
Discretize discretize0 = new Discretize("I406@Yd{on");
assertFalse(discretize0.getUseEqualFrequency());
discretize0.m_UseEqualFrequency = true;
discretize0.setMakeBinary(true);
discretize0.makeBinaryTipText();
discretize0.findNumBinsTipText();
String string0 = discretize0.invertSelectionTipText();
assertEquals("Set attribute selection mode. If false, only selected (numeric) attributes in the range will be discretized; if true, only non-selected attributes will be discretized.", string0);
}
/**
//Test case number: 7
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.getBinRangesString(1588);
boolean boolean0 = false;
discretize0.getRevision();
discretize0.setUseEqualFrequency(false);
int int0 = 0;
// Undeclared exception!
try {
discretize0.outputPeek();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// No output instance format defined
//
verifyException("weka.filters.Filter", e);
}
}
/**
//Test case number: 8
/*Coverage entropy=2.5649493574615376
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
Discretize discretize0 = new Discretize();
Filter.runFilter(discretize0, (String[]) null);
discretize0.m_IgnoreClass = false;
discretize0.getUseBinNumbers();
discretize0.attributeIndicesTipText();
// Undeclared exception!
try {
discretize0.outputPeek();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// No output instance format defined
//
verifyException("weka.filters.Filter", e);
}
}
/**
//Test case number: 9
/*Coverage entropy=2.70805020110221
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
Discretize discretize0 = new Discretize();
Discretize discretize1 = (Discretize)Filter.makeCopy(discretize0);
discretize0.setInvertSelection(false);
discretize0.listOptions();
discretize0.setOutputFormat();
String string0 = discretize0.getAttributeIndices();
assertEquals("first-last", string0);
discretize0.setInvertSelection(true);
String[] stringArray0 = new String[9];
stringArray0[0] = "first-last";
stringArray0[1] = "first-last";
stringArray0[2] = "es&HE}Xn/v_5R_P@E_<";
stringArray0[3] = "first-last";
stringArray0[4] = "No upper limit has been specified for range";
stringArray0[5] = "first-last";
stringArray0[6] = "first-last";
stringArray0[7] = "first-last";
stringArray0[8] = "}";
Filter.runFilter(discretize1, stringArray0);
assertEquals((-1.0), discretize1.getDesiredWeightOfInstancesPerInterval(), 0.01);
assertFalse(discretize1.getUseBinNumbers());
assertFalse(discretize1.getUseEqualFrequency());
assertFalse(discretize1.getFindNumBins());
assertEquals(10, discretize1.getBins());
assertFalse(discretize1.getMakeBinary());
discretize0.getDesiredWeightOfInstancesPerInterval();
String string1 = discretize0.findNumBinsTipText();
assertEquals("Optimize number of equal-width bins using leave-one-out. Doesn't work for equal-frequency binning", string1);
}
/**
//Test case number: 10
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
Discretize discretize0 = new Discretize();
Discretize discretize1 = (Discretize)Filter.makeCopy(discretize0);
discretize0.setInvertSelection(false);
discretize0.listOptions();
discretize0.setOutputFormat();
discretize0.getAttributeIndices();
discretize0.setInvertSelection(true);
String[] stringArray0 = new String[9];
stringArray0[0] = "first-last";
stringArray0[1] = "first-last";
stringArray0[2] = "es&HE}Xn/v_5R_P@E_<";
stringArray0[3] = "first-last";
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
stringArray0[4] = "No upper limit has been specified for range";
stringArray0[5] = "first-last";
stringArray0[6] = "first-last";
stringArray0[7] = "first-last";
discretize1.globalInfo();
AllFilter allFilter0 = new AllFilter();
String string0 = "&.Iz";
Discretize discretize2 = new Discretize();
// Undeclared exception!
try {
discretize2.getOutputFormat();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// No output format defined.
//
verifyException("weka.filters.Filter", e);
}
}
/**
//Test case number: 11
/*Coverage entropy=2.70805020110221
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
Discretize discretize0 = new Discretize("`u");
String[] stringArray0 = new String[1];
stringArray0[0] = "`u";
Discretize.main(stringArray0);
discretize0.getCapabilities();
assertEquals(10, discretize0.getBins());
assertFalse(discretize0.getUseEqualFrequency());
assertEquals((-1.0), discretize0.getDesiredWeightOfInstancesPerInterval(), 0.01);
}
/**
//Test case number: 12
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
Discretize discretize0 = new Discretize("SU$M<P1o");
discretize0.binsTipText();
discretize0.getCapabilities();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = null;
try {
instances0 = new Instances("", arrayList0, (-2141));
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Illegal Capacity: -2141
//
verifyException("java.util.ArrayList", e);
}
}
/**
//Test case number: 13
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
byte[] byteArray0 = new byte[4];
byteArray0[0] = (byte) (-26);
byteArray0[1] = (byte) (-111);
byteArray0[2] = (byte) (-27);
byteArray0[3] = (byte) (-67);
FileSystemHandling.appendDataToFile((EvoSuiteFile) null, byteArray0);
Discretize discretize0 = new Discretize();
String string0 = discretize0.useBinNumbersTipText();
assertFalse(discretize0.getUseEqualFrequency());
assertEquals(10, discretize0.getBins());
assertFalse(discretize0.getMakeBinary());
assertEquals("Use bin numbers (eg BXofY) rather than ranges for for discretized attributes", string0);
assertEquals((-1.0), discretize0.getDesiredWeightOfInstancesPerInterval(), 0.01);
assertFalse(discretize0.getUseBinNumbers());
assertFalse(discretize0.getFindNumBins());
}
/**
//Test case number: 14
/*Coverage entropy=2.70805020110221
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
String string0 = "Use bin numbers (eg BXofY) rather than ranges for for discretized attributes";
Discretize discretize0 = new Discretize("Use bin numbers (eg BXofY) rather than ranges for for discretized attributes");
int int0 = 0;
Discretize discretize1 = new Discretize();
discretize1.getOptions();
discretize1.getBinRangesString(0);
discretize0.getCutPoints(0);
// Undeclared exception!
try {
discretize0.findNumBins(0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 15
/*Coverage entropy=2.4036404106149494
*/
@Test(timeout = 4000)
public void test15() throws Throwable {
FileSystemHandling.appendStringToFile((EvoSuiteFile) null, "\tSpecifies the (maximum) number of bins to divide numeric attributes into.\n\t(default = 10)");
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "user.dir");
Discretize discretize0 = new Discretize();
discretize0.m_UseBinNumbers = true;
discretize0.getOptions();
// Undeclared exception!
try {
discretize0.calculateCutPoints();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 16
/*Coverage entropy=2.995732273553991
*/
@Test(timeout = 4000)
public void test16() throws Throwable {
Discretize discretize0 = new Discretize("7D");
String[] stringArray0 = discretize0.getOptions();
try {
Filter.filterFile(discretize0, stringArray0);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
//
// Unable to determine structure as arff (Reason: org.evosuite.runtime.mock.java.lang.MockThrowable: premature end of file, read Token[EOF], line 1).
// Filter options:
//
// -unset-class-temporarily
// \tUnsets the class index temporarily before the filter is
// \tapplied to the data.
// \t(default: no)
// -B <num>
// \tSpecifies the (maximum) number of bins to divide numeric attributes into.
// \t(default = 10)
// -M <num>
// \tSpecifies the desired weight of instances per bin for
// \tequal-frequency binning. If this is set to a positive
// \tnumber then the -B option will be ignored.
// \t(default = -1)
// -F
// \tUse equal-frequency instead of equal-width discretization.
// -O
// \tOptimize number of bins using leave-one-out estimate
// \tof estimated entropy (for equal-width discretization).
// \tIf this is set then the -B option will be ignored.
// -R <col1,col2-col4,...>
// \tSpecifies list of columns to Discretize. First and last are valid indexes.
// \t(default: first-last)
// -V
// \tInvert matching sense of column indexes.
// -D
// \tOutput binary attributes for discretized attributes.
// -Y
// \tUse bin numbers rather than ranges for discretized attributes.
//
// General options:
//
// -h
// \tGet help on available options.
// \t(use -b -h for help on batch mode.)
// -i <file>
// \tThe name of the file containing input instances.
// \tIf not supplied then instances will be read from stdin.
// -o <file>
// \tThe name of the file output instances will be written to.
// \tIf not supplied then instances will be written to stdout.
// -c <class index>
// \tThe number of the attribute to use as the class.
// \t\"first\" and \"last\" are also valid entries.
// \tIf not supplied then no class is assigned.
//
verifyException("weka.filters.Filter", e);
}
}
/**
//Test case number: 17
/*Coverage entropy=2.1458417525947544
*/
@Test(timeout = 4000)
public void test17() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval(5121.811174574201);
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("#PO;jA|`d|w4", arrayList0, 1);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[0];
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(3.4, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
BinarySparseInstance binarySparseInstance2 = new BinarySparseInstance((SparseInstance) binarySparseInstance1);
binarySparseInstance2.toString();
instances0.add((Instance) binarySparseInstance2);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, binarySparseInstance0.s_numericAfterDecimalPoint);
instances0.retainAll(instances1);
discretize0.setInputFormat(instances1);
int int0 = (-1202);
// Undeclared exception!
try {
discretize0.calculateCutPointsByEqualFrequencyBinning(int0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 18
/*Coverage entropy=2.458311329683084
*/
@Test(timeout = 4000)
public void test18() throws Throwable {
Discretize discretize0 = new Discretize("\tOptimize number of bins using leave-one-out estimate\n\tof estimated entropy (for equal-width discretization).\n\tIf this is set then the -B option will be ignored.");
discretize0.m_IgnoreClass = true;
discretize0.setOutputFormat();
String[] stringArray0 = discretize0.getOptions();
assertEquals(7, stringArray0.length);
assertEquals((-1.0), discretize0.getDesiredWeightOfInstancesPerInterval(), 0.01);
assertEquals(10, discretize0.getBins());
}
/**
//Test case number: 19
/*Coverage entropy=2.5796246736085746
*/
@Test(timeout = 4000)
public void test19() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("=Wg&/{8D5", arrayList0, 1);
String string0 = "fS QPfX.8X'Tl?jEB";
Attribute attribute0 = new Attribute("fS QPfX.8X'Tl?jEB");
double[] doubleArray0 = new double[5];
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(4, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
String string1 = binarySparseInstance1.toString();
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
int int0 = 1033;
Instances instances1 = new Instances(instances0, int0);
instances0.retainAll(arrayList0);
discretize0.setInputFormat(instances0);
String[] stringArray0 = new String[6];
stringArray0[0] = instances0.ARFF_RELATION;
stringArray0[1] = attribute0.ARFF_ATTRIBUTE_REAL;
stringArray0[2] = attribute0.ARFF_ATTRIBUTE_STRING;
stringArray0[3] = string1;
stringArray0[4] = attribute0.ARFF_ATTRIBUTE_REAL;
stringArray0[5] = string0;
try {
Filter.filterFile(discretize0, stringArray0);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
//
// Illegal options: @relation real string {},{4} real fS QPfX.8X'Tl?jEB
// Filter options:
//
// -unset-class-temporarily
// \tUnsets the class index temporarily before the filter is
// \tapplied to the data.
// \t(default: no)
// -B <num>
// \tSpecifies the (maximum) number of bins to divide numeric attributes into.
// \t(default = 10)
// -M <num>
// \tSpecifies the desired weight of instances per bin for
// \tequal-frequency binning. If this is set to a positive
// \tnumber then the -B option will be ignored.
// \t(default = -1)
// -F
// \tUse equal-frequency instead of equal-width discretization.
// -O
// \tOptimize number of bins using leave-one-out estimate
// \tof estimated entropy (for equal-width discretization).
// \tIf this is set then the -B option will be ignored.
// -R <col1,col2-col4,...>
// \tSpecifies list of columns to Discretize. First and last are valid indexes.
// \t(default: first-last)
// -V
// \tInvert matching sense of column indexes.
// -D
// \tOutput binary attributes for discretized attributes.
// -Y
// \tUse bin numbers rather than ranges for discretized attributes.
//
// General options:
//
// -h
// \tGet help on available options.
// \t(use -b -h for help on batch mode.)
// -i <file>
// \tThe name of the file containing input instances.
// \tIf not supplied then instances will be read from stdin.
// -o <file>
// \tThe name of the file output instances will be written to.
// \tIf not supplied then instances will be written to stdout.
// -c <class index>
// \tThe number of the attribute to use as the class.
// \t\"first\" and \"last\" are also valid entries.
// \tIf not supplied then no class is assigned.
//
verifyException("weka.filters.Filter", e);
}
}
/**
//Test case number: 20
/*Coverage entropy=2.259065077425979
*/
@Test(timeout = 4000)
public void test20() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
doubleArray0[1] = (-1144.72938352);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 2;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
Discretize discretize1 = new Discretize(".bsi");
discretize1.m_DesiredWeightOfInstancesPerInterval = 6.7;
discretize0.useEqualFrequencyTipText();
discretize0.calculateCutPoints();
// Undeclared exception!
try {
discretize0.input(binarySparseInstance0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 21
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test21() throws Throwable {
Discretize discretize0 = new Discretize("Value of \"position\": ");
discretize0.setAttributeIndices("Value of \"position\": ");
discretize0.setInvertSelection(false);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
discretize0.m_ClassIndex = 887;
discretize0.m_MakeBinary = true;
discretize0.getCapabilities();
SystemInUtil.addInputLine("weka/core/Capabilities.props");
FileSystemHandling fileSystemHandling0 = new FileSystemHandling();
discretize0.setAttributeIndices("weka/core/Capabilities.props");
int int0 = (-2436);
// Undeclared exception!
try {
discretize0.calculateCutPointsByEqualFrequencyBinning((-2436));
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.core.Instances", e);
}
}
/**
//Test case number: 22
/*Coverage entropy=2.3693821196946767
*/
@Test(timeout = 4000)
public void test22() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
discretize0.listOptions();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("/home/ubuntu/wekafiles/props/Capabilities.props");
FileSystemHandling.shouldThrowIOException(evoSuiteFile0);
doubleArray0[1] = (-1144.72938352);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 2;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
Discretize discretize1 = new Discretize(".bsi");
Filter.makeCopy(discretize1);
instances1.stream();
discretize1.m_DesiredWeightOfInstancesPerInterval = 6.7;
discretize0.useEqualFrequencyTipText();
// Undeclared exception!
try {
discretize0.findNumBins(34);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 23
/*Coverage entropy=2.5400363038209806
*/
@Test(timeout = 4000)
public void test23() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setMakeBinary(true);
discretize0.getOptions();
// Undeclared exception!
try {
discretize0.findNumBins(2387);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 24
/*Coverage entropy=2.678508000514082
*/
@Test(timeout = 4000)
public void test24() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
doubleArray0[1] = (-1144.72938352);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 1;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
Discretize discretize1 = new Discretize(".bsi");
discretize1.m_DesiredWeightOfInstancesPerInterval = 6.7;
discretize0.calculateCutPoints();
Discretize discretize2 = new Discretize();
discretize2.getBinRangesString((-2134061872));
discretize0.setOutputFormat();
}
/**
//Test case number: 25
/*Coverage entropy=2.7467059471170976
*/
@Test(timeout = 4000)
public void test25() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
discretize0.setBins((-2105));
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
doubleArray0[1] = (-1144.72938352);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 1;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
Discretize discretize1 = new Discretize(".bsi");
discretize1.m_DesiredWeightOfInstancesPerInterval = 6.7;
discretize0.calculateCutPoints();
Discretize discretize2 = new Discretize();
discretize2.getBinRangesString((-2134061872));
discretize0.setOutputFormat();
discretize1.getBinRangesString(0);
discretize2.getOptions();
try {
discretize1.setInputFormat(instances0);
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Invalid range list at .bsi
//
verifyException("weka.core.Range", e);
}
}
/**
//Test case number: 26
/*Coverage entropy=2.1960516973750748
*/
@Test(timeout = 4000)
public void test26() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
discretize0.listOptions();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(4, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance0);
Attribute attribute1 = new Attribute("relational", (String) null, (-136));
arrayList0.add(attribute1);
Instances instances1 = new Instances(instances0, (-2020));
instances0.retainAll(instances1);
discretize0.setInputFormat(instances0);
Discretize discretize1 = new Discretize("1#2z6Ba~");
discretize0.calculateCutPoints();
Discretize discretize2 = new Discretize();
// Undeclared exception!
try {
discretize0.getBinRangesString(2);
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// 2
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 27
/*Coverage entropy=2.791080639311774
*/
@Test(timeout = 4000)
public void test27() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.setDesiredWeightOfInstancesPerInterval((-1144.72938352));
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
doubleArray0[1] = (-1144.72938352);
discretize0.setUseEqualFrequency(false);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 1;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
Discretize discretize1 = new Discretize(".bsi");
discretize0.batchFinished();
// Undeclared exception!
try {
discretize1.findNumBins((-2134061872));
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 28
/*Coverage entropy=2.739997406578141
*/
@Test(timeout = 4000)
public void test28() throws Throwable {
Discretize discretize0 = new Discretize();
discretize0.listOptions();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(4, doubleArray0);
Attribute.typeToString(attribute0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance0);
Attribute attribute1 = new Attribute("relational", (String) null, (-136));
arrayList0.add(attribute1);
instances0.retainAll(instances0);
discretize0.setInputFormat(instances0);
Discretize discretize1 = new Discretize("1#2z6Ba~");
discretize0.calculateCutPoints();
Discretize discretize2 = new Discretize();
discretize1.setOutputFormat();
discretize0.setOutputFormat();
discretize0.convertInstance(binarySparseInstance1);
// Undeclared exception!
try {
discretize0.getBinRangesString(1);
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// 1
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 29
/*Coverage entropy=2.458311329683084
*/
@Test(timeout = 4000)
public void test29() throws Throwable {
Discretize discretize0 = new Discretize();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances((String) null, arrayList0, 2710);
discretize0.m_FindNumBins = true;
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 2;
doubleArray0[1] = (double) 0;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
instances1.removeAll(instances0);
Discretize discretize1 = new Discretize(".bsi");
EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("/home/ubuntu/wekafiles/props/Capabilities.props");
byte[] byteArray0 = new byte[1];
byteArray0[0] = (byte)76;
FileSystemHandling.appendDataToFile(evoSuiteFile0, byteArray0);
arrayList0.stream();
discretize1.m_DesiredWeightOfInstancesPerInterval = 6.7;
discretize0.calculateCutPoints();
// Undeclared exception!
try {
discretize0.input(binarySparseInstance0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 30
/*Coverage entropy=2.011242441972426
*/
@Test(timeout = 4000)
public void test30() throws Throwable {
EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("/home/ubuntu/wekafiles/props");
FileSystemHandling.createFolder(evoSuiteFile0);
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances(" // create new instance\n", arrayList0, 1);
Attribute attribute0 = new Attribute((String) null);
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
binarySparseInstance1.toString();
instances0.add((Instance) binarySparseInstance0);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 1);
LinkedList<Object> linkedList0 = new LinkedList<Object>();
instances0.retainAll(linkedList0);
Discretize discretize0 = new Discretize();
discretize0.setInputFormat(instances1);
Discretize discretize1 = new Discretize("@end");
discretize0.calculateCutPoints();
Discretize discretize2 = new Discretize("-M <num>");
// Undeclared exception!
try {
discretize0.batchFinished();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// No output instance format defined
//
verifyException("weka.filters.Filter", e);
}
}
/**
//Test case number: 31
/*Coverage entropy=3.0280290733074104
*/
@Test(timeout = 4000)
public void test31() throws Throwable {
Discretize discretize0 = new Discretize();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
doubleArray0[1] = (-1144.72938352);
discretize0.setUseEqualFrequency(false);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 1;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(".bsi", arrayList0, 1);
instances1.retainAll(arrayList0);
discretize0.setInputFormat(instances1);
discretize0.batchFinished();
discretize0.convertInstance(binarySparseInstance0);
discretize0.input(binarySparseInstance1);
// Undeclared exception!
try {
discretize0.getCutPoints(68);
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// 68
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 32
/*Coverage entropy=2.6093973892808866
*/
@Test(timeout = 4000)
public void test32() throws Throwable {
Discretize discretize0 = new Discretize();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances("", arrayList0, 2710);
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 4;
doubleArray0[1] = (double) 0;
doubleArray0[2] = (-1144.72938352);
doubleArray0[2] = (-1144.72938352);
discretize0.setUseEqualFrequency(false);
doubleArray0[4] = (-1144.72938352);
doubleArray0[5] = (double) 1;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
discretize0.isNewBatch();
discretize0.setInputFormat(instances1);
discretize0.batchFinished();
arrayList0.stream();
discretize0.calculateCutPoints();
discretize0.input(binarySparseInstance1);
discretize0.input(binarySparseInstance0);
}
/**
//Test case number: 33
/*Coverage entropy=2.143952200643869
*/
@Test(timeout = 4000)
public void test33() throws Throwable {
EvoSuiteFile evoSuiteFile0 = new EvoSuiteFile("/home/ubuntu/wekafiles/props");
FileSystemHandling.createFolder(evoSuiteFile0);
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances(" // create new instance\n", arrayList0, 1);
double[] doubleArray0 = new double[2];
doubleArray0[0] = (double) 1;
doubleArray0[1] = (-1367.7770867021138);
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(1, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance0);
LinkedList<String> linkedList0 = new LinkedList<String>();
Properties properties0 = new Properties();
ProtectedProperties protectedProperties0 = new ProtectedProperties(properties0);
ProtectedProperties protectedProperties1 = new ProtectedProperties(protectedProperties0);
Attribute attribute0 = new Attribute("Parameters first and/or toCopy out of range", linkedList0, protectedProperties1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, (-1717986916));
instances1.retainAll(linkedList0);
Discretize discretize0 = new Discretize();
discretize0.setInputFormat(instances0);
Instances instances2 = new Instances(instances1, 1, (-2134061872));
instances2.removeAll(instances1);
Discretize discretize1 = new Discretize("Str");
byte[] byteArray0 = new byte[0];
FileSystemHandling.appendDataToFile(evoSuiteFile0, byteArray0);
arrayList0.stream();
discretize0.calculateCutPoints();
// Undeclared exception!
try {
discretize0.input(binarySparseInstance0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
/**
//Test case number: 34
/*Coverage entropy=2.5283233635280706
*/
@Test(timeout = 4000)
public void test34() throws Throwable {
Discretize discretize0 = new Discretize();
ArrayList<Attribute> arrayList0 = new ArrayList<Attribute>();
Instances instances0 = new Instances((String) null, arrayList0, 2710);
discretize0.m_FindNumBins = true;
Attribute attribute0 = new Attribute(".arff");
double[] doubleArray0 = new double[6];
doubleArray0[0] = (double) 2;
doubleArray0[1] = (double) 0;
BinarySparseInstance binarySparseInstance0 = new BinarySparseInstance(2, doubleArray0);
BinarySparseInstance binarySparseInstance1 = new BinarySparseInstance((SparseInstance) binarySparseInstance0);
instances0.add((Instance) binarySparseInstance1);
arrayList0.add(attribute0);
Instances instances1 = new Instances(instances0, 2710);
instances1.retainAll(arrayList0);
Instances instances2 = new Instances(instances0, 1564);
instances2.retainAll(instances0);
discretize0.setInputFormat(instances0);
Discretize discretize1 = new Discretize("&^zEdD;n-`j)t");
discretize0.batchFinished();
// Undeclared exception!
try {
discretize1.findNumBins(0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("weka.filters.unsupervised.attribute.Discretize", e);
}
}
}
|
corpusculejs/corpuscule
|
packages/storeon/src/utils.js
|
<filename>packages/storeon/src/utils.js<gh_stars>10-100
import {createContextToken} from '@corpuscule/context';
import createTokenRegisry from '@corpuscule/utils/lib/tokenRegistry';
export const [createStoreonToken, tokenRegistry] = createTokenRegisry(
() => new WeakMap(),
createContextToken,
);
|
JarredStanford/JarredStanford.github.io
|
node_modules/grommet-controls/themes/black.js
|
import { deepFreeze, deepMerge } from 'grommet/utils';
import base from './base';
import colorsFromArray from './colorsFromArray';
var brandColor = '#000000';
var accentColors = ['#FF4081', '#4eadeb', '#56cf98', '#765bba'];
var neutralColors = ['#a4c400', '#006766', '#f3741c', '#8F6C53', '#e82121'];
var backgroundColor = '#5e5e5e';
var colors = {
'active': {
light: '#3a82b1',
dark: '#52b7f9',
},
'background': '#444444',
'brand': brandColor,
'focus': accentColors[0],
'control': {
'dark': '#f8f8f8',
'light': '#444444',
},
};
colorsFromArray(colors, accentColors, 'accent');
colorsFromArray(colors, neutralColors, 'neutral');
export default deepFreeze(deepMerge(base, {
global: {
colors: colors,
drop: {
background: '#444444',
},
font: {
family: "'Inconsolata', monospace",
size: '16px',
},
hover: {
background: {
light: '#dddddd',
dark: '#222222',
},
color: {
light: '#333333',
dark: '#ffffff',
},
},
control: {
border: {
radius: '0px',
},
},
},
icon: {
colors: colors,
},
anchor: {
color: {
light: '#0a466e',
dark: '#4eadeb',
},
},
button: {
border: {
radius: '0px',
},
primary: {
color: {
light: '#0a466e',
dark: '#4eadeb',
},
},
},
checkBox: {
check: {
radius: '0px',
},
toggle: {
radius: '0px',
},
},
layer: {
background: backgroundColor,
},
rangeInput: {
track: {
color: {
'dark': '#3a82b1',
'light': '#52b7f9',
},
},
},
}));
|
moyumoyu/dcmtk-openjpeg
|
dcmjpeg/libsrc/pi.cxx
|
/*
* Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2007, Professor <NAME>
* Copyright (c) 2001-2003, <NAME>
* Copyright (c) 2002-2003, <NAME>
* Copyright (c) 2003-2007, <NAME> and <NAME>
* Copyright (c) 2005, <NAME>, FreeImage Team
* Copyright (c) 2006-2007, <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 "opj_includes.h"
/** @defgroup PI PI - Implementation of a packet iterator */
/*@{*/
/** @name Local static functions */
/*@{*/
/**
Get next packet in layer-resolution-component-precinct order.
@param pi packet iterator to modify
@return returns 0 if pi pointed to the last packet or else returns 1
*/
static int pi_next_lrcp(opj_pi_iterator_t * pi);
/**
Get next packet in resolution-layer-component-precinct order.
@param pi packet iterator to modify
@return returns 0 if pi pointed to the last packet or else returns 1
*/
static int pi_next_rlcp(opj_pi_iterator_t * pi);
/**
Get next packet in resolution-precinct-component-layer order.
@param pi packet iterator to modify
@return returns 0 if pi pointed to the last packet or else returns 1
*/
static int pi_next_rpcl(opj_pi_iterator_t * pi);
/**
Get next packet in precinct-component-resolution-layer order.
@param pi packet iterator to modify
@return returns 0 if pi pointed to the last packet or else returns 1
*/
static int pi_next_pcrl(opj_pi_iterator_t * pi);
/**
Get next packet in component-precinct-resolution-layer order.
@param pi packet iterator to modify
@return returns 0 if pi pointed to the last packet or else returns 1
*/
static int pi_next_cprl(opj_pi_iterator_t * pi);
/*@}*/
/*@}*/
/*
==========================================================
local functions
==========================================================
*/
static int pi_next_lrcp(opj_pi_iterator_t * pi) {
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1;
pi->resno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on){
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return 1;
}
LABEL_SKIP:;
}
}
}
}
return 0;
}
static int pi_next_rlcp(opj_pi_iterator_t * pi) {
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if(!pi->tp_on){
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return 1;
}
LABEL_SKIP:;
}
}
}
}
return 0;
}
static int pi_next_rpcl(opj_pi_iterator_t * pi) {
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on){
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpx))))){
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){
continue;
}
if ((res->pw==0)||(res->pw==0)) continue;
if ((trx0==trx1)||(try0==try1)) continue;
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return 1;
}
LABEL_SKIP:;
}
}
}
}
}
return 0;
}
static int pi_next_pcrl(opj_pi_iterator_t * pi) {
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on){
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpx))))){
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){
continue;
}
if ((res->pw==0)||(res->pw==0)) continue;
if ((trx0==trx1)||(try0==try1)) continue;
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return 1;
}
LABEL_SKIP:;
}
}
}
}
}
return 0;
}
static int pi_next_cprl(opj_pi_iterator_t * pi) {
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
if (!pi->tp_on){
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpx))))){
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){
continue;
}
if ((res->pw==0)||(res->pw==0)) continue;
if ((trx0==trx1)||(try0==try1)) continue;
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return 1;
}
LABEL_SKIP:;
}
}
}
}
}
return 0;
}
/*
==========================================================
Packet iterator interface
==========================================================
*/
opj_pi_iterator_t *pi_create_decode(opj_image_t *image, opj_cp_t *cp, int tileno) {
int p, q;
int compno, resno, pino;
opj_pi_iterator_t *pi = NULL;
opj_tcp_t *tcp = NULL;
opj_tccp_t *tccp = NULL;
tcp = &cp->tcps[tileno];
pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t));
if(!pi) {
/* TODO: throw an error */
return NULL;
}
for (pino = 0; pino < tcp->numpocs + 1; pino++) { /* change */
int maxres = 0;
int maxprec = 0;
p = tileno % cp->tw;
q = tileno / cp->tw;
pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0);
pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0);
pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1);
pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1);
pi[pino].numcomps = image->numcomps;
pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t));
if(!pi[pino].comps) {
/* TODO: throw an error */
pi_destroy(pi, cp, tileno);
return NULL;
}
for (compno = 0; compno < pi->numcomps; compno++) {
int tcx0, tcy0, tcx1, tcy1;
opj_pi_comp_t *comp = &pi[pino].comps[compno];
tccp = &tcp->tccps[compno];
comp->dx = image->comps[compno].dx;
comp->dy = image->comps[compno].dy;
comp->numresolutions = tccp->numresolutions;
comp->resolutions = (opj_pi_resolution_t*) opj_calloc(comp->numresolutions, sizeof(opj_pi_resolution_t));
if(!comp->resolutions) {
/* TODO: throw an error */
pi_destroy(pi, cp, tileno);
return NULL;
}
tcx0 = int_ceildiv(pi->tx0, comp->dx);
tcy0 = int_ceildiv(pi->ty0, comp->dy);
tcx1 = int_ceildiv(pi->tx1, comp->dx);
tcy1 = int_ceildiv(pi->ty1, comp->dy);
if (comp->numresolutions > maxres) {
maxres = comp->numresolutions;
}
for (resno = 0; resno < comp->numresolutions; resno++) {
int levelno;
int rx0, ry0, rx1, ry1;
int px0, py0, px1, py1;
opj_pi_resolution_t *res = &comp->resolutions[resno];
if (tccp->csty & J2K_CCP_CSTY_PRT) {
res->pdx = tccp->prcw[resno];
res->pdy = tccp->prch[resno];
} else {
res->pdx = 15;
res->pdy = 15;
}
levelno = comp->numresolutions - 1 - resno;
rx0 = int_ceildivpow2(tcx0, levelno);
ry0 = int_ceildivpow2(tcy0, levelno);
rx1 = int_ceildivpow2(tcx1, levelno);
ry1 = int_ceildivpow2(tcy1, levelno);
px0 = int_floordivpow2(rx0, res->pdx) << res->pdx;
py0 = int_floordivpow2(ry0, res->pdy) << res->pdy;
px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx;
py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy;
res->pw = (rx0==rx1)?0:((px1 - px0) >> res->pdx);
res->ph = (ry0==ry1)?0:((py1 - py0) >> res->pdy);
if (res->pw*res->ph > maxprec) {
maxprec = res->pw*res->ph;
}
}
}
tccp = &tcp->tccps[0];
pi[pino].step_p = 1;
pi[pino].step_c = maxprec * pi[pino].step_p;
pi[pino].step_r = image->numcomps * pi[pino].step_c;
pi[pino].step_l = maxres * pi[pino].step_r;
if (pino == 0) {
pi[pino].include = (short int*) opj_calloc(image->numcomps * maxres * tcp->numlayers * maxprec, sizeof(short int));
if(!pi[pino].include) {
/* TODO: throw an error */
pi_destroy(pi, cp, tileno);
return NULL;
}
}
else {
pi[pino].include = pi[pino - 1].include;
}
if (tcp->POC == 0) {
pi[pino].first = 1;
pi[pino].poc.resno0 = 0;
pi[pino].poc.compno0 = 0;
pi[pino].poc.layno1 = tcp->numlayers;
pi[pino].poc.resno1 = maxres;
pi[pino].poc.compno1 = image->numcomps;
pi[pino].poc.prg = tcp->prg;
} else {
pi[pino].first = 1;
pi[pino].poc.resno0 = tcp->pocs[pino].resno0;
pi[pino].poc.compno0 = tcp->pocs[pino].compno0;
pi[pino].poc.layno1 = tcp->pocs[pino].layno1;
pi[pino].poc.resno1 = tcp->pocs[pino].resno1;
pi[pino].poc.compno1 = tcp->pocs[pino].compno1;
pi[pino].poc.prg = tcp->pocs[pino].prg;
}
pi[pino].poc.layno0 = 0;
pi[pino].poc.precno0 = 0;
pi[pino].poc.precno1 = maxprec;
}
return pi;
}
opj_pi_iterator_t *pi_initialise_encode(opj_image_t *image, opj_cp_t *cp, int tileno, J2K_T2_MODE t2_mode){
int p, q, pino;
int compno, resno;
int maxres = 0;
int maxprec = 0;
opj_pi_iterator_t *pi = NULL;
opj_tcp_t *tcp = NULL;
opj_tccp_t *tccp = NULL;
tcp = &cp->tcps[tileno];
pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t));
if(!pi) { return NULL;}
pi->tp_on = cp->tp_on;
for(pino = 0;pino < tcp->numpocs+1 ; pino ++){
p = tileno % cp->tw;
q = tileno / cp->tw;
pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0);
pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0);
pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1);
pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1);
pi[pino].numcomps = image->numcomps;
pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t));
if(!pi[pino].comps) {
pi_destroy(pi, cp, tileno);
return NULL;
}
for (compno = 0; compno < pi[pino].numcomps; compno++) {
int tcx0, tcy0, tcx1, tcy1;
opj_pi_comp_t *comp = &pi[pino].comps[compno];
tccp = &tcp->tccps[compno];
comp->dx = image->comps[compno].dx;
comp->dy = image->comps[compno].dy;
comp->numresolutions = tccp->numresolutions;
comp->resolutions = (opj_pi_resolution_t*) opj_malloc(comp->numresolutions * sizeof(opj_pi_resolution_t));
if(!comp->resolutions) {
pi_destroy(pi, cp, tileno);
return NULL;
}
tcx0 = int_ceildiv(pi[pino].tx0, comp->dx);
tcy0 = int_ceildiv(pi[pino].ty0, comp->dy);
tcx1 = int_ceildiv(pi[pino].tx1, comp->dx);
tcy1 = int_ceildiv(pi[pino].ty1, comp->dy);
if (comp->numresolutions > maxres) {
maxres = comp->numresolutions;
}
for (resno = 0; resno < comp->numresolutions; resno++) {
int levelno;
int rx0, ry0, rx1, ry1;
int px0, py0, px1, py1;
opj_pi_resolution_t *res = &comp->resolutions[resno];
if (tccp->csty & J2K_CCP_CSTY_PRT) {
res->pdx = tccp->prcw[resno];
res->pdy = tccp->prch[resno];
} else {
res->pdx = 15;
res->pdy = 15;
}
levelno = comp->numresolutions - 1 - resno;
rx0 = int_ceildivpow2(tcx0, levelno);
ry0 = int_ceildivpow2(tcy0, levelno);
rx1 = int_ceildivpow2(tcx1, levelno);
ry1 = int_ceildivpow2(tcy1, levelno);
px0 = int_floordivpow2(rx0, res->pdx) << res->pdx;
py0 = int_floordivpow2(ry0, res->pdy) << res->pdy;
px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx;
py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy;
res->pw = (rx0==rx1)?0:((px1 - px0) >> res->pdx);
res->ph = (ry0==ry1)?0:((py1 - py0) >> res->pdy);
if (res->pw*res->ph > maxprec) {
maxprec = res->pw * res->ph;
}
}
}
tccp = &tcp->tccps[0];
pi[pino].step_p = 1;
pi[pino].step_c = maxprec * pi[pino].step_p;
pi[pino].step_r = image->numcomps * pi[pino].step_c;
pi[pino].step_l = maxres * pi[pino].step_r;
for (compno = 0; compno < pi->numcomps; compno++) {
opj_pi_comp_t *comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
opj_pi_resolution_t *res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi[pino].dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi[pino].dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
if (pino == 0) {
pi[pino].include = (short int*) opj_calloc(tcp->numlayers * pi[pino].step_l, sizeof(short int));
if(!pi[pino].include) {
pi_destroy(pi, cp, tileno);
return NULL;
}
}
else {
pi[pino].include = pi[pino - 1].include;
}
/* Generation of boundaries for each prog flag*/
if(tcp->POC && ( cp->cinema || ((!cp->cinema) && (t2_mode == FINAL_PASS)))){
tcp->pocs[pino].compS= tcp->pocs[pino].compno0;
tcp->pocs[pino].compE= tcp->pocs[pino].compno1;
tcp->pocs[pino].resS = tcp->pocs[pino].resno0;
tcp->pocs[pino].resE = tcp->pocs[pino].resno1;
tcp->pocs[pino].layE = tcp->pocs[pino].layno1;
tcp->pocs[pino].prg = tcp->pocs[pino].prg1;
if (pino > 0)
tcp->pocs[pino].layS = (tcp->pocs[pino].layE > tcp->pocs[pino - 1].layE) ? tcp->pocs[pino - 1].layE : 0;
}else {
tcp->pocs[pino].compS= 0;
tcp->pocs[pino].compE= image->numcomps;
tcp->pocs[pino].resS = 0;
tcp->pocs[pino].resE = maxres;
tcp->pocs[pino].layS = 0;
tcp->pocs[pino].layE = tcp->numlayers;
tcp->pocs[pino].prg = tcp->prg;
}
tcp->pocs[pino].prcS = 0;
tcp->pocs[pino].prcE = maxprec;;
tcp->pocs[pino].txS = pi[pino].tx0;
tcp->pocs[pino].txE = pi[pino].tx1;
tcp->pocs[pino].tyS = pi[pino].ty0;
tcp->pocs[pino].tyE = pi[pino].ty1;
tcp->pocs[pino].dx = pi[pino].dx;
tcp->pocs[pino].dy = pi[pino].dy;
}
return pi;
}
void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno) {
int compno, pino;
opj_tcp_t *tcp = &cp->tcps[tileno];
if(pi) {
for (pino = 0; pino < tcp->numpocs + 1; pino++) {
if(pi[pino].comps) {
for (compno = 0; compno < pi->numcomps; compno++) {
opj_pi_comp_t *comp = &pi[pino].comps[compno];
if(comp->resolutions) {
opj_free(comp->resolutions);
}
}
opj_free(pi[pino].comps);
}
}
if(pi->include) {
opj_free(pi->include);
}
opj_free(pi);
}
}
int pi_next(opj_pi_iterator_t * pi) {
switch (pi->poc.prg) {
case LRCP:
return pi_next_lrcp(pi);
case RLCP:
return pi_next_rlcp(pi);
case RPCL:
return pi_next_rpcl(pi);
case PCRL:
return pi_next_pcrl(pi);
case CPRL:
return pi_next_cprl(pi);
case PROG_UNKNOWN:
return 0;
}
return 0;
}
int pi_create_encode( opj_pi_iterator_t *pi, opj_cp_t *cp,int tileno, int pino,int tpnum, int tppos, J2K_T2_MODE t2_mode,int cur_totnum_tp){
char prog[4];
int i;
int incr_top=1,resetX=0;
opj_tcp_t *tcps =&cp->tcps[tileno];
opj_poc_t *tcp= &tcps->pocs[pino];
pi[pino].first = 1;
pi[pino].poc.prg = tcp->prg;
switch(tcp->prg){
case CPRL: strncpy(prog, "CPRL",4);
break;
case LRCP: strncpy(prog, "LRCP",4);
break;
case PCRL: strncpy(prog, "PCRL",4);
break;
case RLCP: strncpy(prog, "RLCP",4);
break;
case RPCL: strncpy(prog, "RPCL",4);
break;
case PROG_UNKNOWN:
return 1;
}
if(!(cp->tp_on && ((!cp->cinema && (t2_mode == FINAL_PASS)) || cp->cinema))){
pi[pino].poc.resno0 = tcp->resS;
pi[pino].poc.resno1 = tcp->resE;
pi[pino].poc.compno0 = tcp->compS;
pi[pino].poc.compno1 = tcp->compE;
pi[pino].poc.layno0 = tcp->layS;
pi[pino].poc.layno1 = tcp->layE;
pi[pino].poc.precno0 = tcp->prcS;
pi[pino].poc.precno1 = tcp->prcE;
pi[pino].poc.tx0 = tcp->txS;
pi[pino].poc.ty0 = tcp->tyS;
pi[pino].poc.tx1 = tcp->txE;
pi[pino].poc.ty1 = tcp->tyE;
}else {
if( tpnum < cur_totnum_tp){
for(i=3;i>=0;i--){
switch(prog[i]){
case 'C':
if (i > tppos){
pi[pino].poc.compno0 = tcp->compS;
pi[pino].poc.compno1 = tcp->compE;
}else{
if (tpnum == 0){
tcp->comp_t = tcp->compS;
pi[pino].poc.compno0 = tcp->comp_t;
pi[pino].poc.compno1 = tcp->comp_t+1;
tcp->comp_t+=1;
}else{
if (incr_top == 1){
if(tcp->comp_t ==tcp->compE){
tcp->comp_t = tcp->compS;
pi[pino].poc.compno0 = tcp->comp_t;
pi[pino].poc.compno1 = tcp->comp_t+1;
tcp->comp_t+=1;
incr_top=1;
}else{
pi[pino].poc.compno0 = tcp->comp_t;
pi[pino].poc.compno1 = tcp->comp_t+1;
tcp->comp_t+=1;
incr_top=0;
}
}else{
pi[pino].poc.compno0 = tcp->comp_t-1;
pi[pino].poc.compno1 = tcp->comp_t;
}
}
}
break;
case 'R':
if (i > tppos){
pi[pino].poc.resno0 = tcp->resS;
pi[pino].poc.resno1 = tcp->resE;
}else{
if (tpnum == 0){
tcp->res_t = tcp->resS;
pi[pino].poc.resno0 = tcp->res_t;
pi[pino].poc.resno1 = tcp->res_t+1;
tcp->res_t+=1;
}else{
if (incr_top == 1){
if(tcp->res_t==tcp->resE){
tcp->res_t = tcp->resS;
pi[pino].poc.resno0 = tcp->res_t;
pi[pino].poc.resno1 = tcp->res_t+1;
tcp->res_t+=1;
incr_top=1;
}else{
pi[pino].poc.resno0 = tcp->res_t;
pi[pino].poc.resno1 = tcp->res_t+1;
tcp->res_t+=1;
incr_top=0;
}
}else{
pi[pino].poc.resno0 = tcp->res_t - 1;
pi[pino].poc.resno1 = tcp->res_t;
}
}
}
break;
case 'L':
if (i > tppos){
pi[pino].poc.layno0 = tcp->layS;
pi[pino].poc.layno1 = tcp->layE;
}else{
if (tpnum == 0){
tcp->lay_t = tcp->layS;
pi[pino].poc.layno0 = tcp->lay_t;
pi[pino].poc.layno1 = tcp->lay_t+1;
tcp->lay_t+=1;
}else{
if (incr_top == 1){
if(tcp->lay_t == tcp->layE){
tcp->lay_t = tcp->layS;
pi[pino].poc.layno0 = tcp->lay_t;
pi[pino].poc.layno1 = tcp->lay_t+1;
tcp->lay_t+=1;
incr_top=1;
}else{
pi[pino].poc.layno0 = tcp->lay_t;
pi[pino].poc.layno1 = tcp->lay_t+1;
tcp->lay_t+=1;
incr_top=0;
}
}else{
pi[pino].poc.layno0 = tcp->lay_t - 1;
pi[pino].poc.layno1 = tcp->lay_t;
}
}
}
break;
case 'P':
switch(tcp->prg){
case LRCP:
case RLCP:
if (i > tppos){
pi[pino].poc.precno0 = tcp->prcS;
pi[pino].poc.precno1 = tcp->prcE;
}else{
if (tpnum == 0){
tcp->prc_t = tcp->prcS;
pi[pino].poc.precno0 = tcp->prc_t;
pi[pino].poc.precno1 = tcp->prc_t+1;
tcp->prc_t+=1;
}else{
if (incr_top == 1){
if(tcp->prc_t == tcp->prcE){
tcp->prc_t = tcp->prcS;
pi[pino].poc.precno0 = tcp->prc_t;
pi[pino].poc.precno1 = tcp->prc_t+1;
tcp->prc_t+=1;
incr_top=1;
}else{
pi[pino].poc.precno0 = tcp->prc_t;
pi[pino].poc.precno1 = tcp->prc_t+1;
tcp->prc_t+=1;
incr_top=0;
}
}else{
pi[pino].poc.precno0 = tcp->prc_t - 1;
pi[pino].poc.precno1 = tcp->prc_t;
}
}
}
break;
default:
if (i > tppos){
pi[pino].poc.tx0 = tcp->txS;
pi[pino].poc.ty0 = tcp->tyS;
pi[pino].poc.tx1 = tcp->txE;
pi[pino].poc.ty1 = tcp->tyE;
}else{
if (tpnum == 0){
tcp->tx0_t = tcp->txS;
tcp->ty0_t = tcp->tyS;
pi[pino].poc.tx0 = tcp->tx0_t;
pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx);
pi[pino].poc.ty0 = tcp->ty0_t;
pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
tcp->tx0_t = pi[pino].poc.tx1;
tcp->ty0_t = pi[pino].poc.ty1;
}else{
if (incr_top == 1){
if(tcp->tx0_t >= tcp->txE){
if(tcp->ty0_t >= tcp->tyE){
tcp->ty0_t = tcp->tyS;
pi[pino].poc.ty0 = tcp->ty0_t;
pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
tcp->ty0_t = pi[pino].poc.ty1;
incr_top=1;resetX=1;
}else{
pi[pino].poc.ty0 = tcp->ty0_t;
pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
tcp->ty0_t = pi[pino].poc.ty1;
incr_top=0;resetX=1;
}
if(resetX==1){
tcp->tx0_t = tcp->txS;
pi[pino].poc.tx0 = tcp->tx0_t;
pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx);
tcp->tx0_t = pi[pino].poc.tx1;
}
}else{
pi[pino].poc.tx0 = tcp->tx0_t;
pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx);
tcp->tx0_t = pi[pino].poc.tx1;
pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy);
pi[pino].poc.ty1 = tcp->ty0_t ;
incr_top=0;
}
}else{
pi[pino].poc.tx0 = tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx);
pi[pino].poc.tx1 = tcp->tx0_t ;
pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy);
pi[pino].poc.ty1 = tcp->ty0_t ;
}
}
}
break;
}
break;
}
}
}
}
return 0;
}
|
linqin07/SpringBoot-Study
|
spring-boot-security/src/main/java/com/sans/core/entity/SysMenuEntity.java
|
<filename>spring-boot-security/src/main/java/com/sans/core/entity/SysMenuEntity.java
package com.sans.core.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* @Description 权限实体
* @Author Sans
* @CreateTime 2019/9/14 15:57
*/
@Data
@TableName("sys_menu")
public class SysMenuEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 权限ID
*/
@TableId
private Long menuId;
/**
* 权限名称
*/
private String name;
/**
* 权限标识
*/
private String permission;
}
|
sprucehq/clr-icons-react
|
dist/ClrUninstall.js
|
<reponame>sprucehq/clr-icons-react
import * as React from "react";
var ClrUninstall = function() {
return React.createElement(
"svg",
{
version: "1.1",
viewBox: "0 0 36 36",
preserveAspectRatio: "xMidYMid meet",
xmlns: "http://www.w3.org/2000/svg",
focusable: "false",
role: "img",
xmlnsXlink: "http://www.w3.org/1999/xlink"
},
React.createElement("path", {
d:
"M11.29,26.72a1,1,0,0,0,1.41,0L18,21.49l5.3,5.23A1,1,0,0,0,24.7,25.3l-5.28-5.21,5.28-5.21a1,1,0,0,0-1.41-1.42L18,18.68l-5.3-5.23a1,1,0,0,0-1.41,1.42l5.28,5.21L11.3,25.3A1,1,0,0,0,11.29,26.72Z"
}),
React.createElement("path", {
d:
"M30.92,8H26.55a1,1,0,0,0,0,2H31V30H5V10H9.38a1,1,0,0,0,0-2H5.08A2,2,0,0,0,3,10V30a2,2,0,0,0,2.08,2H30.92A2,2,0,0,0,33,30V10A2,2,0,0,0,30.92,8Z"
})
);
};
export default ClrUninstall;
|
SoCaTel/PortalSide
|
src/main/java/com/socatel/utils/NextGroupStepRunnable.java
|
<reponame>SoCaTel/PortalSide
package com.socatel.utils;
import com.socatel.components.Methods;
public class NextGroupStepRunnable implements Runnable {
private Integer id;
private Methods methods;
public NextGroupStepRunnable (Methods methods, Integer id) {
this.methods = methods;
this.id = id;
}
@Override
public void run() {
methods.nextStep(id);
}
}
|
storset/vtk
|
src/main/java/vtk/security/web/SecurityInitializer.java
|
/* Copyright (c) 2004, University of Oslo, Norway
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the University of Oslo 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 vtk.security.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.OrderComparator;
import vtk.security.AuthenticationException;
import vtk.security.AuthenticationProcessingException;
import vtk.security.CookieLinkStore;
import vtk.security.Principal;
import vtk.security.PrincipalFactory;
import vtk.security.PrincipalManager;
import vtk.security.SecurityContext;
import vtk.security.token.TokenManager;
import vtk.security.web.AuthenticationHandler.AuthResult;
import vtk.web.RequestContext;
import vtk.web.service.Assertion;
import vtk.web.service.Service;
/**
* Initializer for the {@link SecurityContext security context}. A security context is created for every request. Also
* detects authentication information in requests (using {@link AuthenticationHandler authentication handlers}) and
* tries to process them.
*
* <p>
* Configurable JavaBean properties:
* <ul>
* <li><code>authenticationHandlers</code> the list of {@link AuthenticationHandler authentication handlers} to use.
* These handlers are invoked in the same order they are provided. If unspecified, the application context is searched
* for authentication handlers.
* <li><code>tokenManager</code> the {@link TokenManager} which stores repository tokens for authenticated principals
* </ul>
*/
public class SecurityInitializer implements InitializingBean, ApplicationContextAware {
private static final String SECURITY_TOKEN_SESSION_ATTR = SecurityInitializer.class.getName() + ".SECURITY_TOKEN";
public static final String VRTXLINK_COOKIE = "VRTXLINK";
private String vrtxAuthSP;
private String uioAuthIDP;
private static final String AUTH_HANDLER_SP_COOKIE_CATEGORY = "spCookie";
private static Log logger = LogFactory.getLog(SecurityInitializer.class);
private static Log authLogger = LogFactory.getLog("vtk.security.web.AuthLog");
private TokenManager tokenManager;
private PrincipalManager principalManager;
private PrincipalFactory principalFactory;
private List<AuthenticationHandler> authenticationHandlers;
private Map<String, AuthenticationHandler> authHandlerMap;
private ApplicationContext applicationContext;
private CookieLinkStore cookieLinkStore;
private String spCookieDomain = null;
// Only relevant when using both https AND http and
// different session cookie name for each protocol:
private boolean cookieLinksEnabled = false;
// Only relevant when using secure protocol:
private boolean rememberAuthMethod = false;
// Assertion that must match in order to use authentication challenge from cookie:
private Assertion spCookieAssertion;
@SuppressWarnings("unchecked")
@Override
public void afterPropertiesSet() {
if (this.authenticationHandlers == null) {
logger.info("No authentication handlers specified, looking in context");
Map<?, AuthenticationHandler> matchingBeans = this.applicationContext.getBeansOfType(
AuthenticationHandler.class, false, false);
List<AuthenticationHandler> handlers = new ArrayList<AuthenticationHandler>(matchingBeans.values());
if (handlers.isEmpty()) {
throw new IllegalStateException("At least one authentication handler must be specified, "
+ "either explicitly or in application context");
}
Collections.sort(handlers, new OrderComparator());
this.authenticationHandlers = handlers;
}
this.authHandlerMap = new HashMap<String, AuthenticationHandler>();
for (AuthenticationHandler handler : this.authenticationHandlers) {
this.authHandlerMap.put(handler.getIdentifier(), handler);
}
logger.info("Using authentication handlers: " + this.authenticationHandlers);
}
/**
*
* @param req
* @param resp
* @return <code>true</code> if request processing should continue after context has been created,
* <code>false</code> otherwise (which means that security context initialization handles a challenge or any
* authentication post-processing requests by itself).
*
* @throws AuthenticationProcessingException
* @throws ServletException
* @throws IOException
*/
public boolean createContext(HttpServletRequest req, HttpServletResponse resp)
throws AuthenticationProcessingException, ServletException, IOException {
/**
* HttpSession session = getSession(req); String token = null;
*
* if (session != null) { token = (String) session.getAttribute(SECURITY_TOKEN_SESSION_ATTR); }
*/
String token = getToken(req, resp);
if (token != null) {
Principal principal = this.tokenManager.getPrincipal(token);
if (principal != null) {
if (logger.isDebugEnabled()) {
logger.debug("Found valid token '" + token + "', principal " + principal
+ " in request session, setting security context");
}
SecurityContext.setSecurityContext(new SecurityContext(token, principal));
if (getCookie(req, VRTXLINK_COOKIE) == null && this.cookieLinksEnabled) {
UUID cookieLinkID = this.cookieLinkStore.addToken(req, token);
Cookie c = new Cookie(VRTXLINK_COOKIE, cookieLinkID.toString());
c.setPath("/");
resp.addCookie(c);
if (logger.isDebugEnabled()) {
logger.debug("Setting cookie: " + c + ": " + cookieLinkID.toString());
}
}
return true;
}
if (logger.isDebugEnabled()) {
logger.debug("Invalid token '" + token + "' in request session, "
+ "will proceed to check authentication");
}
}
for (AuthenticationHandler handler : this.authenticationHandlers) {
if (handler.isRecognizedAuthenticationRequest(req)) {
if (logger.isDebugEnabled()) {
logger.debug("Request " + req + " is recognized as an authentication attempt by handler " + handler
+ ", will try to authenticate");
}
try {
AuthResult result = handler.authenticate(req);
if (result == null) {
throw new IllegalStateException("Principal handler returned NULL AuthResult: " + handler
+ " for request " + req);
}
Principal principal = this.principalFactory.getPrincipal(result.getUID(), Principal.Type.USER);
// boolean valid = this.principalManager.validatePrincipal(principal);
// if (!valid) {
// logger.warn("Unknown principal: " + principal + " returned by authentication handler "
// + handler + ". " + "Not setting security context.");
//
// throw new IllegalStateException("Invalid principal: " + principal);
// }
if (logger.isDebugEnabled()) {
logger.debug("Successfully authenticated principal: " + principal
+ " using authentication handler " + handler + ". " + "Setting security context.");
}
if (authLogger.isDebugEnabled()) {
authLogger.debug(req.getRemoteAddr() + " - request-URI: " + req.getRequestURI() + " - "
+ "Auth: principal: '" + principal + "' - method: '" + handler.getIdentifier()
+ "' - status: OK");
}
token = this.tokenManager.newToken(principal, handler);
SecurityContext securityContext = new SecurityContext(token, this.tokenManager.getPrincipal(token));
SecurityContext.setSecurityContext(securityContext);
HttpSession session = req.getSession(true);
session.setAttribute(SECURITY_TOKEN_SESSION_ATTR, token);
onSuccessfulAuthentication(req, resp, handler, token);
if (!handler.postAuthentication(req, resp)) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication post-processing completed by authentication handler "
+ handler + ", request processing will proceed");
}
return true;
}
if (logger.isDebugEnabled()) {
logger.debug("Authentication post-processing completed by authentication handler " + handler
+ ", response already committed.");
}
return false;
} catch (AuthenticationException exception) {
AuthenticationChallenge challenge = handler.getAuthenticationChallenge();
if (logger.isDebugEnabled()) {
logger.debug("Authentication attempt " + req + " rejected by " + "handler " + handler
+ " with message " + exception.getMessage() + ", presenting challenge " + challenge
+ " to the client");
}
if (authLogger.isDebugEnabled()) {
authLogger.debug(req.getRemoteAddr() + " - request-URI: " + req.getRequestURI() + " - "
+ "Auth: request: '" + req.getRequestURI() + "' - method: '"
+ handler.getIdentifier() + "' - status: FAIL ");
authLogger.debug(req.getRemoteAddr() + " - request-URI: " + req.getRequestURI() + " - "
+ "Authentication attempt " + req + " rejected by " + "handler " + handler
+ " with message " + exception.getMessage() + ", presenting challenge " + challenge
+ " to the client");
}
doChallenge(req, resp, challenge);
return false;
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Request " + req + " is not recognized as an authentication "
+ "attempt by any authentication handler. Creating default " + "security context.");
}
SecurityContext.setSecurityContext(new SecurityContext(null, null));
return true;
}
public void challenge(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
throws AuthenticationProcessingException {
Service service = RequestContext.getRequestContext().getService();
AuthenticationChallenge challenge = getAuthenticationChallenge(request, service);
if (logger.isDebugEnabled()) {
logger.debug("Authentication required for request " + request + ", service " + service + ". "
+ "Using challenge " + challenge, ex);
}
if (challenge == null) {
throw new IllegalStateException("Authentication challenge for service " + service
+ " (or any of its ancestors) is not specified.");
}
doChallenge(request, response, challenge);
}
/**
* Removes authentication state from the authentication system. The {@link SecurityContext} is cleared, the current
* principal is removed from the {@link TokenManager}, but the {@link AuthenticationHandler#logout logout} process
* is not initiated.
*
* @return <code>true</code> if any state was removed, <code>false</code> otherwise
*/
public boolean removeAuthState(HttpServletRequest request, HttpServletResponse response) {
if (!SecurityContext.exists()) {
return false;
}
SecurityContext securityContext = SecurityContext.getSecurityContext();
Principal principal = securityContext.getPrincipal();
if (principal == null) {
return false;
}
this.tokenManager.removeToken(securityContext.getToken());
SecurityContext.setSecurityContext(null);
if (authLogger.isDebugEnabled()) {
authLogger.debug(request.getRemoteAddr() + " - request-URI: " + request.getRequestURI() + " - "
+ "removeAuthState_method: Logout: principal: '" + principal
+ "' - method: '<none>' - status: OK");
}
if (this.rememberAuthMethod) {
List<String> spCookies = new ArrayList<String>();
spCookies.add(vrtxAuthSP);
spCookies.add(uioAuthIDP);
spCookies.add(VRTXLINK_COOKIE);
for (String cookie : spCookies) {
Cookie c = getCookie(request, cookie);
if (c != null) {
if (logger.isDebugEnabled()) {
logger.debug("Deleting cookie " + cookie);
}
if (authLogger.isDebugEnabled()) {
authLogger.debug(request.getRemoteAddr() + " - request-URI: " + request.getRequestURI() + " - "
+ "Deleting cookie " + cookie);
}
c = new Cookie(cookie, c.getValue());
if (!cookie.equals(VRTXLINK_COOKIE)) {
c.setSecure(true);
}
c.setPath("/");
if (this.spCookieDomain != null && !cookie.equals(VRTXLINK_COOKIE)) {
c.setDomain(this.spCookieDomain);
}
c.setMaxAge(0);
response.addCookie(c);
}
}
}
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
return true;
}
/**
* Logs out the client from the authentication system. Clears the {@link SecurityContext} and removes the principal
* from the {@link TokenManager}. Finally, calls the authentication handler's {@link AuthenticationHandler#logout
* logout} method.
*
* @param request
* the request
* @param response
* the response
* @return the return value of the authentication handler's <code>logout()</code> method.
* @throws AuthenticationProcessingException
* if an underlying problem prevented the request from being processed
* @throws IOException
* @throws ServletException
* @see AuthenticationHandler#logout
*/
public boolean logout(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationProcessingException, ServletException, IOException {
if (!SecurityContext.exists()) {
return false;
}
SecurityContext securityContext = SecurityContext.getSecurityContext();
Principal principal = securityContext.getPrincipal();
if (principal == null) {
return false;
}
AuthenticationHandler handler = this.tokenManager.getAuthenticationHandler(securityContext.getToken());
// FIXME: what if handler.isLogoutSupported() == false?
boolean result = handler.logout(principal, request, response);
String status = result ? "OK" : "FAIL";
if (authLogger.isDebugEnabled()) {
authLogger.debug(request.getRemoteAddr() + " - request-URI: " + request.getRequestURI() + " - "
+ "logout_method: Logout: principal: '" + principal + "' - method: '"
+ handler.getIdentifier() + "' - status: " + status);
}
this.tokenManager.removeToken(securityContext.getToken());
SecurityContext.setSecurityContext(null);
if (this.rememberAuthMethod) {
List<String> spCookies = new ArrayList<String>();
spCookies.add(vrtxAuthSP);
spCookies.add(uioAuthIDP);
if (this.cookieLinksEnabled) {
spCookies.add(VRTXLINK_COOKIE);
}
for (String cookie : spCookies) {
Cookie c = getCookie(request, cookie);
if (c != null) {
if (logger.isDebugEnabled()) {
logger.debug("Deleting cookie " + cookie);
}
c = new Cookie(cookie, c.getValue());
if (!cookie.equals(VRTXLINK_COOKIE)) {
c.setSecure(true);
}
c.setPath("/");
if (this.spCookieDomain != null && !cookie.equals(VRTXLINK_COOKIE)) {
c.setDomain(this.spCookieDomain);
}
c.setMaxAge(0);
response.addCookie(c);
}
}
}
return result;
}
/**
* @see vtk.web.ContextInitializer#destroyContext()
*/
public void destroyContext() {
if (logger.isDebugEnabled()) {
logger.debug("Destroying security context: " + SecurityContext.getSecurityContext());
}
SecurityContext.setSecurityContext(null);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName());
sb.append(": ").append(System.identityHashCode(this));
sb.append(", authenticationHandlers: [");
sb.append(this.authenticationHandlers);
sb.append("]");
return sb.toString();
}
@Required
public void setTokenManager(TokenManager tokenManager) {
this.tokenManager = tokenManager;
}
@Required
public void setPrincipalManager(PrincipalManager principalManager) {
this.principalManager = principalManager;
}
@Required
public void setPrincipalFactory(PrincipalFactory principalFactory) {
this.principalFactory = principalFactory;
}
public void setAuthenticationHandlers(List<AuthenticationHandler> authenticationHandlers) {
this.authenticationHandlers = authenticationHandlers;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void setCookieLinkStore(CookieLinkStore cookieLinkStore) {
this.cookieLinkStore = cookieLinkStore;
}
public void setCookieLinksEnabled(boolean cookieLinksEnabled) {
this.cookieLinksEnabled = cookieLinksEnabled;
}
public void setRememberAuthMethod(boolean rememberAuthMethod) {
this.rememberAuthMethod = rememberAuthMethod;
}
public void setSpCookieDomain(String spCookieDomain) {
if (spCookieDomain != null && !"".equals(spCookieDomain.trim())) {
this.spCookieDomain = spCookieDomain;
}
}
public void setSpCookieAssertion(Assertion spCookieAssertion) {
this.spCookieAssertion = spCookieAssertion;
}
private String getToken(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
if (!this.cookieLinksEnabled) {
if (session == null) {
return null;
}
return (String) session.getAttribute(SECURITY_TOKEN_SESSION_ATTR);
}
if (session != null) {
final String tokenFromSession = (String) session.getAttribute(SECURITY_TOKEN_SESSION_ATTR);
if (tokenFromSession != null) {
Principal principal = this.tokenManager.getPrincipal(tokenFromSession);
if (principal != null) {
return tokenFromSession;
}
}
}
if (request.getCookies() != null && !request.isSecure()) {
Cookie c = getCookie(request, VRTXLINK_COOKIE);
if (logger.isDebugEnabled()) {
logger.debug("Cookie: " + VRTXLINK_COOKIE + ": " + c);
}
if (c != null) {
UUID id;
try {
id = UUID.fromString(c.getValue());
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
logger.debug("Invalid UUID cookie value: " + c.getValue(), t);
}
return null;
}
String token = this.cookieLinkStore.getToken(request, id);
if (token == null) {
if (logger.isDebugEnabled()) {
logger.debug("No token found from cookie " + VRTXLINK_COOKIE + ", deleting cookie");
}
c = new Cookie(VRTXLINK_COOKIE, c.getValue());
c.setPath("/");
c.setMaxAge(0);
response.addCookie(c);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Found token " + token + " from cookie " + VRTXLINK_COOKIE);
}
session = request.getSession(true);
session.setAttribute(SECURITY_TOKEN_SESSION_ATTR, token);
return token;
}
}
}
return null;
}
private void onSuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp,
AuthenticationHandler handler, String token) {
if (!req.isSecure()) {
return;
}
Set<?> categories = handler.getCategories();
if (categories == null)
categories = Collections.EMPTY_SET;
if (this.rememberAuthMethod && categories.contains(AUTH_HANDLER_SP_COOKIE_CATEGORY)) {
List<String> spCookies = new ArrayList<String>();
spCookies.add(vrtxAuthSP);
spCookies.add(uioAuthIDP);
for (String cookie : spCookies) {
Cookie c = new Cookie(cookie, handler.getIdentifier());
c.setSecure(true);
c.setPath("/");
if (this.spCookieDomain != null) {
c.setDomain(this.spCookieDomain);
}
resp.addCookie(c);
if (logger.isDebugEnabled()) {
logger.debug("Setting cookie: " + c + ": " + handler.getIdentifier());
}
}
}
if (this.cookieLinksEnabled) {
UUID cookieLinkID = this.cookieLinkStore.addToken(req, token);
Cookie c = new Cookie(VRTXLINK_COOKIE, cookieLinkID.toString());
c.setPath("/");
resp.addCookie(c);
if (logger.isDebugEnabled()) {
logger.debug("Setting cookie: " + c + ": " + cookieLinkID.toString());
}
}
}
private void doChallenge(HttpServletRequest request, HttpServletResponse response, AuthenticationChallenge challenge) {
HttpSession session = request.getSession(false);
if (session != null) {
Object token = session.getAttribute(SECURITY_TOKEN_SESSION_ATTR);
if (token != null) {
if (logger.isDebugEnabled()) {
logger.debug("Removing invalid token '" + token + "' from session");
}
session.removeAttribute(SECURITY_TOKEN_SESSION_ATTR);
}
}
try {
challenge.challenge(request, response);
} catch (AuthenticationProcessingException ape) {
// VTK-1896
// Avoid wrapping APE in another APE, otherwise we get banana dance.
throw ape;
} catch (Exception e) {
throw new AuthenticationProcessingException("Unable to present authentication challenge " + challenge, e);
}
}
private AuthenticationChallenge getAuthenticationChallenge(HttpServletRequest request, Service service) {
AuthenticationChallenge challenge = null;
if (this.rememberAuthMethod) {
Cookie c = getCookie(request, vrtxAuthSP);
if (c != null) {
String id = c.getValue();
AuthenticationHandler handler = this.authHandlerMap.get(id);
if (handler != null) {
Set<?> categories = handler.getCategories();
if (categories == null) {
categories = Collections.EMPTY_SET;
}
if (handler != null && categories.contains(AUTH_HANDLER_SP_COOKIE_CATEGORY)) {
challenge = handler.getAuthenticationChallenge();
}
}
}
}
if (challenge != null) {
if (this.spCookieAssertion != null) {
boolean match = this.spCookieAssertion.matches(request, null, null);
if (!match) {
challenge = null;
}
}
}
if (challenge != null) {
if (logger.isDebugEnabled()) {
logger.debug("Using challenge from cookie " + vrtxAuthSP + ": " + challenge);
}
return challenge;
}
challenge = service.getAuthenticationChallenge();
if (challenge == null && service.getParent() != null) {
return getAuthenticationChallenge(request, service.getParent());
}
return challenge;
}
private static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public void setVrtxAuthSP(String vrtxAuthSP) {
this.vrtxAuthSP = vrtxAuthSP;
}
public void setUioAuthIDP(String uioAuthIDP) {
this.uioAuthIDP = uioAuthIDP;
}
}
|
akatz2/openessence-demo
|
core/src/main/webapp/js/oe/reporting/defaultDataSourceReportGroupBySelectionForm.js
|
<filename>core/src/main/webapp/js/oe/reporting/defaultDataSourceReportGroupBySelectionForm.js
/*
* Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
* All rights reserved.
*
* This material may be used, modified, or reproduced by or for the U.S.
* Government pursuant to the rights granted under the clauses at
* DFARS 252.227-7013/7014 or FAR 52.227-14.
*
* 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
*
* NO WARRANTY. THIS MATERIAL IS PROVIDED "AS IS." JHU/APL DISCLAIMS ALL
* WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING (BUT NOT
* LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF
* INTELLECTUAL PROPERTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE
* RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE
* LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT,
* CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR
* INABILITY TO USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES
* FOR LOST PROFITS.
*/
Ext.namespace("OE.report.datasource.groupBy");
/**
* Search form panel, builds query form using filter dimensions and results grid using detail dimensions.
*
* Selected records are returned on submit using name/value <code>configuration.name</code>.
*/
OE.report.datasource.groupBy.form = function (configuration) {
var sm = new Ext.grid.RowSelectionModel();
var gridPanel = new Ext.grid.GridPanel({
itemId: 'groupByGrid',
region: 'center',
store: new Ext.data.Store({
reader: new Ext.data.ArrayReader({}, [
{name: 'dimensionId'},
{name: 'dimension'}
]),
data: configuration.data
}),
columns: [
{id: 'dimension', header: messagesBundle['input.datasource.default.groupBy.columns'], width: 200, dataIndex: 'dimension'}
],
sm: sm,
border: false,
autoExpandColumn: 'dimension',
autoExpandMin: 150,
deferRowRender: false // for auto-selecting rows
});
var resultsFormPanel = new Ext.form.FormPanel({
layout: 'border',
border: false,
monitorValid: true,
items: [
{
xtype: 'textfield',
inputType: 'hidden',
name: 'results',
allowBlank: false,
getValue: function () {
// To return records for get field values
return sm.getSelections();
},
getRawValue: function () {
// For validation
return sm.getSelections();
}
},
gridPanel
],
buttons: [
{
text: messagesBundle[configuration.dataSource + '.ok'] || messagesBundle['input.datasource.default.ok'],
formBind: true,
handler: function () {
if (configuration.callback) {
configuration.callback(resultsFormPanel.getForm().getFieldValues());
}
},
scope: configuration
},
{
text: messagesBundle[configuration.dataSource + '.cancel'] || messagesBundle['input.datasource.default.cancel'],
handler: function () {
if (configuration.callback) {
configuration.callback();
}
},
scope: configuration
}
]
});
return resultsFormPanel;
};
|
SAP/go-dblib
|
asetypes/convert.go
|
<reponame>SAP/go-dblib
// SPDX-FileCopyrightText: 2020 SAP SE
// SPDX-FileCopyrightText: 2021 SAP SE
//
// SPDX-License-Identifier: Apache-2.0
package asetypes
import (
"database/sql/driver"
"fmt"
"reflect"
)
// ConvertValue converts a value-interface of an ASE data type into
// a database/sql/driver.Value with the respective golang data type.
func (t DataType) ConvertValue(v interface{}) (driver.Value, error) {
sv := reflect.ValueOf(v)
// Return value as-is if the type already matches.
if sv.Type() == ReflectTypes[t] {
return v, nil
}
switch t {
case INT1:
switch sv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return uint8(sv.Int()), nil
}
case INT2:
switch sv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return int16(sv.Int()), nil
}
case INT4:
switch sv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return int32(sv.Int()), nil
}
case INT8, INTN:
switch sv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return sv.Int(), nil
}
case UINT2:
switch sv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return uint16(sv.Uint()), nil
}
case UINT4:
switch sv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return uint32(sv.Uint()), nil
}
case UINT8, UINTN:
switch sv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return sv.Uint(), nil
}
case FLT4:
switch sv.Kind() {
case reflect.Float64:
return float32(sv.Float()), nil
}
case FLT8:
switch sv.Kind() {
case reflect.Float32:
return sv.Float(), nil
}
}
return nil, fmt.Errorf("cannot convert %v (type %T) for %s", v, v, t)
}
|
AnneSophieS/manager
|
packages/manager/apps/dedicated/client/app/components/validator/validator.service.js
|
<reponame>AnneSophieS/manager<gh_stars>100-1000
angular.module('services').service('Validator', [
function ValidatorService() {
const self = this;
this.isValidIpv4 = function isValidIpv4(ip) {
let isValid;
try {
// Coz sometimes ipaddr is buggy
isValid = ip && ip.split('.').length === 4 && ipaddr.IPv4.isValid(ip);
} catch (e) {
isValid = false;
throw e;
}
return isValid;
};
// @todo use a regexp instead
this.isValidIpv4Block = function isValidIpv4Block(block) {
const split = block.split('/');
return (
split.length === 2 &&
this.isValidIpv4(split[0]) &&
parseInt(split[1], 10) > 0 &&
parseInt(split[1], 10) < 33
);
};
this.isValidIpv6 = function isValidIpv6(ip) {
let isValid;
try {
// Coz sometimes ipaddr is buggy
isValid = ip && ipaddr.IPv6.isValid(ip);
} catch (e) {
isValid = false;
throw e;
}
return isValid;
};
// TODO use a regexp instead
this.isValidIpv6Block = function isValidIpv6Block(block) {
const split = block.split('/');
return (
split.length === 2 &&
this.isValidIpv6(split[0]) &&
parseInt(split[1], 10) > 0 &&
parseInt(split[1], 10) < 129
);
};
// opts.canBeginWithUnderscore = specifics NDD can be like: _foo._bar.example.com
// opts.canBeginWithWildcard = specifics NDD can be like: *.foo.bar.example.com
this.isValidDomain = function isValidDomain(domain, _opts) {
let opts = _opts;
if (!opts) {
opts = {};
}
let inError = false;
if (domain) {
const punycodeVersion = punycode.toASCII(domain.trim());
const dotSplit = punycodeVersion.split('.');
// Check lengths
inError = punycodeVersion.length > 255 || dotSplit.length < 2;
// Check wildcard
if (
!inError &&
~punycodeVersion.indexOf('*') &&
(opts.canBeginWithWildcard
? !/^(?:\*\.)[^*]+$/.test(punycodeVersion)
: true)
) {
inError = true;
}
// Check subdomain(s)
if (!inError) {
angular.forEach(dotSplit, (sub) => {
if (sub.length > 63 || /(?:(?:^\s*$)|(?:^-)|(?:-$))/.test(sub)) {
inError = true;
}
if (
~sub.indexOf('_') &&
(opts.canBeginWithUnderscore ? !/^_[^_]+$/.test(sub) : true)
) {
inError = true;
}
});
}
// Check chars globally
if (!inError) {
inError = !/^[\w\-.*]+$/.test(punycodeVersion);
}
}
return !inError;
};
this.isValidSubDomain = function isValidSubDomain(subDomain, opts) {
return self.isValidDomain(`${subDomain}.example.com`, opts);
};
},
]);
|
jack-debug/Ares-1.0-Source-Leak
|
org/spongepowered/asm/mixin/injection/throwables/InjectionError.java
|
<filename>org/spongepowered/asm/mixin/injection/throwables/InjectionError.java
package org.spongepowered.asm.mixin.injection.throwables;
public class InjectionError extends Error
{
private static final long serialVersionUID = 1L;
public InjectionError() {
}
public InjectionError(final String a1) {
super(a1);
}
public InjectionError(final Throwable a1) {
super(a1);
}
public InjectionError(final String a1, final Throwable a2) {
super(a1, a2);
}
}
|
abdalla/docker-image-for-python-boto3-mysql
|
deps/unixODBC-2.3.4/Drivers/MiniSQL/_Prepare.c
|
<reponame>abdalla/docker-image-for-python-boto3-mysql
/**********************************************************************
* SQLPrepare
*
**********************************************************************
*
* This code was created by <NAME> (mostly during Christmas 98/99).
* This code is LGPL. Please ensure that this message remains in future
* distributions and uses of this code (thats about all I get out of it).
* - <NAME> <EMAIL>
*
**********************************************************************/
#include <config.h>
#include "driver.h"
SQLRETURN _Prepare( SQLHSTMT hDrvStmt,
SQLCHAR *szSqlStr,
SQLINTEGER nSqlStrLength )
{
HDRVSTMT hStmt = (HDRVSTMT)hDrvStmt;
/* SANITY CHECKS */
if ( NULL == hStmt )
return SQL_INVALID_HANDLE;
sprintf( hStmt->szSqlMsg, "hStmt = $%08lX", hStmt );
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, hStmt->szSqlMsg );
if ( szSqlStr == NULL )
{
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR No SQL to process" );
return SQL_ERROR;
}
if ( hStmt->pszQuery != NULL )
{
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR Statement already in use." );
return SQL_ERROR;
}
/* allocate and copy statement to buffer (process escape sequences and parameter tokens as required) */
hStmt->pszQuery = (char *)strdup( szSqlStr );
if ( NULL == hStmt->pszQuery )
{
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR Memory allocation error" );
return SQL_ERROR;
}
logPushMsg( hStmt->hLog, __FILE__, __FILE__, __LINE__, LOG_INFO, LOG_INFO, "SQL_SUCCESS" );
return SQL_SUCCESS;
}
|
cuttlefish/geogig
|
src/core/src/main/java/org/locationtech/geogig/plumbing/DiffWorkTree.java
|
<filename>src/core/src/main/java/org/locationtech/geogig/plumbing/DiffWorkTree.java<gh_stars>0
/* Copyright (c) 2012-2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* <NAME> (Boundless) - initial implementation
*/
package org.locationtech.geogig.plumbing;
import org.eclipse.jdt.annotation.Nullable;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.Ref;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.repository.AbstractGeoGigOp;
import org.locationtech.geogig.repository.DiffEntry;
import org.locationtech.geogig.repository.StagingArea;
import org.locationtech.geogig.repository.WorkingTree;
import org.locationtech.geogig.storage.AutoCloseableIterator;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
/**
* Compares the features in the {@link WorkingTree working tree} and the {@link StagingArea index}
* or a given root tree-ish.
*/
public class DiffWorkTree extends AbstractGeoGigOp<AutoCloseableIterator<DiffEntry>>
implements Supplier<AutoCloseableIterator<DiffEntry>> {
private String pathFilter;
private String refSpec;
private boolean reportTrees;
private Long limit;
private boolean preserveIterationOrder;
/**
* @param refSpec the name of the root tree object in the to compare the working tree against.
* If {@code null} or not specified, defaults to the current state of the index.
* @return {@code this}
*/
public DiffWorkTree setOldVersion(@Nullable String refSpec) {
this.refSpec = refSpec;
return this;
}
/**
* @param path the path filter to use during the diff operation
* @return {@code this}
*/
public DiffWorkTree setFilter(@Nullable String path) {
pathFilter = path;
return this;
}
/**
* @param preserveIterationOrder if {@code true} the diff order will be consistent
* @return {@code this}
*/
public DiffWorkTree setPreserveIterationOrder(boolean preserveIterationOrder) {
this.preserveIterationOrder = preserveIterationOrder;
return this;
}
/**
* If no {@link #setOldVersion(String) old version} was set, returns the differences between the
* working tree and the index, otherwise the differences between the working tree and the
* specified revision.
*
* @return an iterator to a set of differences between the two trees
* @see DiffEntry
*/
@Override
protected AutoCloseableIterator<DiffEntry> _call() {
final Optional<String> ref = Optional.fromNullable(refSpec);
final RevTree oldTree = ref.isPresent() ? getOldTree() : stagingArea().getTree();
final RevTree newTree = workingTree().getTree();
DiffTree diff = command(DiffTree.class).setReportTrees(this.reportTrees)
.setOldTree(oldTree.getId()).setNewTree(newTree.getId()).setMaxDiffs(limit)
.setPreserveIterationOrder(preserveIterationOrder);
if (this.pathFilter != null) {
diff.setPathFilter(ImmutableList.of(pathFilter));
}
return diff.call();
}
/**
* @return the tree referenced by the old ref, or the head of the index.
*/
private RevTree getOldTree() {
final String oldVersion = Optional.fromNullable(refSpec).or(Ref.STAGE_HEAD);
Optional<ObjectId> headTreeId = command(ResolveTreeish.class).setTreeish(oldVersion).call();
Preconditions.checkArgument(headTreeId.isPresent(),
"Refspec " + oldVersion + " does not resolve to a tree");
final RevTree headTree;
headTree = command(RevObjectParse.class).setObjectId(headTreeId.get()).call(RevTree.class)
.get();
return headTree;
}
/**
* @param reportTrees
* @return
*/
public DiffWorkTree setReportTrees(boolean reportTrees) {
this.reportTrees = reportTrees;
return this;
}
public DiffWorkTree setMaxDiffs(@Nullable Long limit) {
Preconditions.checkArgument(limit == null || limit.longValue() >= 0L,
"limit must be >= 0: ", limit);
this.limit = limit;
return this;
}
/**
* Implements {@link Supplier#get()} by deferring to {@link #call()}
*
* @see #call()
*/
@Override
public AutoCloseableIterator<DiffEntry> get() {
return call();
}
}
|
teddywest32/intellij-community
|
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalProjectPathLookupElement.java
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.externalSystem.service.ui;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.FoldRegion;
import com.intellij.openapi.editor.FoldingModel;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME>
* @since 5/25/13 7:26 PM
*/
public class ExternalProjectPathLookupElement extends LookupElement {
@NotNull private final String myProjectName;
@NotNull private final String myProjectPath;
public ExternalProjectPathLookupElement(@NotNull String projectName, @NotNull String projectPath) {
myProjectName = projectName;
myProjectPath = projectPath;
}
@NotNull
@Override
public String getLookupString() {
return myProjectName;
}
@Override
public void handleInsert(InsertionContext context) {
Editor editor = context.getEditor();
final FoldingModel foldingModel = editor.getFoldingModel();
foldingModel.runBatchFoldingOperation(() -> {
FoldRegion[] regions = foldingModel.getAllFoldRegions();
for (FoldRegion region : regions) {
foldingModel.removeFoldRegion(region);
}
});
final Document document = editor.getDocument();
final int startOffset = context.getStartOffset();
document.replaceString(startOffset, document.getTextLength(), myProjectPath);
final Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitDocument(document);
foldingModel.runBatchFoldingOperationDoNotCollapseCaret(() -> {
FoldRegion region = foldingModel.addFoldRegion(startOffset, startOffset + myProjectPath.length(), myProjectName);
if (region != null) {
region.setExpanded(false);
}
});
}
}
|
sentervip/T1sdk5.4.0
|
5.0.4/projects/target_apps/ble_examples/ble_app_profile/src/platform/user_periph_setup.c
|
<gh_stars>0
/**
****************************************************************************************
*
* @file user_periph_setup.c
*
* @brief Peripherals setup and initialization.
*
* Copyright (C) 2015. Dialog Semiconductor Ltd, unpublished work. This computer
* program includes Confidential, Proprietary Information and is a Trade Secret of
* Dialog Semiconductor Ltd. All use, disclosure, and/or reproduction is prohibited
* unless authorized in writing. All Rights Reserved.
*
* <<EMAIL>> and contributors.
*
****************************************************************************************
*/
/*
* INCLUDE FILES
****************************************************************************************
*/
#include "rwip_config.h" // SW configuration
#include "user_periph_setup.h" // peripheral configuration
#include "global_io.h"
#include "gpio.h"
#include "uart.h" // UART initialization
#if DEVELOPMENT_DEBUG
void GPIO_reservations(void)
{
/*
* Globally reserved GPIOs reservation
*/
/*
* Application specific GPIOs reservation. Used only in Development mode (#if DEVELOPMENT_DEBUG)
i.e.
RESERVE_GPIO(DESCRIPTIVE_NAME, GPIO_PORT_0, GPIO_PIN_1, PID_GPIO); //Reserve P_01 as Generic Purpose I/O
*/
#ifdef CFG_PRINTF_UART2
RESERVE_GPIO(UART2_TX, UART2_TX_GPIO_PORT, UART2_TX_GPIO_PIN, PID_UART2_TX);
RESERVE_GPIO(UART2_RX, UART2_RX_GPIO_PORT, UART2_RX_GPIO_PIN, PID_UART2_RX);
#endif
}
#endif //DEVELOPMENT_DEBUG
void set_pad_functions(void) // set gpio port function mode
{
#ifdef CFG_PRINTF_UART2
GPIO_ConfigurePin(UART2_TX_GPIO_PORT, UART2_TX_GPIO_PIN, OUTPUT, PID_UART2_TX, false);
GPIO_ConfigurePin(UART2_RX_GPIO_PORT, UART2_RX_GPIO_PIN, INPUT, PID_UART2_RX, false);
#endif
/*
* Configure application ports.
i.e.
GPIO_ConfigurePin( GPIO_PORT_0, GPIO_PIN_1, OUTPUT, PID_GPIO, false ); // Set P_01 as Generic purpose Output
*/
}
void periph_init(void)
{
// Power up peripherals' power domain
SetBits16(PMU_CTRL_REG, PERIPH_SLEEP, 0);
while (!(GetWord16(SYS_STAT_REG) & PER_IS_UP));
SetBits16(CLK_16M_REG, XTAL16_BIAS_SH_ENABLE, 1);
//rom patch
patch_func();
//Init pads
set_pad_functions();
// (Re)Initialize peripherals
// i.e.
// uart_init(UART_BAUDRATE_115K2, 3);
#ifdef CFG_PRINTF_UART2
SetBits16(CLK_PER_REG, UART2_ENABLE, 1);
uart2_init(UART_BAUDRATE_115K2, 3);
#endif
// Enable the pads
SetBits16(SYS_CTRL_REG, PAD_LATCH_EN, 1);
}
|
cuongpm/android-browser-downloader
|
app/src/main/java/com/browser/downloader/ui/adapter/ProgressAdapter.java
|
<gh_stars>10-100
package com.browser.downloader.ui.adapter;
import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.browser.core.R;
import com.browser.downloader.data.model.ProgressInfo;
import com.browser.core.databinding.ItemProgressBinding;
import java.util.ArrayList;
public class ProgressAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<ProgressInfo> mProgressInfos;
public ProgressAdapter(ArrayList<ProgressInfo> progressInfos) {
this.mProgressInfos = progressInfos;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemProgressBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
R.layout.item_progress, parent, false);
return new ProgressViewHolder(binding);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ProgressInfo progressInfo = mProgressInfos.get(position);
ItemProgressBinding binding = ((ProgressViewHolder) holder).binding;
binding.tvTitle.setText(progressInfo.getVideo().getFileName());
binding.progressBar.setProgress(progressInfo.getProgress());
binding.tvProgress.setText(progressInfo.getProgressSize());
binding.ivThumbnail.setImageURI(progressInfo.getVideo().getThumbnail());
}
@Override
public int getItemCount() {
return mProgressInfos.size();
}
class ProgressViewHolder extends RecyclerView.ViewHolder {
ItemProgressBinding binding;
public ProgressViewHolder(ItemProgressBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
}
|
ylankgz/amazon-ssm-agent
|
agent/framework/processor/executer/iohandler/iomodule/mock/iomodule.go
|
// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
// Package iomodulemock implements the mock iomodule
package iomodulemock
import (
"io"
"github.com/aws/amazon-ssm-agent/agent/log"
"github.com/stretchr/testify/mock"
)
// MockIOModule mocks an IOModule.
type MockIOModule struct {
mock.Mock
}
// Read is a mocked method that acknowledges that the function has been called.
func (m *MockIOModule) Read(log log.T, reader *io.PipeReader) {
m.Called(log, reader)
}
|
iamycx/Spring-learning
|
spring-aop/src/com/iamycx/aspectj/example/WaiterManager.java
|
package com.iamycx.aspectj.example;
public class WaiterManager {
public void addWaiter(Waiter waiter){
System.out.println("add Waiter...");
}
public void addNaiveWaiter(NaiveWaiter nw){
System.out.println("add NaiveWaiter...");
}
}
|
ganapathygit/camel
|
platforms/camel-catalog-rest/src/main/java/org/apache/camel/catalog/rest/CamelConnectorCatalogRest.java
|
<reponame>ganapathygit/camel
/**
* 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.camel.catalog.rest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.camel.catalog.connector.CamelConnectorCatalog;
import org.apache.camel.catalog.connector.ConnectorDto;
import org.apache.camel.catalog.connector.DefaultCamelConnectorCatalog;
import org.apache.camel.catalog.maven.DefaultMavenArtifactProvider;
import org.apache.camel.catalog.maven.MavenArtifactProvider;
/**
* A REST based {@link CamelConnectorCatalog} service as a JAX-RS resource class.
*/
@Api(value = "/camel-connector-catalog", description = "Camel Connector Catalog REST API")
@Path("/camel-connector-catalog")
public class CamelConnectorCatalogRest {
private CamelConnectorCatalog catalog = new DefaultCamelConnectorCatalog();
private MavenArtifactProvider maven = new DefaultMavenArtifactProvider();
public CamelConnectorCatalog getCatalog() {
return catalog;
}
/**
* To inject an existing {@link CamelConnectorCatalog}
*/
public void setCatalog(CamelConnectorCatalog catalog) {
this.catalog = catalog;
}
@GET
@Path("/findConnector")
@Produces("application/json")
@ApiOperation(value = "Find all the connectors from the catalog")
public List<ConnectorDto> findConnector(@ApiParam(value = "Whether to include latest version only", defaultValue = "true")
@QueryParam("latestVersionOnly") Boolean latestVersionOnly) {
boolean latest = latestVersionOnly != null ? latestVersionOnly : true;
return catalog.findConnector(latest);
}
@GET
@Path("/findConnector/{filter}")
@Produces("application/json")
@ApiOperation(value = "Find all the connectors from the catalog")
public List<ConnectorDto> findConnector(@ApiParam("Filter the connector matching by name, description or labels")
@PathParam("filter") String filter,
@ApiParam(value = "Whether to include latest version only", defaultValue = "true")
@QueryParam("latestVersionOnly") Boolean latestVersionOnly) {
boolean latest = latestVersionOnly != null ? latestVersionOnly : true;
return catalog.findConnector(latest);
}
@GET
@Path("/connectorJSon/{groupId}/{artifactId}/{version}")
@Produces("application/json")
@ApiOperation(value = "Returns the camel-connector json file for the given connector with the Maven coordinate")
public String connectorJSon(@ApiParam(value = "Maven groupdId of the connector", required = true)
@PathParam("groupId") String groupId,
@ApiParam(value = "Maven artifactId of the connector", required = true)
@PathParam("artifactId") String artifactId,
@ApiParam(value = "Maven version of the connector", required = true)
@PathParam("version") String version) {
return catalog.connectorJSon(groupId, artifactId, version);
}
@GET
@Path("/connectorSchemaJSon/{groupId}/{artifactId}/{version}")
@Produces("application/json")
@ApiOperation(value = "Returns the camel-connector-schema json file for the given connector with the Maven coordinate")
public String connectorSchemaJSon(@ApiParam(value = "Maven groupdId of the connector", required = true)
@PathParam("groupId") String groupId,
@ApiParam(value = "Maven artifactId of the connector", required = true)
@PathParam("artifactId") String artifactId,
@ApiParam(value = "Maven version of the connector", required = true)
@PathParam("version") String version) {
return catalog.connectorSchemaJSon(groupId, artifactId, version);
}
@POST
@Path("/asEndpointUri/{scheme}")
@Consumes("application/json")
@Produces("text/plain")
@ApiOperation(value = "Creates an endpoint uri in Java style configured using the provided options in the JSon body")
public String asEndpointUri(@ApiParam(value = "The component scheme", readOnly = true) @PathParam("scheme") String scheme,
@ApiParam(value = "The options as a JSon map with key/value pairs", required = true) String json) {
try {
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, Map.class);
return catalog.asEndpointUri(scheme, map, true);
} catch (Exception e) {
return null;
}
}
@POST
@Path("/asEndpointUriXml/{scheme}")
@Consumes("application/json")
@Produces("text/plain")
@ApiOperation(value = "Creates an endpoint uri in XML style configured using the provided options in the JSon body")
public String asEndpointUriXml(@ApiParam(value = "The component scheme", readOnly = true) @PathParam("scheme") String scheme,
@ApiParam(value = "The options as a JSon map with key/value pairs", required = true) String json) {
try {
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, Map.class);
return catalog.asEndpointUriXml(scheme, map, true);
} catch (Exception e) {
return null;
}
}
@POST
@Path("/mavenCacheDirectory/{name}")
@ApiOperation(value = "Configures the Maven cache directory to use when downloading artifacts")
public void mavenCacheDirectory(@ApiParam(value = "The name of the cache directory", required = true) @PathParam("name") String name) {
maven.setCacheDirectory(name);
}
@POST
@Path("/addMavenRepository/{name}/{url}")
@ApiOperation(value = "Adds a third party Maven repository to use for downloading Maven artifacts")
public void addMavenRepository(@ApiParam(value = "The name of the Maven repository", required = true) @PathParam("name") String name,
@ApiParam(value = "The URL of the Maven repository", required = true) @PathParam("url") String url) {
maven.addMavenRepository(name, url);
}
@POST
@Path("/addConnectorFromMavenArtifact/{groupId}/{artifactId}/{version}")
@Produces("application/json")
@ApiOperation(value = "Downloads the Maven artifact and scan for custom Camel connectors which will be added to the catalog and returns the names of the found connectors")
public Set<String> addConnectorFromMavenArtifact(@ApiParam(value = "The Maven groupId", required = true) @PathParam("groupId") String groupId,
@ApiParam(value = "The Maven artifactId", required = true) @PathParam("artifactId") String artifactId,
@ApiParam(value = "The Maven version", required = true) @PathParam("version") String version) {
return maven.addArtifactToCatalog(null, catalog, groupId, artifactId, version);
}
}
|
ecmarsh/algorithms
|
exercises/minSwapsForEqualRow.js
|
<gh_stars>1-10
/**
* @=lc id=1007 lang=javascript
*
* [1007] Minimum Swaps for Equal Row
*
* Given two arrays, A and B, return the minimum number of swaps
* to make all values in either A the same or all elements in B the same.
* If no amount of swaps can make all elements in either arr equal, return -1.
*
* @constraints
* - `1 <= A[i], B[i] <= 6`
* - `2 <= A.length == B.length <= 20,000`
*
* @example
* Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
* Output: 2
* Explanation: Swap index 1 and 3 to make all elements of A equal to 2.
*
* @example
* Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
* Output: -1
* Explanation: No amount of swaps can make all values in either A or B equal.
*
* @complexity
* N = A = A.length = B = B.length
* Time: O(A+B) = O(2N) = O(N)
* Space: O(1)
*/
/**
* @param {number[]} A
* @param {number[]} B
* @return {number}
*/
module.exports = function minSwapsForEqualRow( A, B ) {
// Pick arbitrary value in A and B to compare if can make equal.
const [a, b] = [A[0], B[0]];
// Check min rotations to make all elements equal in A
const aMin = check( A, B, a );
// If b is same value or we have an answer with A, no need to check with b.
// NOTE: we don't need to check with A since we compare the min of moving
// a to b and vice versa (which row has more of "a") in the check function.
return a === b || aMin !== -1 ? aMin : check( A, B, b );
};
/**
* Check checks that for each i, either A[i] or B[i] is
* equal to `x`. Returns -1 if not, or the minimum indices
* that are not equal to x; that is, min rotations needed.
*
* @param {number[]} A
* @param {number[]} B
* @param {number} x
* @returns {number} -1 or the min rotations.
*/
const check = ( A, B, x ) => {
let [aNotX, bNotX] = [0, 0];
for ( let i = 0; i < A.length; i++ ) {
if ( A[i] !== x && B[i] !== x ) {
return -1;
}
// A[i] or B[i] or both must be equal to x
// Count a rotation/swap for one, if any, not equal
if ( A[i] !== x ) {
aNotX++;
} else if ( B[i] !== x ) {
bNotX++;
}
}
return Math.min( aNotX, bNotX );
};
|
nagrohan726/eclipse-workspace
|
CoreJava/ExceptionHandling/src/StringParser.java
|
public class StringParser {
public static void main(String[] args) {
try {
String s = "abcd";
int i = Integer.parseInt(s);
System.out.println(i);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number");
}
}
}
|
djangojeng-e/TIL
|
python_class/191120_creating_class.py
|
<reponame>djangojeng-e/TIL<gh_stars>0
# Class named as Human will be created
class Human(): # 1. Class has been created.
'''Human''' # 2. ''' ''' is description on the class. refer to Docstring
person1 = Human()
# 3. Human Class has been called. One instance created to person1
person2 = Human()
# 4. Human Class has been called. One instance created to person2.
# Class has its own functionality to save and control data.
# e.g. list is a type of class that can store data in order.
# e.g. list can control its data by using commands like append(), extend(), inse# rt(), pop()
person1.language = 'English' # Person1 speaks English
person2.language = 'German' # Person2 speaks German
print(person1.language)
print(person2.language)
print()
print()
print()
person.name = 'George'
person.name = 'Ozil'
def speak(person):
print("{} speaks {}".format(person.name, person.language))
speak(person1)
speak(person2)
|
1813404040072/template-react-antdesign
|
src/routes/UI/Editor/messages/index.js
|
<filename>src/routes/UI/Editor/messages/index.js
export const scope = 'routes.Editor';
export default ({
richText: {
id: `${scope}.richText`,
defaultMessage: 'Rich text',
},
richTextUse: {
id: `${scope}.richTextUse`,
defaultMessage: 'Rich text use',
},
specific: {
id: `${scope}.specific`,
defaultMessage: 'Specific parameters can be viewed on their website.',
},
settings: {
id: `${scope}.settings`,
defaultMessage: 'Settings',
},
getValue: {
id: `${scope}.getValue`,
defaultMessage: 'Get value',
},
clearValue: {
id: `${scope}.clearValue`,
defaultMessage: 'Clear value',
},
});
|
sagarbabalsure/pythonCodes
|
OOP/example4.py
|
<reponame>sagarbabalsure/pythonCodes
# class animal inherit all class object's attributes
class animal(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("{} is eating {}".format(self.name, food))
# class dog inherit all class animal's attributes
# plus its attributes
class dog(animal):
def fetch(self, thing):
print("{} fetched {}".format(self.name, thing))
# class cat inherit all class animal's attributes
# plus its attributes
class cat(animal):
def cat_eat(self, eat):
print("{} eats {}".format(self.name, eat))
|
isspek/veracity-detection
|
RumourEval2019Models/Bert-MFajcik/task_A/datasets/RumourEvalDataset_BERT.py
|
<gh_stars>0
__author__ = "<NAME>"
import json
import torch
import torchtext as tt
from typing import List, Tuple
from pytorch_pretrained_bert import BertTokenizer
from torchtext.data import Example
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
"""
This file contains implementation of Bert-MFajcik datasets extending torchtext.data.Dataset class
"""
class RumourEval2019Dataset_BERTTriplets(tt.data.Dataset):
"""
Creates dataset, where each example is composed as triplet: (source post, previous post, target post)
"""
def __init__(self, path: str, fields: List[Tuple[str, tt.data.Field]], tokenizer: BertTokenizer,
max_length: int = 512, include_features=False, **kwargs):
max_length = max_length - 3 # Count without special tokens
sentiment_analyser = SentimentIntensityAnalyzer()
with open(path) as dataf:
data_json = json.load(dataf)
examples = []
# Each input needs to have at most 2 segments
# We will create following input
# - [CLS] source post, previous post [SEP] choice_1 [SEP]
for example in data_json["Examples"]:
make_ids = lambda x: tokenizer.convert_tokens_to_ids(tokenizer.tokenize(x))
text = make_ids(example["spacy_processed_text"])
prev = make_ids(example["spacy_processed_text_prev"])
src = make_ids(example["spacy_processed_text_src"])
segment_A = src + prev
segment_B = text
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
# truncate if exceeds max length
if len(text_ids) > max_length:
# Truncate segment A
segment_A = segment_A[:max_length // 2]
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
if len(text_ids) > max_length:
# Truncate also segment B
segment_B = segment_B[:max_length // 2]
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
segment_ids = [0] * (len(segment_A) + 2) + [1] * (len(segment_B) + 1)
input_mask = [1] * len(segment_ids)
if include_features:
example_list = list(example.values()) + [text_ids, segment_ids, input_mask]
else:
sentiment = sentiment_analyser.polarity_scores(example["raw_text"])
example_list = [example["id"], example["branch_id"], example["tweet_id"], example["stance_label"],
example["veracity_label"],
"\n-----------\n".join(
[example["raw_text_src"], example["raw_text_prev"], example["raw_text"]]),
example["issource"], sentiment["pos"], sentiment["neu"], sentiment["neg"]] + [
text_ids, segment_ids, input_mask]
examples.append(Example.fromlist(example_list, fields))
super(RumourEval2019Dataset_BERTTriplets, self).__init__(examples, fields, **kwargs)
@staticmethod
def prepare_fields_for_text():
"""
BERT [PAD] token has index 0
"""
text_field = lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=True, pad_token=0)
return [
('id', tt.data.RawField()),
('branch_id', tt.data.RawField()),
('tweet_id', tt.data.RawField()),
('stance_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('veracity_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('raw_text', tt.data.RawField()),
('issource', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('sentiment_pos', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('sentiment_neu', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('sentiment_neg', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('text', text_field()),
('type_mask', text_field()),
('input_mask', text_field())]
@staticmethod
def prepare_fields_for_f_and_text(
text_field=lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=True, pad_token=0),
float_field=lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=False,
dtype=torch.float)):
return [
('avgw2v', tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True)),
('hasnegation', float_field()),
('hasswearwords', float_field()),
('capitalratio', float_field()),
('hasperiod', float_field()),
('hasqmark', float_field()),
('hasemark', float_field()),
('hasurl', float_field()),
('haspic', float_field()),
('charcount', float_field()),
('wordcount', float_field()),
('issource', float_field()),
('Word2VecSimilarityWrtOther', float_field()),
('Word2VecSimilarityWrtSource', float_field()),
('Word2VecSimilarityWrtPrev', float_field()),
('raw_text', tt.data.RawField()),
('spacy_processed_text', tt.data.RawField()),
('spacy_processed_BLvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_POSvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_DEPvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_NERvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('src_num_false_synonyms', float_field()),
('src_num_false_antonyms', float_field()),
('thread_num_false_synonyms', float_field()),
('thread_num_false_antonyms', float_field()),
('src_unconfirmed', float_field()),
('src_rumour', float_field()),
('thread_unconfirmed', float_field()),
('thread_rumour', float_field()),
('src_num_wh', float_field()),
('thread_num_wh', float_field()),
('id', tt.data.RawField()),
('branch_id', tt.data.RawField()),
('tweet_id', tt.data.RawField()),
('stance_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('veracity_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('raw_text_prev', tt.data.RawField()),
('raw_text_src', tt.data.RawField()),
('spacy_processed_text_prev', tt.data.RawField()),
('spacy_processed_text_src', tt.data.RawField()),
('text', text_field()),
('type_mask', text_field()),
('input_mask', text_field())
]
class RumourEval2019Dataset_BERTTriplets_with_Tags(tt.data.Dataset):
"""
Creates dataset similar to RumourEval2019Dataset_BERTTriplets, but this one also contains
word-level POS/NER/DEP tags
"""
def __init__(self, path: str, fields: List[Tuple[str, tt.data.Field]], tokenizer: BertTokenizer,
max_length: int = 512, include_features=False, **kwargs):
max_length = max_length - 3 # Count without special tokens
sentiment_analyser = SentimentIntensityAnalyzer()
with open(path) as dataf:
data_json = json.load(dataf)
examples = []
# Each input needs to have at most 2 segments
# We will create following input
# - [CLS] source post, previous post [SEP] choice_1 [SEP]
# more important parts are towards the end, usually, and they can be truncated
for example in data_json["Examples"]:
def make_ids_with_mapping(text):
make_ids = lambda x: tokenizer.convert_tokens_to_ids(tokenizer.tokenize(x))
word_tokens = text.split()
ids_mapping = {i: make_ids(w) for i, w in enumerate(word_tokens)}
ids = []
for subwordindices in ids_mapping.values(): ids += subwordindices
return ids_mapping, ids
text_mapping, text = make_ids_with_mapping(example["spacy_processed_text"])
prev_mapping, prev = make_ids_with_mapping(example["spacy_processed_text_prev"])
src_mapping, src = make_ids_with_mapping(example["spacy_processed_text_src"])
segment_A = src + prev
segment_B = text
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
NER_segment_B = []
for k, v in text_mapping.items():
for id in v: NER_segment_B.append(example['spacy_processed_NERvec'][k])
DEP_segment_B = []
for k, v in text_mapping.items():
for id in v: DEP_segment_B.append(example['spacy_processed_DEPvec'][k])
POS_segment_B = []
for k, v in text_mapping.items():
for id in v: POS_segment_B.append(example['spacy_processed_POSvec'][k])
# truncate if exceeds max length
if len(text_ids) > max_length:
# Truncate segment A
segment_A = segment_A[:max_length // 2]
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
if len(text_ids) > max_length:
# Truncate also segment B
segment_B = segment_B[:max_length // 2]
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
NER_segment_B = NER_segment_B[:max_length // 2]
DEP_segment_B = DEP_segment_B[:max_length // 2]
POS_segment_B = POS_segment_B[:max_length // 2]
NER_mask_ids = [0] * (len(segment_A) + 2) + NER_segment_B + [0]
DEP_mask_ids = [0] * (len(segment_A) + 2) + DEP_segment_B + [0]
POS_mask_ids = [0] * (len(segment_A) + 2) + POS_segment_B + [0]
segment_ids = [0] * (len(segment_A) + 2) + [1] * (len(segment_B) + 1)
# example_list = list(example.values())[:-3] + [text_ids, segment_ids]
if include_features:
example_list = list(example.values()) + [text_ids, segment_ids, NER_mask_ids]
else:
sentiment = sentiment_analyser.polarity_scores(example["raw_text"])
example_list = [example["id"], example["branch_id"], example["tweet_id"], example["stance_label"],
example["veracity_label"],
"\n-----------\n".join(
[example["raw_text_src"], example["raw_text_prev"], example["raw_text"]]),
example["issource"], sentiment["pos"], sentiment["neu"], sentiment["neg"]] + [
text_ids, segment_ids, NER_mask_ids, DEP_mask_ids, POS_mask_ids]
examples.append(Example.fromlist(example_list, fields))
super(RumourEval2019Dataset_BERTTriplets_with_Tags, self).__init__(examples, fields, **kwargs)
@staticmethod
def prepare_fields_for_text():
"""
BERT [PAD] token has index 0
"""
text_field = lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=True, pad_token=0)
return [
('id', tt.data.RawField()),
('branch_id', tt.data.RawField()),
('tweet_id', tt.data.RawField()),
('stance_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('veracity_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('raw_text', tt.data.RawField()),
('issource', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('sentiment_pos', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('sentiment_neu', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('sentiment_neg', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('text', text_field()),
('type_mask', text_field()),
('ner_mask', text_field()),
('dep_mask', text_field()),
('pos_mask', text_field())]
@staticmethod
def prepare_fields_for_f_and_text(
text_field=lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=True, pad_token=0),
float_field=lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=False,
dtype=torch.float)):
return [
('avgw2v', tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True)),
('hasnegation', float_field()),
('hasswearwords', float_field()),
('capitalratio', float_field()),
('hasperiod', float_field()),
('hasqmark', float_field()),
('hasemark', float_field()),
('hasurl', float_field()),
('haspic', float_field()),
('charcount', float_field()),
('wordcount', float_field()),
('issource', float_field()),
('Word2VecSimilarityWrtOther', float_field()),
('Word2VecSimilarityWrtSource', float_field()),
('Word2VecSimilarityWrtPrev', float_field()),
('raw_text', tt.data.RawField()),
('spacy_processed_text', tt.data.RawField()),
('spacy_processed_BLvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_POSvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_DEPvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_NERvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('src_num_false_synonyms', float_field()),
('src_num_false_antonyms', float_field()),
('thread_num_false_synonyms', float_field()),
('thread_num_false_antonyms', float_field()),
('src_unconfirmed', float_field()),
('src_rumour', float_field()),
('thread_unconfirmed', float_field()),
('thread_rumour', float_field()),
('src_num_wh', float_field()),
('thread_num_wh', float_field()),
('id', tt.data.RawField()),
('branch_id', tt.data.RawField()),
('tweet_id', tt.data.RawField()),
('stance_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('veracity_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('raw_text_prev', tt.data.RawField()),
('raw_text_src', tt.data.RawField()),
('spacy_processed_text_prev', tt.data.RawField()),
('spacy_processed_text_src', tt.data.RawField()),
('text', text_field()),
('type_mask', text_field()),
('ner_mask', text_field())
]
class RumourEval2019Dataset_BERTTriplets_3Segments(tt.data.Dataset):
"""
Creates dataset similar to RumourEval2019Dataset_BERTTriplets, but this one
separates src text and prev text via [SEP] token and different segment embedding
"""
def __init__(self, path: str, fields: List[Tuple[str, tt.data.Field]], tokenizer: BertTokenizer,
max_length: int = 512, include_features=False, **kwargs):
max_length = max_length - 3 # Count without special tokens
with open(path) as dataf:
data_json = json.load(dataf)
examples = []
# Each input needs to have at most 2 segments
# We will create following input
# - [CLS] source post, previous post [SEP] choice_1 [SEP]
for example in data_json["Examples"]:
make_ids = lambda x: tokenizer.convert_tokens_to_ids(tokenizer.tokenize(x))
text = make_ids(example["spacy_processed_text"])
prev = make_ids(example["spacy_processed_text_prev"])
src = make_ids(example["spacy_processed_text_src"])
segment_A = src
segment_C = prev
segment_B = text
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + [tokenizer.vocab["[SEP]"]] + segment_C + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
# truncate if exceeds max length
if len(text_ids) > max_length:
# Truncate segment A
segment_C = segment_C[:max_length // 2]
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + [tokenizer.vocab["[SEP]"]] + segment_C + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
if len(text_ids) > max_length:
# Truncate segment A
segment_A = segment_A[:max_length // 2]
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + [tokenizer.vocab["[SEP]"]] + segment_C + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
if len(text_ids) > max_length:
# Truncate also segment B
segment_B = segment_B[:max_length // 2]
text_ids = [tokenizer.vocab["[CLS]"]] + segment_A + [tokenizer.vocab["[SEP]"]] + segment_C + \
[tokenizer.vocab["[SEP]"]] + segment_B + [tokenizer.vocab["[SEP]"]]
segment_ids = [0] * (len(segment_A) + 2) + [2] * (len(segment_C) + 1) + [1] * (len(segment_B) + 1)
# example_list = list(example.values())[:-3] + [text_ids, segment_ids]
if include_features:
example_list = list(example.values()) + [text_ids, segment_ids]
else:
example_list = [example["id"], example["branch_id"], example["tweet_id"], example["stance_label"],
example["veracity_label"],
"\n-----------\n".join(
[example["raw_text_src"], example["raw_text_prev"], example["raw_text"]]),
example["issource"]] + [text_ids, segment_ids]
examples.append(Example.fromlist(example_list, fields))
super(RumourEval2019Dataset_BERTTriplets_3Segments, self).__init__(examples, fields, **kwargs)
@staticmethod
def prepare_fields_for_text():
"""
BERT [PAD] token has index 0
"""
text_field = lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=True, pad_token=0)
return [
('id', tt.data.RawField()),
('branch_id', tt.data.RawField()),
('tweet_id', tt.data.RawField()),
('stance_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('veracity_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('raw_text', tt.data.RawField()),
('issource', tt.data.Field(use_vocab=False, batch_first=True, sequential=False)),
('text', text_field()),
('type_mask', text_field())]
@staticmethod
def prepare_fields_for_f_and_text(
text_field=lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=True, pad_token=0),
float_field=lambda: tt.data.Field(use_vocab=False, batch_first=True, sequential=False,
dtype=torch.float)):
return [
('avgw2v', tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True)),
('hasnegation', float_field()),
('hasswearwords', float_field()),
('capitalratio', float_field()),
('hasperiod', float_field()),
('hasqmark', float_field()),
('hasemark', float_field()),
('hasurl', float_field()),
('haspic', float_field()),
('charcount', float_field()),
('wordcount', float_field()),
('issource', float_field()),
('Word2VecSimilarityWrtOther', float_field()),
('Word2VecSimilarityWrtSource', float_field()),
('Word2VecSimilarityWrtPrev', float_field()),
('raw_text', tt.data.RawField()),
('spacy_processed_text', tt.data.RawField()),
('spacy_processed_BLvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_POSvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_DEPvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('spacy_processed_NERvec',
tt.data.Field(use_vocab=False, dtype=torch.float, batch_first=True, pad_token=0)),
('src_num_false_synonyms', float_field()),
('src_num_false_antonyms', float_field()),
('thread_num_false_synonyms', float_field()),
('thread_num_false_antonyms', float_field()),
('src_unconfirmed', float_field()),
('src_rumour', float_field()),
('thread_unconfirmed', float_field()),
('thread_rumour', float_field()),
('src_num_wh', float_field()),
('thread_num_wh', float_field()),
('id', tt.data.RawField()),
('branch_id', tt.data.RawField()),
('tweet_id', tt.data.RawField()),
('stance_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('veracity_label', tt.data.Field(sequential=False, use_vocab=False, batch_first=True, is_target=True)),
('raw_text_prev', tt.data.RawField()),
('raw_text_src', tt.data.RawField()),
('spacy_processed_text_prev', tt.data.RawField()),
('spacy_processed_text_src', tt.data.RawField()),
('text', text_field()),
('type_mask', text_field())
]
|
babyhuey/qtiworks
|
qtiworks-jqtiplus/src/main/java/uk/ac/ed/ph/jqtiplus/value/TextFormat.java
|
/* Copyright (c) 2012-2013, University of Edinburgh.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* * Neither the name of the University of Edinburgh 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.
*
*
* This software is derived from (and contains code from) QTItools and MathAssessEngine.
* QTItools is (c) 2008, University of Southampton.
* MathAssessEngine is (c) 2010, University of Edinburgh.
*/
package uk.ac.ed.ph.jqtiplus.value;
import uk.ac.ed.ph.jqtiplus.exception.QtiParseException;
import uk.ac.ed.ph.jqtiplus.types.Stringifiable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* plain -
* Indicates that the text to be entered by the candidate is plain text.
* This format is suitable for short unstructured responses. Delivery
* engines should preserve white-space characters in candidate input except
* where a response consists only of white-space characters, in which case
* it should be treated as an empty string (NULL).
* <p>
* preFormatted - Indicates that the text to be entered by the candidate is pre-formatted and should be rendered in a way consistent with the definition of pre
* in [XHTML]. Delivery engines must preserve white-space characters except where a response consists only of white-space characters, in which case it should be
* treated as an empty string (NULL).
* <p>
* xhtml - Indicates that the text to be entered by the candidate is structured text. The value of the response variable is text marked up in XHTML. The
* delivery engine should present an interface suitable for capturing structured text, this might be plain typed text interpreted with a set of simple text
* markup conventions such as those used in wiki page editors or a complete WYSIWYG editor.
*
* @author <NAME>
*/
public enum TextFormat implements Stringifiable {
/**
* plain type.
*/
PLAIN("plain"),
/**
* preFormatted type.
*/
PRE_FORMATTED("preFormatted"),
/**
* xhtml type.
*/
XHTML("xhtml");
/** Name of this class in xml schema. */
public static final String QTI_CLASS_NAME = "textFormat";
private static Map<String, TextFormat> formats;
static {
formats = new HashMap<String, TextFormat>();
for (final TextFormat type : TextFormat.values()) {
formats.put(type.textFormat, type);
}
}
private String textFormat;
private TextFormat(String textFormat) {
this.textFormat = textFormat;
}
/**
* Returns true if this textFormat is plain; false otherwise.
*
* @return true if this textFormat is plain; false otherwise
*/
public boolean isPlain() {
return this == PLAIN;
}
/**
* Returns true if this textFormat is preFormatted; false otherwise.
*
* @return true if this textFormat is preFormatted; false otherwise
*/
public boolean isPreFormatted() {
return this == PRE_FORMATTED;
}
/**
* Returns true if this textFormat is xhtml; false otherwise.
*
* @return true if this textFormat is xhtml; false otherwise
*/
public boolean isXhtml() {
return this == XHTML;
}
@Override
public String toQtiString() {
return textFormat;
}
/**
* Returns parsed <code>TextFormat</code> from given <code>String</code>.
*
* @param textFormat <code>String</code> representation of <code>TextFormat</code>
* @return parsed <code>TextFormat</code> from given <code>String</code>
* @throws QtiParseException if given <code>String</code> is not valid <code>TextFormat</code>
*/
public static TextFormat parseTextFormat(String textFormat) {
final TextFormat result = formats.get(textFormat);
if (result == null) {
throw new QtiParseException("Invalid " + QTI_CLASS_NAME + " '" + textFormat + "'.");
}
return result;
}
/**
* Returns intersection of two given types sets (order is not important).
*
* @param firstSet first set of types
* @param secondSet second set of types
* @return intersection of two given types sets
*/
public static TextFormat[] intersection(TextFormat[] firstSet, TextFormat[] secondSet) {
final List<TextFormat> paramTypes = new ArrayList<TextFormat>();
for (final TextFormat type : firstSet) {
if (Arrays.binarySearch(secondSet, type) >= 0) {
paramTypes.add(type);
}
}
return paramTypes.toArray(new TextFormat[] {});
}
}
|
tum-gis/opendrive-ade-citygml4j
|
src/main/java/org/citygml/ade/opendrive/adapter/geometry/OpenDRIVECurveAdapter.java
|
package org.citygml.ade.opendrive.adapter.geometry;
import org.citygml.ade.opendrive.adapter.core.OpenDRIVEAdditionalDataPropertyAdapter;
import org.citygml.ade.opendrive.model.geometry.OpenDRIVECurve;
import org.citygml.ade.opendrive.module.OpenDRIVEADEModule;
import org.xmlobjects.annotation.XMLElement;
import org.xmlobjects.builder.ObjectBuildException;
import org.xmlobjects.gml.adapter.geometry.primitives.AbstractCurveAdapter;
import org.xmlobjects.gml.adapter.geometry.primitives.CurveAdapter;
import org.xmlobjects.gml.model.geometry.primitives.Curve;
import org.xmlobjects.serializer.ObjectSerializeException;
import org.xmlobjects.serializer.ObjectSerializer;
import org.xmlobjects.stream.XMLReadException;
import org.xmlobjects.stream.XMLReader;
import org.xmlobjects.stream.XMLWriteException;
import org.xmlobjects.stream.XMLWriter;
import org.xmlobjects.xml.Attributes;
import org.xmlobjects.xml.Element;
import org.xmlobjects.xml.Namespaces;
import javax.xml.namespace.QName;
@XMLElement(name = "OpenDRIVECurve", namespaceURI = OpenDRIVEADEModule.OPENDRIVEADE_NAMESPACE)
public class OpenDRIVECurveAdapter extends AbstractCurveAdapter<OpenDRIVECurve> {
// Does not work extending CurveAdapter since CurveAdapter extends AbstractCurveAdapter<Curve>
// and therefore also OpenDRIVECurveAdapter extends AbstractCurveAdapter<Curve> and is therefore not correctly
// recognized during the XML writing or since OpenDRIVECurve is a Curve the CurveAdapter methods are called
// private static CurveAdapter curveAdapter = new CurveAdapter();
public OpenDRIVECurveAdapter() {
}
@Override
public OpenDRIVECurve createObject(QName name, Object parent) throws ObjectBuildException {
return new OpenDRIVECurve();
}
@Override
public void buildChildObject(OpenDRIVECurve object, QName name, Attributes attributes, XMLReader reader) throws ObjectBuildException, XMLReadException {
// if (OpenDRIVEADEModule.OPENDRIVEADE_NAMESPACE.equals(name.getNamespaceURI())) {
// switch (name.getLocalPart()) {
//
// }
// } else {
// // If the namespace is not from the ADE then the element is from the citygml standard module
// super.buildChildObject(object, name, attributes, reader);
// }
// No OpenDRIVE ADE properties
// super.buildChildObject(object, name, attributes, reader);
// this.curveAdapter.buildChildObject(object, name, attributes, reader);
new CurveAdapter().buildChildObject(object, name, attributes, reader);
}
@Override
public Element createElement(OpenDRIVECurve object, Namespaces namespaces) throws ObjectSerializeException {
return Element.of(OpenDRIVEADEModule.OPENDRIVEADE_NAMESPACE, "OpenDRIVECurve");
}
@Override
public void writeChildElements(OpenDRIVECurve object, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
// No OpenDRIVE ADE properties
// super.writeChildElements(object, namespaces, writer);
// this.curveAdapter.writeChildElements(object, namespaces, writer);
new CurveAdapter().writeChildElements(object, namespaces, writer);
if (object.getAdditionalData() != null)
writer.writeElementUsingSerializer(Element.of(OpenDRIVEADEModule.OPENDRIVEADE_NAMESPACE, "additionalData"),
object.getAdditionalData(), OpenDRIVEAdditionalDataPropertyAdapter.class, namespaces);
}
}
|
pktm14/utilities
|
src/main/java/edu/scripps/yates/utilities/proteomicsmodel/factories/TissueEx.java
|
<filename>src/main/java/edu/scripps/yates/utilities/proteomicsmodel/factories/TissueEx.java
package edu.scripps.yates.utilities.proteomicsmodel.factories;
import java.io.Serializable;
import edu.scripps.yates.utilities.proteomicsmodel.Tissue;
public class TissueEx implements Tissue, Serializable {
/**
*
*/
private static final long serialVersionUID = -8230799076830462784L;
private final String tissueID;
private String name;
public TissueEx(String tissueID) {
super();
this.tissueID = tissueID;
}
/**
* @return the tissueID
*/
@Override
public String getTissueID() {
return tissueID;
}
/**
* @return the name
*/
@Override
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TissueEx [tissueID=" + tissueID + ", name=" + name + "]";
}
}
|
bsf2dev/bsf
|
Source/Foundation/bsfEngine/Utility/BsShapeMeshes3D.h
|
//************************************ bs::framework - Copyright 2018 <NAME> **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "BsPrerequisites.h"
#include "Image/BsColor.h"
#include "Math/BsAABox.h"
#include "Math/BsRect3.h"
namespace bs
{
/** @addtogroup Utility-Engine
* @{
*/
/** Helper class for easily creating common 3D shapes. */
class BS_EXPORT ShapeMeshes3D
{
public:
/**
* Fills the mesh data with vertices representing an outline of axis aligned box.
*
* @param[in] box Axis aligned box to create the mesh data for
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for 8 vertices and 24 indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireAABox(const AABox& box, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the mesh data with vertices representing a solid axis aligned box.
*
* @param[in] box Axis aligned box to create the mesh data for
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* Vector3 VES_NORMAL
* 32bit index buffer
* Enough space for 24 vertices and 36 indices
* Optionally it may also have:
* Vector2 VES_TEXCOORD
* Vector4 VES_TANGENT
* @note
* Primitives are output in the form of a triangle list.
*/
static void solidAABox(const AABox& box, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the mesh data with vertices representing an outline of a sphere.
*
* @param[in] sphere Sphere to get the mesh data for
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the sphere will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for 3 * ((quality + 1) * 5) vertices
* Enough space for 6 * ((quality + 1) * 5 - 1) indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireSphere(const Sphere& sphere, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset,
UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing an outline of a hemisphere.
*
* @param[in] sphere Sphere to get the mesh data for
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the sphere will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for 3 * ((quality + 1) * 5) vertices
* Enough space for 6 * ((quality + 1) * 5 - 1) indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireHemisphere(const Sphere& sphere, const SPtr<MeshData>& meshData, UINT32 vertexOffset,
UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing a sphere.
*
* @param[in] sphere Sphere to get the mesh data for
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the sphere will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* Vector3 VES_NORMAL
* 32bit index buffer
* Enough space for 20 * (4 * (3 ^ quality)) vertices
* Enough space for 20 * (4 * (3 ^ quality)) indices
* Optionally it may also have:
* Vector2 VES_TEXCOORD
* Vector4 VES_TANGENT
* @note
* Primitives are output in the form of a triangle list.
*/
static void solidSphere(const Sphere& sphere, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset,
UINT32 quality = 1);
/**
* Fills the mesh data with vertices representing an outline of an arc.
*
* @param[in] center Center of the arc to generate geometry for.
* @param[in] radius Radius of the arc to generate geometry for.
* @param[in] normal Normal around which the arc is generated. Arc geometry will be perpendicular
* to the normal.
* @param[in] startAngle Angle at which the arc starts.
* @param[in] amountAngle Angle that the arc spans.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the arc will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for ((quality + 1) * 5) vertices
* Enough space for (((quality + 1) * 5 - 1) * 2) indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireArc(const Vector3& center, float radius, const Vector3& normal, Degree startAngle, Degree amountAngle,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing a solid double-sided arc.
*
* @param[in] center Center of the arc to generate geometry for.
* @param[in] radius Radius of the arc to generate geometry for.
* @param[in] normal Normal around which the arc is generated. Arc geometry will be perpendicular to
* the normal.
* @param[in] startAngle Angle at which the arc starts.
* @param[in] amountAngle Angle that the arc spans.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the arc will have. Higher level means higher
* quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* Vector3 VES_NORMAL
* 32bit index buffer
* Enough space for ((quality + 1) * 5 + 1) * 2 vertices
* Enough space for (((quality + 1) * 5 - 1) * 6) indices
* Optionally it may also have:
* Vector2 VES_TEXCOORD
* Vector4 VES_TANGENT
* @note
* Primitives are output in the form of a triangle list.
*/
static void solidArc(const Vector3& center, float radius, const Vector3& normal, Degree startAngle, Degree amountAngle,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing an outline of a disc.
*
* @param[in] center Center of the disc to generate geometry for.
* @param[in] radius Radius of the disc to generate geometry for.
* @param[in] normal Normal around which the disc is generated. Disc geometry will be perpendicular
* to the normal.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the disc will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for ((quality + 1) * 5) vertices
* Enough space for (((quality + 1) * 5 - 1) * 2) indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireDisc(const Vector3& center, float radius, const Vector3& normal, const SPtr<MeshData>& meshData,
UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing a solid double-sided disc.
*
* @param[in] center Center of the disc to generate geometry for.
* @param[in] radius Radius of the disc to generate geometry for.
* @param[in] normal Normal around which the disc is generated. Disc geometry will be perpendicular
* to the normal.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the disc will have. Higher level means higher
* quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* Vector3 VES_NORMAL
* 32bit index buffer
* Enough space for ((quality + 1) * 5 + 1) * 2 vertices
* Enough space for (((quality + 1) * 5 - 1) * 6) indices
* @note
* Primitives are output in the form of a triangle list.
*/
static void solidDisc(const Vector3& center, float radius, const Vector3& normal, const SPtr<MeshData>& meshData,
UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing an outline of an camera frustum. Frustum will be facing -z and be
* positioned at world origin.
*
* @param[in] position Starting point for the frustum.
* @param[in] aspect Aspect ratio (width / height).
* @param[in] FOV Horizontal field of view angle.
* @param[in] near Distance to near clipping plane.
* @param[in] far Distance to far clipping plane.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for 8 vertices and 24 indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireFrustum(const Vector3& position, float aspect, Degree FOV, float near, float far,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the mesh data with vertices representing a wireframe cone.
*
* @param[in] base World position of the cone base.
* @param[in] normal Direction of the pointed part of the cone.
* @param[in] height Cone height (distance from base to the top).
* @param[in] radius Cone radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cones.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cone will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for ((quality + 1) * 4 + 5) vertices
* Enough space for (((quality + 1) * 4 + 4) * 2) indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireCone(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing a solid cone.
*
* @param[in] base World position of the cone base.
* @param[in] normal Direction of the pointed part of the cone.
* @param[in] height Cone height (distance from base to the top).
* @param[in] radius Cone radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cones.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cone will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* Vector3 VES_NORMAL
* 32bit index buffer
* Enough space for ((quality + 1) * 4) * 3 + 1 vertices
* Enough space for (((quality + 1) * 4) * 6) indices
* Optionally it may also have:
* Vector2 VES_TEXCOORD
* Vector4 VES_TANGENT
* @note
* Primitives are output in the form of a triangle list.
*/
static void solidCone(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing a wireframe cylinder.
*
* @param[in] base World position of the cylinder base.
* @param[in] normal Orientation of the cylinder (height gets applied in this direction).
* @param[in] height Cylinder height (distance from base to the top).
* @param[in] radius Cylinder radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cylinders.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cylinder will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for ((quality + 1) * 4) * 2) vertices
* Enough space for ((quality + 1) * 4) * 6) indices
* @note
* Primitives are output in the form of a line list.
*/
static void wireCylinder(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing a solid cylinder.
*
* @param[in] base World position of the cylinder base.
* @param[in] normal Orientation of the cylinder (height gets applied in this direction).
* @param[in] height Cylinder height (distance from base to the top).
* @param[in] radius Cylinder radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cylinders.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cylinder will have. Higher level means
* higher quality but also more vertices and primitives.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* Vector3 VES_NORMAL
* 32bit index buffer
* Enough space for ((quality + 1) * 4 + 1) * 4) vertices
* Enough space for ((quality + 1) * 4) * 12) indices
* Optionally it may also have:
* Vector2 VES_TEXCOORD
* Vector4 VES_TANGENT
* @note
* Primitives are output in the form of a triangle list.
*/
static void solidCylinder(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset, UINT32 quality = 10);
/**
* Fills the mesh data with vertices representing a quad (4 triangles, two sided).
*
* @param[in] area Area in which to draw the quad.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* Vector3 VES_NORMAL
* 32bit index buffer
* Enough space for 8 vertices and 12 indices
* Optionally it may also have:
* Vector2 VES_TEXCOORD
* Vector4 VES_TANGENT
* @note
* Primitives are output in the form of a triangle list.
*/
static void solidQuad(const Rect3& area, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the mesh data with vertices representing a per-pixel line.
*
* @param[in] a Start point of the line.
* @param[in] b End point of the line.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for 2 vertices and 2 indices
* @note
* Primitives are output in the form of a line list.
*/
static void pixelLine(const Vector3& a, const Vector3& b, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the mesh data with vertices representing an anti-aliased line of specific width. Antialiasing is done
* using alpha blending.
*
* @param[in] a Start point of the line.
* @param[in] b End point of the line.
* @param[in] up Up direction to which the line will run perpendicular to.
* @param[in] width Width of the line.
* @param[in] borderWidth Width of the anti-aliased border.
* @param[in] color Color of the line.
* @param[in, out] meshData Mesh data that will be populated by this method.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* UINT32 VES_COLOR
* 32bit index buffer
* Enough space for 8 vertices and 30 indices
* @note
* Primitives are output in the form of a triangle list.
*/
static void antialiasedLine(const Vector3& a, const Vector3& b, const Vector3& up, float width, float borderWidth, const Color& color,
const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the mesh data with vertices representing per-pixel lines.
*
* @param[in] linePoints A list of start and end points for the lines. Must be a multiple of 2.
* @param[in, out] meshData Mesh data that will be populated.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* 32bit index buffer
* Enough space for (numLines * 2) vertices and (numLines * 2) indices
* @note
* Primitives are output in the form of a line list.
*/
static void pixelLineList(const Vector<Vector3>& linePoints, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the mesh data with vertices representing anti-aliased lines of specific width. Antialiasing is done using
* alpha blending.
*
* @param[in] linePoints A list of start and end points for the lines. Must be a multiple of 2.
* @param[in] up Up direction to which the line will run perpendicular to.
* @param[in] width Width of the line.
* @param[in] borderWidth Width of the anti-aliased border.
* @param[in] color Color of the line.
* @param[in, out] meshData Mesh data that will be populated by this method.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*
* @note
* Provided MeshData must have some specific elements at least:
* Vector3 VES_POSITION
* UINT32 VES_COLOR
* 32bit index buffer
* Enough space for (numLines * 8) vertices and (numLines * 30) indices
* @note
* Primitives are output in the form of a triangle list.
*/
static void antialiasedLineList(const Vector<Vector3>& linePoints, const Vector3& up, float width, float borderWidth,
const Color& color, const SPtr<MeshData>& meshData, UINT32 vertexOffset, UINT32 indexOffset);
/**
* Fills the provided buffers with position and index data representing an outline of an axis aligned box. Use
* getNumElementsWireAABox() to determine the required sizes of the output buffers.
*
* @param[in] box Box to create geometry for.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes.
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void wireAABox(const AABox& box, UINT8* outVertices, UINT32 vertexOffset, UINT32 vertexStride,
UINT32* outIndices, UINT32 indexOffset);
/**
* Fills the provided buffers with position and index data representing a solid axis aligned box. Use
* getNumElementsAABox() to determine the required sizes of the output buffers.
*
* @param[in] box Box to create geometry for.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[out] outNormals Pre-allocated output buffer that will store the vertex normal data.
* @param[out] outUV Pre-allocated output buffer that will store the vertex UV data. Set to null if not
* required.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void solidAABox(const AABox& box, UINT8* outVertices, UINT8* outNormals, UINT8* outUV, UINT32 vertexOffset,
UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset);
/**
* Fills the provided buffers with position and index data representing a sphere. Use getNumElementsSphere() to
* determine the required sizes of the output buffers.
*
* @param[in] sphere Sphere to create geometry for.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[out] outNormals Pre-allocated output buffer that will store the vertex normal data. Can be null if
* normals aren't needed.
* @param[out] outUV Pre-allocated output buffer that will store the vertex UV data. Set to null if not
* required.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the sphere will have. Higher level means higher
* quality but also more vertices and primitives.
*/
static void solidSphere(const Sphere& sphere, UINT8* outVertices, UINT8* outNormals, UINT8* outUV,
UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset, UINT32 quality);
/**
* Fills the provided buffers with position and index data representing an outline of an arc. Use
* getNumElementWiresArc() to determine the required sizes of the output buffers.
*
* @param[in] center Center of the arc to generate geometry for.
* @param[in] radius Radius of the arc to generate geometry for.
* @param[in] normal Normal around which the arc is generated. Arc geometry will be perpendicular to the
* normal.
* @param[in] startAngle Angle at which the arc starts.
* @param[in] amountAngle Angle that the arc spans.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes.
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the arc will have. Higher level means higher
* quality but also more vertices and primitives.
*/
static void wireArc(const Vector3& center, float radius, const Vector3& normal, Degree startAngle, Degree amountAngle,
UINT8* outVertices, UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset, UINT32 quality);
/**
* Fills the provided buffers with position and index data representing a solid arc. Use getNumElementsArc() to
* determine the required sizes of the output buffers.
*
* @param[in] center Center of the arc to generate geometry for.
* @param[in] radius Radius of the arc to generate geometry for.
* @param[in] normal Normal around which the arc is generated. Arc geometry will be perpendicular to the
* normal.
* @param[in] startAngle Angle at which the arc starts.
* @param[in] amountAngle Angle that the arc spans.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[out] outNormals Pre-allocated output buffer that will store the vertex normal data.
* @param[out] outUV Pre-allocated output buffer that will store the vertex UV data. Set to null if not
* required.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the arc will have. Higher level means higher
* quality but also more vertices and primitives.
*/
static void solidArc(const Vector3& center, float radius, const Vector3& normal, Degree startAngle,
Degree amountAngle, UINT8* outVertices, UINT8* outNormals, UINT8* outUV, UINT32 vertexOffset,
UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset, UINT32 quality);
/**
* Fills the provided buffers with position and index data representing an outline of a camera frustum. Use
* getNumElementsFrustum() to determine the required sizes of the output buffers.
*
* @param[in] position Starting point for the frustum.
* @param[in] aspect Aspect ratio (width / height).
* @param[in] FOV Horizontal field of view angle.
* @param[in] near Distance to near clipping plane.
* @param[in] far Distance to far clipping plane.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes.
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void wireFrustum(const Vector3& position, float aspect, Degree FOV, float near, float far,
UINT8* outVertices, UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset);
/**
* Fills the provided buffers with position and index data representing a solid cone. Use getNumElementsCone() to
* determine the required sizes of the output buffers.
*
* @param[in] base World position of the cone base.
* @param[in] normal Direction of the pointed part of the cone.
* @param[in] height Cone height (distance from base to the top).
* @param[in] radius Cone radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cones.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[out] outNormals Pre-allocated output buffer that will store the vertex normal data. Can be null if
* normals aren't needed.
* @param[out] outUV Pre-allocated output buffer that will store the vertex UV data. Set to null if not
* required.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cone will have. Higher level means higher
* quality but also more vertices and primitives.
*/
static void solidCone(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
UINT8* outVertices, UINT8* outNormals, UINT8* outUV, UINT32 vertexOffset, UINT32 vertexStride,
UINT32* outIndices, UINT32 indexOffset, UINT32 quality);
/**
* Fills the provided buffers with position and index data representing a wire cone. Use getNumElementsWireCone() to
* determine the required sizes of the output buffers.
*
* @param[in] base World position of the cone base.
* @param[in] normal Direction of the pointed part of the cone.
* @param[in] height Cone height (distance from base to the top).
* @param[in] radius Cone radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cones.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cone will have. Higher level means higher
* quality but also more vertices and primitives.
*/
static void wireCone(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
UINT8* outVertices, UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset,
UINT32 quality);
/**
* Fills the provided buffers with position and index data representing a solid cylinder. Use getNumElementsCylinder() to
* determine the required sizes of the output buffers.
*
* @param[in] base World position of the cylinder base.
* @param[in] normal Orientation of the cylinder (height gets applied in this direction).
* @param[in] height Cylinder height (distance from base to the top).
* @param[in] radius Cylinder radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cylinders.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[out] outNormals Pre-allocated output buffer that will store the vertex normal data. Can be null if
* normals aren't needed.
* @param[out] outUV Pre-allocated output buffer that will store the vertex UV data. Set to null if not
* required.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cylinder will have. Higher level means higher
* quality but also more vertices and primitives.
*/
static void solidCylinder(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
UINT8* outVertices, UINT8* outNormals, UINT8* outUV, UINT32 vertexOffset, UINT32 vertexStride,
UINT32* outIndices, UINT32 indexOffset, UINT32 quality);
/**
* Fills the provided buffers with position and index data representing a wire cylinder. Use getNumElementsWireCylinder() to
* determine the required sizes of the output buffers.
*
* @param[in] base World position of the cylinder base.
* @param[in] normal Orientation of the cylinder (height gets applied in this direction).
* @param[in] height Cylinder height (distance from base to the top).
* @param[in] radius Cylinder radius (distance from base center to outer edge).
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical cylinders.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
* @param[in] quality Represents the level of tessellation the cylinder will have. Higher level means higher
* quality but also more vertices and primitives.
*/
static void wireCylinder(const Vector3& base, const Vector3& normal, float height, float radius, Vector2 scale,
UINT8* outVertices, UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset,
UINT32 quality);
/**
* Fills the provided buffers with position and index data representing a solid quad. Use getNumElementsQuad() to
* determine the required sizes of the output buffers.
*
* @param[in] area Area covered by the quad.
* @param[out] outVertices Pre-allocated output buffer that will store the vertex position data.
* @param[out] outNormals Pre-allocated output buffer that will store the vertex normal data.
* @param[out] outUV Pre-allocated output buffer that will store the vertex UV data. Set to null if not
* required.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and normal buffer)
* @param[out] outIndices Pre-allocated output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void solidQuad(const Rect3& area, UINT8* outVertices, UINT8* outNormals, UINT8* outUV, UINT32 vertexOffset,
UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset);
/** Calculates number of vertices and indices required for geometry of a solid axis aligned box. */
static void getNumElementsAABox(UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a wireframe axis aligned box. */
static void getNumElementsWireAABox(UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a solid sphere of the specified quality. */
static void getNumElementsSphere(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a wire sphere of the specified quality. */
static void getNumElementsWireSphere(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a wire hemisphere of the specified quality. */
static void getNumElementsWireHemisphere(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a solid arc of the specified quality. */
static void getNumElementsArc(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a wire arc of the specified quality. */
static void getNumElementsWireArc(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a solid desc of the specified quality. */
static void getNumElementsDisc(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a wire disc of the specified quality. */
static void getNumElementsWireDisc(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a solid cone of the specified quality. */
static void getNumElementsCone(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a wireframe cone of the specified quality. */
static void getNumElementsWireCone(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a solid cylinder of the specified quality. */
static void getNumElementsCylinder(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a wireframe cylinder of the specified quality. */
static void getNumElementsWireCylinder(UINT32 quality, UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a frustum. */
static void getNumElementsFrustum(UINT32& numVertices, UINT32& numIndices);
/** Calculates number of vertices and indices required for geometry of a quadrirateral. */
static void getNumElementsQuad(UINT32& numVertices, UINT32& numIndices);
static const UINT32 NUM_VERTICES_AA_LINE;
static const UINT32 NUM_INDICES_AA_LINE;
protected:
/**
* Fills the provided buffers with vertices representing a per-pixel line.
*
* @param[in] a Start point of the line.
* @param[in] b End point of the line.
* @param[out] outVertices Output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and color buffer)
* @param[out] outIndices Output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void pixelLine(const Vector3& a, const Vector3& b, UINT8* outVertices,
UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset);
/**
* Fills the provided buffers with vertices representing an antialiased line with a custom width.
*
* @param[in] a Start point of the line.
* @param[in] b End point of the line.
* @param[in] up Up direction to which the line will run perpendicular to.
* @param[in] width Width of the line.
* @param[in] borderWidth Width of the anti-aliased border.
* @param[in] color Color of the line.
* @param[out] outVertices Output buffer that will store the vertex position data.
* @param[out] outColors Output buffer that will store the vertex color data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and color buffer)
* @param[out] outIndices Output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void antialiasedLine(const Vector3& a, const Vector3& b, const Vector3& up, float width, float borderWidth,
const Color& color, UINT8* outVertices, UINT8* outColors, UINT32 vertexOffset, UINT32 vertexStride,
UINT32* outIndices, UINT32 indexOffset);
/**
* Fills the provided buffers with position data and indices representing an inner area of a polygon (basically a
* normal non-antialiased polygon).
*
* @param[in] points Points defining the polygon. First point is assumed to be the start and end point.
* @param[out] outVertices Output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and color buffer)
* @param[out] outIndices Output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void pixelSolidPolygon(const Vector<Vector3>& points, UINT8* outVertices,
UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset);
/**
* Fills the provided buffers with vertices representing a pixel-wide polygon border.
*
* @param[in] points Points defining the polygon. First point is assumed to be the start and end point.
* @param[out] outVertices Output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and color buffer)
* @param[out] outIndices Output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void pixelWirePolygon(const Vector<Vector3>& points, UINT8* outVertices,
UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset);
/**
* Fills the provided buffers with vertices representing an antialiased polygon.
*
* @param[in] points Points defining the polygon. First point is assumed to be the start and end point.
* @param[in] up Up direction to which the polygon will run perpendicular to.
* @param[in] borderWidth Width of the anti-aliased border.
* @param[in] color Color of the polygon.
* @param[out] outVertices Output buffer that will store the vertex position data.
* @param[out] outColors Output buffer that will store the vertex color data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and color buffer)
* @param[out] outIndices Output buffer that will store the index data. Indices are 32bit.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start writing at.
*/
static void antialiasedPolygon(const Vector<Vector3>& points, const Vector3& up, float borderWidth, const Color& color, UINT8* outVertices, UINT8* outColors,
UINT32 vertexOffset, UINT32 vertexStride, UINT32* outIndices, UINT32 indexOffset);
private:
/**
* Calculates the center of the provided vertices.
*
* @param[in] vertices Buffer containing vertices. Vertices must be of three dimensions at least.
* @param[in] numVertices Number of vertices to calculate the center for.
* @param[in] vertexStride Number of bytes between two vertices in the buffer.
* @return Center point of the vertices.
*/
static Vector3 calcCenter(UINT8* vertices, UINT32 numVertices, UINT32 vertexStride);
/**
* Subdivides the provided triangle so it approximates a curved surface of a sphere.
*
* @param[in] center Center of the sphere to approximate.
* @param[in] radius Radius of the sphere to approximate.
* @param[in] numLevels Number of times to subdivide the triangle. Higher number means better approximation.
* @param[in] a First corner of the triangle. Must be normalized.
* @param[in] b Second corner of the triangle. Must be normalized.
* @param[in] c Third corner of the triangle. Must be normalized.
* @param[out] outVertices Output buffer that will store the vertex position data.
* @param[out] outNormals Output buffer that will store the vertex normal data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and color buffer)
* @return Number of vertices generated (3 * (4 ^ numLevels)).
*/
static UINT32 subdivideTriangleOnSphere(const Vector3& center, float radius, UINT32 numLevels,
const Vector3& a, const Vector3& b, const Vector3& c,
UINT8* outVertices, UINT8* outNormals, UINT32 vertexOffset, UINT32 vertexStride);
/**
* Generates vertices that are part of an arc approximation.
*
* @param[in] center Determines world position of the arc.
* @param[in] up Determines rotation of the arc. Arc vertices will be perpendicular to this
* direction.
* @param[in] radius Distance of arc vertices from the center.
* @param[in] startAngle Angle in degrees to start the arc at.
* @param[in] angleAmount Angle in degrees to extend the arc from the start angle.
* @param[in] scale Scale to apply to the x/y axes, allowing you to create elliptical arcs.
* @param[in] numVertices Number of vertices to generate for the arc. Higher number means better arc
* approximation. Must be 2 or higher.
* @param[out] outVertices Output buffer that will store the vertex position data.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffer to start writing at.
* @param[in] vertexStride Size of a single vertex, in bytes. (Same for both position and color buffer)
*/
static void generateArcVertices(const Vector3& center, const Vector3& up, float radius, Degree startAngle,
Degree angleAmount, Vector2 scale, UINT32 numVertices, UINT8* outVertices, UINT32 vertexOffset,
UINT32 vertexStride);
/**
* Calculates per-vertex tangents and bitangents based on the provided vertices, uv coordinates and indices.
*
* @param[in] positions Pointer to an array of vertex positions.
* @param[in] normals Pointer to an array of vertex normals.
* @param[in] uv Pointer to an array of vertex UV coordinates.
* @param[in] indices Set of 32-bit indices containing indexes into vertex array for each triangle.
* @param[in] numVertices Number of vertices in the @p vertices, @p normals and @p uv arrays.
* @param[in] numIndices Number of indices in the @p indices array. Must be a multiple of three.
* @param[in] vertexOffset Offset in number of vertices from the start of the buffers to start reading/writing.
* @param[in] indexOffset Offset in number of indices from the start of the buffer to start reading from.
* @param[in] vertexStride Number of bytes to advance the @p vertices, @p normals and @p uv arrays with each
* vertex. If set to zero them each array is advanced according to its own size.
* @param[out] tangents Pre-allocated buffer that will contain the calculated tangents & bitangents packed
* into 4D vector where first three components are the tangent, and 4th is the sign of
* the bitangent. Must be the same length as the vertex array.
*/
static void generateTangents(UINT8* positions, UINT8* normals, UINT8* uv, UINT32* indices, UINT32 numVertices,
UINT32 numIndices, UINT32 vertexOffset, UINT32 indexOffset, UINT32 vertexStride,
UINT8* tangents);
};
/** @} */
}
|
msharmavikram/gem5_experiments
|
build/ARM/debug/MiscRegs.hh
|
/*
* DO NOT EDIT THIS FILE! Automatically generated by SCons.
*/
#ifndef __DEBUG_MiscRegs_HH__
#define __DEBUG_MiscRegs_HH__
namespace Debug {
class SimpleFlag;
extern SimpleFlag MiscRegs;
}
#endif // __DEBUG_MiscRegs_HH__
|
DaoCalendar/similarity
|
src/test/java/org/xm/tokenizer/TokenizerTest.java
|
package org.xm.tokenizer;
import org.junit.Test;
import java.util.List;
/**
* @author xuming
*/
public class TokenizerTest {
@Test
public void getSegmentResult() throws Exception {
String sentence = "什么是球体和服装?一个伟大的国家,中国,电脑病毒会传染给人吗?";
List<Word> lists = Tokenizer.segment(sentence);
System.out.println(lists);
}
}
|
dtdannen/LUiGi-2
|
core/StarcraftBot/BWSAL_0.9.12/BasicAIModule/Source/AttackClosestScript.cpp
|
#include "AttackClosestScript.h"
#include <Windows.h>
using namespace BWAPI;
using namespace boost;
AttackClosestScript::AttackClosestScript() {
// do nothing
targetPriorityWorkerUnit = false;
}
AttackClosestScript::AttackClosestScript(std::set<BWAPI::Unit*> unitsForCombat, BWAPI::Position pos) {
this->unitsForCombat = unitsForCombat;
this->destination = pos;
targetPriorityWorkerUnit = false;
}
void AttackClosestScript::update() {
bool haveWorkerEnemy = false;
// find nearby enemy units
BWAPI::Player* enemy = BWAPI::Broodwar->self()->isEnemy(BWAPI::Broodwar->getPlayer(0)) ?
BWAPI::Broodwar->getPlayer(0) : BWAPI::Broodwar->getPlayer(1); // get the enemy
// see if the enemy has any visible units
std::set<BWAPI::Unit*> nearbyEnemyUnits;
BOOST_FOREACH (BWAPI::Unit* e, enemy->getUnits()) {
// if the enemy unit is within 500 distance of this plan's units,
// include them in battle simulation
bool alreadyAddedCurrEnemy = false;
BOOST_FOREACH (BWAPI::Unit* a, this->unitsForCombat) {
if (e->getPosition().getApproxDistance(a->getPosition()) < 500 // nearby, or
|| BWTA::getRegion(a->getPosition()) == BWTA::getRegion(e->getPosition())) { // in same region
if (!alreadyAddedCurrEnemy) { // prevent duplicate insertions
nearbyEnemyUnits.insert(e);
alreadyAddedCurrEnemy = true;
if (e->getType().isWorker()) {
haveWorkerEnemy = true;
}
}
}
}
}
std::set<BWAPI::Unit*> nearbyWorkerEnemyUnits;
if (!nearbyEnemyUnits.empty()) {
// if our priority is to kill worker units, then if any worker units exist
// ignore all other units
if (this->targetPriorityWorkerUnit && haveWorkerEnemy) {
// remove any workers from the set of enemies
BOOST_FOREACH (BWAPI::Unit* currEnemyUnit, nearbyEnemyUnits) {
if (currEnemyUnit->getType().isWorker()) {
nearbyWorkerEnemyUnits.insert(currEnemyUnit);
}
}
}
//nearbyEnemyUnits = nearbyWorkerEnemyUnits; // cant do this because nearby enemy units is used elsewhere
// 1. Loop through all of my units
BOOST_FOREACH (BWAPI::Unit* myUnit, this->unitsForCombat) {
// if it is a healing unit, nevermind
if (myUnit->getType() != BWAPI::UnitTypes::Terran_Medic) {
// check to see if my unit has a target
std::map<int,int>::iterator currentTargetIT = attackAssignments.find(myUnit->getID());
std::pair<int,int> currentTarget;
BWAPI::Unit* newTarget = NULL;
if (currentTargetIT != attackAssignments.end()) {
// my unit DOES have a target
currentTarget = *currentTargetIT;
BWAPI::Unit* currEnemyUnit = Broodwar->getUnit(currentTarget.second);
// if my unit is not alive, remove it from the assignments list
if (myUnit->getHitPoints() <= 0) {
attackAssignments.erase(myUnit->getID());
}else if (currEnemyUnit->getHitPoints() <= 0 || !currEnemyUnit->isVisible() || !currEnemyUnit->exists()){
// my unit is alive but enemy unit is dead, or invisible, or does not exist
// so give my unit a new target
if (this->targetPriorityWorkerUnit && haveWorkerEnemy) {
newTarget = findClosestEnemyUnitNOK(myUnit, nearbyWorkerEnemyUnits, attackAssignments);
}else{
newTarget = findClosestEnemyUnitNOK(myUnit, nearbyEnemyUnits, attackAssignments);
}
}else {
// my unit has a target so do nothing
}
}else{
// My unit does not have a target, find him the nearest enemy
if (this->targetPriorityWorkerUnit && haveWorkerEnemy) {
newTarget = findClosestEnemyUnitNOK(myUnit, nearbyWorkerEnemyUnits, attackAssignments);
}else{
newTarget = findClosestEnemyUnitNOK(myUnit, nearbyEnemyUnits, attackAssignments);
}
}
if (newTarget != NULL) {
// order the attack
myUnit->attack(newTarget);
// update assignment
attackAssignments[myUnit->getID()] = newTarget->getID();
// DEBUG Info
//Broodwar->sendText("Give my unit %d new attack", myUnit->getID());
}
}
}
// debug information: draw lines showing who is attacking who
std::map<int,int>::iterator mapping = attackAssignments.begin();
while (mapping != attackAssignments.end()) {
if (Broodwar->getUnit(mapping->first)->getHitPoints() > 0) {
int x1 = Broodwar->getUnit(mapping->first)->getPosition().x();
int y1 = Broodwar->getUnit(mapping->first)->getPosition().y();
int x2 = Broodwar->getUnit(mapping->second)->getPosition().x();
int y2 = Broodwar->getUnit(mapping->second)->getPosition().y();
Broodwar->drawLine(BWAPI::CoordinateType::Map,x1,y1,x2,y2,BWAPI::Colors::Red);
}
mapping++;
}
}else{
// order each unit to attack move to destination
BOOST_FOREACH (BWAPI::Unit* myUnit, this->unitsForCombat) {
if (!myUnit->isMoving() || !myUnit->isAttacking()) {
//MessageBoxA(NULL, ("Just ordered unit to attack to attack "+SSTR(this->destination.x()) + "," + SSTR(this->destination.y())).c_str(),"TEST MESSAGE",0);
if (this->targetPriorityWorkerUnit) {
myUnit->move(this->destination); // because we do not want to attack anything until we get to our destination because we want to make sure we kill workers first
}else{
myUnit->attack(this->destination);
}
}
}
}
this->nearbyEnemyUnits = nearbyEnemyUnits;
this->nearbyWorkerEnemyUnits = nearbyWorkerEnemyUnits;
}
void AttackClosestScript::killWorkerUnits() {
this->targetPriorityWorkerUnit = true;
}
// if all our units are dead OR
// if we are in center of region and there are no more enemy units visible
bool AttackClosestScript::finished() {
bool anyUnitAlive = false;
int numb_units_alive = 0;
BOOST_FOREACH(BWAPI::Unit* myUnit, this->unitsForCombat) {
if (myUnit->getHitPoints() > 0) {
anyUnitAlive = true;
numb_units_alive++;
}else{
//Broodwar->sendText(("Unit "+SSTR(myUnit->getID())+" has died").c_str());
}
}
if (!anyUnitAlive) return true; // DONE - we have all died
bool areWeStillMoving = false;
// first check to see if we are still moving to center
BOOST_FOREACH(BWAPI::Unit* myUnit, this->unitsForCombat) {
if (myUnit->getHitPoints() > 0 && myUnit->getPosition().getApproxDistance(this->destination) >= 125) {
areWeStillMoving = true;
}
}
if (areWeStillMoving) return false; // NOT DONE - still moving
// we have stopped moving, and are still alive, are there still enemies?
bool anyVisibleEnemyUnit = false;
if (this->targetPriorityWorkerUnit) {
BOOST_FOREACH(BWAPI::Unit* enemyUnit, this->nearbyWorkerEnemyUnits) {
if (enemyUnit->getHitPoints() > 0) {
anyVisibleEnemyUnit = true;
}
}
}else{
BOOST_FOREACH(BWAPI::Unit* enemyUnit, this->nearbyEnemyUnits) {
if (enemyUnit->getHitPoints() > 0) {
anyVisibleEnemyUnit = true;
}
}
}
return !anyVisibleEnemyUnit; // If any visible unit, keep going
}
void AttackClosestScript::finishedProduce(std::map<BWAPI::UnitType , int> * How_Many_Died , int * Total_Died, int * Enemy_Scale , int * Our_Scale , int * StillMoving){
bool anyUnitAlive = false;
int numb_units_alive = 0;
int numb_units_died = 0;
int count=0 ;
typedef std::pair<const BWAPI::UnitType, int> uti_t;
std::map<BWAPI::UnitType , int > temp ;
BOOST_FOREACH(BWAPI::Unit* myUnit, this->unitsForCombat) {
std::pair<BWAPI::UnitType , int > a = std::pair<BWAPI::UnitType , int >(myUnit->getType() , 0);
(temp).insert(a);
(*How_Many_Died).insert(a);
}
BOOST_FOREACH(BWAPI::Unit* myUnit, this->unitsForCombat) {
if (myUnit->getHitPoints() > 0) {
anyUnitAlive = true;
numb_units_alive++;
}else{
numb_units_died++;
BOOST_FOREACH(uti_t uti, (temp)) {
if (std::strcmp(myUnit->getType().getName().c_str(), uti.first.getName().c_str()) == 0) {
// if they match, increment count
uti.second ++;
}
//Broodwar->sendText(("Unit "+SSTR(myUnit->getID())+" has died").c_str());
}
}
}
BOOST_FOREACH(uti_t uti1, (temp)) {
BOOST_FOREACH(uti_t uti2, (*How_Many_Died)) {
if (std::strcmp(uti1.first.getName().c_str(), uti2.first.getName().c_str()) == 0) {
// if they match, if temp > Original , do increment for origial
if(uti1.second > uti2.second){
uti2.second= uti1.second;
}
}
}
}
if(*Total_Died < numb_units_died)
*Total_Died = numb_units_died ;
*Our_Scale = numb_units_alive ;
bool areWeStillMoving = false;
// first check to see if we are still moving to center
BOOST_FOREACH(BWAPI::Unit* myUnit, this->unitsForCombat) {
if (myUnit->getHitPoints() > 0 && myUnit->getPosition().getApproxDistance(this->destination) >= 125) {
areWeStillMoving = true;
}
}
if(areWeStillMoving){
*StillMoving = 1;
}
else{
*StillMoving = 0;
}
// we have stopped moving, and are still alive, are there still enemies?
bool anyVisibleEnemyUnit = false;
int numb_enemy_units_alive = 0;
if (this->targetPriorityWorkerUnit) {
BOOST_FOREACH(BWAPI::Unit* enemyUnit, this->nearbyWorkerEnemyUnits) {
if (enemyUnit->getHitPoints() > 0) {
anyVisibleEnemyUnit = true;
numb_enemy_units_alive ++;
}
}
}else{
BOOST_FOREACH(BWAPI::Unit* enemyUnit, this->nearbyEnemyUnits) {
if (enemyUnit->getHitPoints() > 0) {
anyVisibleEnemyUnit = true;
numb_enemy_units_alive++;
}
}
}
* Enemy_Scale = numb_enemy_units_alive;
}
// returns the nearest enemy unit my unit should now attack
BWAPI::Unit* AttackClosestScript::findClosestEnemyUnitNOK(BWAPI::Unit* myUnit, std::set<BWAPI::Unit*> enemyUnits, std::map<int,int> currentAssignments) {
int maxNumAttackers = 3;
// duplicate enemy units set
std::set<BWAPI::Unit*> enemyUnitsCopy(enemyUnits);
// remove all enemies that have 3 or more attackers
bool removeUnitFromCurrentEnemies = false;
BOOST_FOREACH(BWAPI::Unit* eUC, enemyUnits) {
int count = 0;
std::map<int,int>::iterator currAssIT = currentAssignments.begin();
while (currAssIT != currentAssignments.end()) {
if (currAssIT->second == eUC->getID()) {
count++;
if (count >= maxNumAttackers) {
//removeUnitFromCurrentEnemies = true;
if (!enemyUnitsCopy.empty() && enemyUnitsCopy.find(eUC) != enemyUnitsCopy.end()) {
enemyUnitsCopy.erase(eUC);
}
break;
}
}
currAssIT++;
}
//if (removeUnitFromCurrentEnemies) {
//}
}
// now find the closest enemy
return findClosestEnemyUnit(myUnit, enemyUnitsCopy);
}
BWAPI::Unit* AttackClosestScript::findClosestEnemyUnit(BWAPI::Unit* myUnit, std::set<BWAPI::Unit*> enemyUnits) {
if (enemyUnits.empty()) {
return NULL;
}
// start off with the first enemy unit in the set as the closest one
BWAPI::Unit* currEnemyUnit = *(enemyUnits.begin());
int currDist = currEnemyUnit->getPosition().getApproxDistance(myUnit->getPosition());
// are there non-building enemies?
bool areThereNonBuildingEnemies = false;
BOOST_FOREACH (BWAPI::Unit* u, enemyUnits) {
if (!u->getType().isBuilding()) {
areThereNonBuildingEnemies = true;
}
}
// find closest enemy
BOOST_FOREACH (BWAPI::Unit* e, enemyUnits) {
if (e->getPosition().getApproxDistance(myUnit->getPosition()) < currDist && e->getHitPoints() > 0) {
// if there are units that aren't buildings, attack those first
if (areThereNonBuildingEnemies) {
// check this unit is not a building, only then assign
if (!e->getType().isBuilding()) {
currEnemyUnit = e;
currDist = e->getPosition().getApproxDistance(myUnit->getPosition());
}
}else{
// just do the regular thing, consider all units
currEnemyUnit = e;
currDist = e->getPosition().getApproxDistance(myUnit->getPosition());
}
}
}
return currEnemyUnit;
}
void AttackClosestScript::setUnits( std::set<BWAPI::Unit*> availableUnits )
{
this->unitsForCombat = availableUnits;
}
|
ranarashadmahmood/OMNETPY
|
pysamples/pytictoc/txc10.py
|
"""
Let's make it more interesting by using several (n) `tic' modules,
and connecting every module to every other. For now, let's keep it
simple what they do: module 0 generates a message, and the others
keep tossing it around in random directions until it arrives at
module 2.
"""
from pyopp import cSimpleModule, cMessage, EV
class PyTxc10(cSimpleModule):
def initialize(self):
if self.getIndex() == 0:
# Boot the process scheduling the initial message as a self-message.
self.scheduleAt(0.0, cMessage('tic-0'))
def handleMessage(self, msg):
if self.getIndex() == 3:
# Message arrived.
EV << "Message " << msg.getName() << " arrived.\n";
else:
# We need to forward the message.
self.forwardMessage(msg)
def forwardMessage(self, msg):
# In this example, we just pick a random gate to send it on.
# We draw a random number between 0 and the size of gate `out[]'.
n = self.gateSize("out")
k = self.intuniform(0, n-1);
EV << "Forwarding message " << msg.getName() << " on port out[" << k << "]\n"
self.send(msg, "out", k)
|
FateRevoked/mage
|
Mage.Sets/src/mage/cards/h/HuntedTroll.java
|
package mage.cards.h;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ColoredManaCost;
import mage.abilities.effects.common.CreateTokenTargetEffect;
import mage.abilities.effects.common.RegenerateSourceEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.ColoredManaSymbol;
import mage.constants.Zone;
import mage.game.permanent.token.FaerieToken;
import mage.target.Target;
import mage.target.common.TargetOpponent;
/**
*
* @author Loki
*/
public final class HuntedTroll extends CardImpl {
public HuntedTroll(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{G}{G}");
this.subtype.add(SubType.TROLL);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(8);
this.toughness = new MageInt(4);
// When Hunted Troll enters the battlefield, create four 1/1 blue Faerie creature tokens with flying under target opponent's control.
Ability ability = new EntersBattlefieldTriggeredAbility(new CreateTokenTargetEffect(new FaerieToken(), 4), false);
Target target = new TargetOpponent();
ability.addTarget(target);
this.addAbility(ability);
// {G}: Regenerate Hunted Troll.
this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new RegenerateSourceEffect(), new ColoredManaCost(ColoredManaSymbol.G)));
}
public HuntedTroll(final HuntedTroll card) {
super(card);
}
@Override
public HuntedTroll copy() {
return new HuntedTroll(this);
}
}
|
YolandaMDavis/nifi
|
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/endpoints/ProvenanceEventEndpointMerger.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.nifi.cluster.coordination.http.endpoints;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.nifi.cluster.manager.NodeResponse;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
import org.apache.nifi.web.api.dto.provenance.ProvenanceEventDTO;
import org.apache.nifi.web.api.entity.ProvenanceEventEntity;
public class ProvenanceEventEndpointMerger extends AbstractSingleDTOEndpoint<ProvenanceEventEntity, ProvenanceEventDTO> {
public static final Pattern PROVENANCE_EVENT_URI = Pattern.compile("/nifi-api/provenance/events/[0-9]+");
@Override
public boolean canHandle(URI uri, String method) {
return "GET".equalsIgnoreCase(method) && PROVENANCE_EVENT_URI.matcher(uri.getPath()).matches();
}
@Override
protected Class<ProvenanceEventEntity> getEntityClass() {
return ProvenanceEventEntity.class;
}
@Override
protected ProvenanceEventDTO getDto(ProvenanceEventEntity entity) {
return entity.getProvenanceEvent();
}
@Override
protected void mergeResponses(ProvenanceEventDTO clientDto, Map<NodeIdentifier, ProvenanceEventDTO> dtoMap, Set<NodeResponse> successfulResponses, Set<NodeResponse> problematicResponses) {
// The request for a Provenance Event is replicated to a single Node. We simply update its cluster node info.
// However, we only do this if the cluster node info isn't set, because if this is replicated across the cluster,
// the cluster coordinator will have already set it, and we will be receiving the response from the cluster
// coordinator. We do not want to overwrite this value on all DTO's with the cluster coordinator's information.
if (clientDto.getClusterNodeId() == null || clientDto.getClusterNodeAddress() == null) {
final NodeIdentifier nodeId = successfulResponses.iterator().next().getNodeId();
clientDto.setClusterNodeId(nodeId.getId());
clientDto.setClusterNodeAddress(nodeId.getApiAddress() + ":" + nodeId.getApiPort());
}
}
}
|
ojmakhura/spring-richclient
|
spring-richclient-samples/spring-richclient-samples-showcase/src/main/java/org/springframework/richclient/samples/showcase/exceptionhandling/JXErrorDialogExceptionHandlerCommand.java
|
package org.springframework.richclient.samples.showcase.exceptionhandling;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.exceptionhandling.JXErrorDialogExceptionHandler;
/**
* Command throwing the specific {@link JXErrorDialogException} that should be
* caught by the {@link JXErrorDialogExceptionHandler}.
*
* @author <NAME>
*
*/
public class JXErrorDialogExceptionHandlerCommand extends ActionCommand {
@Override
protected void doExecuteCommand() {
throw new JXErrorDialogException();
}
}
|
IsraelyFlightSimulator/Negev-Storm
|
SOURCES/sim/rwr/alr56.cpp
|
#include "stdhdr.h"
#include "object.h"
#include "simmover.h"
#include "ClassTbl.h"
#include "simdrive.h"
#include "fsound.h"
#include "mfd.h"
#include "msginc\TrackMsg.h"
#include "Graphics\Include\Display.h"
#include "airunit.h"
#include "aircrft.h"
#include "alr56.h"
#include "radarData.h"
ALR56Class::ALR56Class (int idx, SimMoverClass* self) : PlayerRwrClass (idx, self)
{
priorityMode = FALSE;
}
ALR56Class::~ALR56Class (void)
{
}
float ALR56Class::GetLethality (FalconEntity* theObject)
{
int alt = (lowAltPriority) ? LOW_ALT_LETHALITY : HIGH_ALT_LETHALITY;
if (F4IsBadReadPtr(theObject, sizeof(FalconEntity))) // JB 010404 CTD
return 0;
float lethality = RadarDataTable[theObject->GetRadarType()].Lethality[alt];
// Scale lethality for normalized range
float dx = theObject->XPos()-platform->XPos();
float dy = theObject->YPos()-platform->YPos();
float nomRange = RadarDataTable[theObject->GetRadarType()].NominalRange;
float range = (float)sqrt(dx*dx + dy*dy) / (2.0f * nomRange);
// lethality = max (lethality, 0.1F); - Place into code if you want search radars to be shown from emiterList
if (range < 0.8f) {
lethality *= 1 - range;
} else {
lethality *= 0.2f;
}
return lethality;
}
void ALR56Class::PushButton(int whichButton, int whichMFD)
{
switch (whichButton)
{
case 0:
MfdDisplay[whichMFD]->SetNewMode(MFDClass::MfdMenu);
break;
case 14:
MFDSwapDisplays();
break;
}
}
|
intel/qpl
|
tools/tests/fuzzing/high-level-api/deflate_fuzz_test.hpp
|
/*******************************************************************************
* Copyright (C) 2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include <iostream>
#include <string>
#include <vector>
#include "qpl/cpp_api/operations/compression/deflate_operation.hpp"
#include "qpl/cpp_api/operations/compression/inflate_operation.hpp"
struct deflate_properties {
size_t property_size;
size_t property_gzip_mode;
};
static inline int deflate_fuzz(const uint8_t * Data, size_t Size,
qpl::compression_modes compression_mode,
qpl::compression_levels compression_level)
{
const uint8_t* source_data_ptr = Data;
size_t source_size = Size;
size_t destination_size = Size;
bool gzip_mode = false;
if (Size == 0) {
return 0;
}
if (Size > sizeof(deflate_properties)) {
deflate_properties* properties = (deflate_properties*)Data;
source_data_ptr += sizeof(deflate_properties);
source_size -= sizeof(deflate_properties);
destination_size = properties->property_size;
destination_size %= (source_size + source_size);
if (0 == destination_size) {
destination_size = source_size + source_size;
}
if (properties->property_gzip_mode & 1) {
gzip_mode = true;
}
}
std::vector<uint8_t> source(source_data_ptr, source_data_ptr + source_size);
std::vector<uint8_t> destination(destination_size, 0xaa);
try {
auto deflate_operation = (qpl::dynamic_mode == compression_mode) ?
qpl::deflate_operation::builder()
.compression_level(compression_level)
.compression_mode<qpl::compression_modes::dynamic_mode>()
.gzip_mode(gzip_mode)
.build() :
qpl::deflate_operation::builder()
.compression_level(compression_level)
.compression_mode<qpl::compression_modes::fixed_mode>()
.gzip_mode(gzip_mode)
.build();
const auto compressed_result = qpl::execute<qpl::software>(deflate_operation,
std::begin(source),
std::end(source),
std::begin(destination),
std::end(destination));
compressed_result.if_absent([](uint32_t status) -> void {
// Valid behavior as the operation result is unpredictable
});
}
catch (qpl::operation_process_exception& e) {
// Handling Exceptions on misconfigured operation
}
return 0;
}
|
heisedebaise/photon
|
photon-ctrl-http/src/main/java/org/lpw/photon/ctrl/http/ServiceHelperImpl.java
|
<reponame>heisedebaise/photon
package org.lpw.photon.ctrl.http;
import org.lpw.photon.bean.BeanFactory;
import org.lpw.photon.ctrl.Dispatcher;
import org.lpw.photon.ctrl.Handler;
import org.lpw.photon.ctrl.context.HeaderAware;
import org.lpw.photon.ctrl.context.RequestAware;
import org.lpw.photon.ctrl.context.ResponseAware;
import org.lpw.photon.ctrl.context.SessionAware;
import org.lpw.photon.ctrl.http.context.CookieAware;
import org.lpw.photon.ctrl.http.context.HeaderAdapterImpl;
import org.lpw.photon.ctrl.http.context.RequestAdapterImpl;
import org.lpw.photon.ctrl.http.context.ResponseAdapterImpl;
import org.lpw.photon.ctrl.http.context.SessionAdapterImpl;
import org.lpw.photon.ctrl.http.ws.WsHelper;
import org.lpw.photon.ctrl.status.Status;
import org.lpw.photon.ctrl.upload.UploadService;
import org.lpw.photon.util.Codec;
import org.lpw.photon.util.Context;
import org.lpw.photon.util.Converter;
import org.lpw.photon.util.Logger;
import org.lpw.photon.util.Numeric;
import org.lpw.photon.util.TimeHash;
import org.lpw.photon.util.Validator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
@Controller("photon.ctrl.http.service.helper")
public class ServiceHelperImpl implements ServiceHelper {
private static final String ROOT = "/";
@Inject
private Validator validator;
@Inject
private Converter converter;
@Inject
private Context context;
@Inject
private Numeric numeric;
@Inject
private Codec codec;
@Inject
private TimeHash timeHash;
@Inject
private Logger logger;
@Inject
private HeaderAware headerAware;
@Inject
private SessionAware sessionAware;
@Inject
private RequestAware requestAware;
@Inject
private ResponseAware responseAware;
@Inject
private Handler handler;
@Inject
private Dispatcher dispatcher;
@Inject
private Status status;
@Inject
private Cors cors;
@Inject
private Redirect redirect;
@Inject
private Optional<IgnoreTimeHash> ignoreTimeHash;
@Inject
private CookieAware cookieAware;
@Value("${photon.ctrl.http.ignore.root:false}")
private boolean ignoreRoot;
@Value("${photon.ctrl.http.ignore.prefixes:/upload/}")
private String ignorePrefixes;
@Value("${photon.ctrl.http.ignore.suffixes:.ico,.js,.css,.html,.jpg,.jpeg,.gif,.png,.svg,.eot,.woff,.ttf,.json,.txt}")
private String ignoreSuffixes;
@Value("${photon.ctrl.http.not-modified.names:/upload/image/}")
private String notModifiedNames;
@Value("${photon.ctrl.http.virtual-context:}")
private String virtualContext;
@Value("${photon.ctrl.http.url:}")
private String url;
private int contextPath;
private String servletContextPath;
private int virtualContextLength;
private String[] prefixes;
private String[] suffixes;
private String[] names;
private Set<String> ignoreUris;
@Override
public void setPath(String real, String context) {
contextPath = validator.isEmpty(context) || context.equals(ROOT) ? 0 : context.length();
servletContextPath = contextPath > 0 ? context : "";
virtualContextLength = virtualContext.length();
if (logger.isInfoEnable())
logger.info("部署项目路径[{}],虚拟路径[{}]。", context, virtualContext);
prefixes = converter.toArray(ignorePrefixes, ",");
suffixes = converter.toArray(ignoreSuffixes, ",");
names = converter.toArray(notModifiedNames, ",");
ignoreUris = new HashSet<>();
BeanFactory.getBeans(IgnoreUri.class).forEach(ignoreUri -> ignoreUris.addAll(Arrays.asList(ignoreUri.getIgnoreUris())));
}
@Override
public boolean service(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (cors.is(request, response)) {
cors.set(request, response);
return true;
}
String uri = getUri(request);
String lowerCaseUri = uri.toLowerCase();
if (lowerCaseUri.startsWith(UploadService.ROOT)) {
if (lowerCaseUri.startsWith(UploadService.ROOT + "image/"))
return false;
StringBuilder attachment = new StringBuilder("attachment; filename*=").append(context.getCharset(null)).append("''");
String filename = request.getParameter("filename");
if (validator.isEmpty(filename))
attachment.append(uri.substring(uri.lastIndexOf('/') + 1));
else {
attachment.append(codec.encodeUrl(filename, null));
int indexOf;
if (filename.indexOf('.') == -1 && (indexOf = uri.lastIndexOf('.')) > -1)
attachment.append(uri.substring(indexOf));
}
response.setHeader("Content-Disposition", attachment.toString());
if (logger.isDebugEnable())
logger.debug("请求[{}]非图片上传资源。", uri);
return false;
}
if (ignoreUris.contains(uri) || resource(request, response, uri)) {
if (logger.isDebugEnable())
logger.debug("忽略请求[{}]。", uri);
return false;
}
if (redirect.redirect(request, uri, response))
return true;
context.clearThreadLocal();
if (lowerCaseUri.equals(WsHelper.URI)) {
context.putThreadLocal(WsHelper.IP, request.getRemoteAddr());
context.putThreadLocal(WsHelper.PORT, request.getServerPort());
return false;
}
String sessionId = getSessionId(request);
try {
return handler.call(sessionId, () -> service(request, response, uri, sessionId));
} catch (Exception e) {
logger.warn(e, "处理请求[{}]时发生异常!", uri);
return false;
}
}
private String getUri(HttpServletRequest request) {
String uri = request.getRequestURI();
if (contextPath > 0)
uri = uri.substring(contextPath);
if (virtualContextLength > 0 && uri.startsWith(virtualContext))
uri = uri.substring(virtualContextLength);
return uri;
}
private boolean service(HttpServletRequest request, HttpServletResponse response, String uri, String sessionId) throws IOException {
cors.set(request, response);
OutputStream outputStream = setContext(request, response, uri, sessionId);
response.setHeader("Cache-Control", "no-cache");
if (timeHash.isEnable() && !timeHash.valid(request.getIntHeader("time-hash")) && !status.isStatus(uri)
&& (ignoreTimeHash.isEmpty() || !ignoreTimeHash.get().ignore())) {
if (logger.isDebugEnable())
logger.debug("请求[{}]TimeHash[{}]验证不通过。", uri, request.getIntHeader("time-hash"));
return false;
}
dispatcher.execute();
outputStream.flush();
outputStream.close();
return true;
}
private boolean resource(HttpServletRequest request, HttpServletResponse response, String uri) {
if (!ignore(uri))
return false;
File file = new File(context.getAbsolutePath(uri));
if (!file.exists()) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return true;
}
if (file.isDirectory())
return true;
String ifNoneMatch = request.getHeader("If-None-Match");
String lastModified = numeric.toString(file.lastModified());
if (notModified(ifNoneMatch, lastModified, uri))
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
else
response.setHeader("ETag", lastModified);
return true;
}
private boolean ignore(String uri) {
if (ignoreRoot && uri.equals(ROOT))
return true;
for (String prefix : prefixes)
if (uri.startsWith(prefix))
return true;
int indexOf = uri.lastIndexOf('/');
if (indexOf == -1)
return false;
String name = uri.substring(indexOf + 1);
for (String n : suffixes)
if (name.equals(n))
return true;
indexOf = name.lastIndexOf('.');
if (indexOf == -1)
return false;
String suffix = name.substring(indexOf);
for (String s : suffixes)
if (suffix.equals(s))
return true;
return false;
}
private boolean notModified(String ifNoneMatch, String lastModified, String uri) {
if (validator.isEmpty(ifNoneMatch))
return false;
if (ifNoneMatch.equals(lastModified))
return true;
for (String name : names)
if (uri.contains(name))
return true;
return false;
}
@Override
public OutputStream setContext(HttpServletRequest request, HttpServletResponse response, String uri) throws IOException {
return setContext(request, response, uri, getSessionId(request));
}
private OutputStream setContext(HttpServletRequest request, HttpServletResponse response, String uri, String sessionId) throws IOException {
context.setLocale(request.getLocale());
headerAware.set(new HeaderAdapterImpl(request));
sessionAware.set(new SessionAdapterImpl(sessionId));
requestAware.set(new RequestAdapterImpl(request, uri));
cookieAware.set(request, response);
response.setCharacterEncoding(context.getCharset(null));
OutputStream outputStream = response.getOutputStream();
responseAware.set(new ResponseAdapterImpl(servletContextPath, response, outputStream));
return outputStream;
}
private String getSessionId(HttpServletRequest request) {
String sessionId = request.getHeader(SESSION_ID);
if (!validator.isEmpty(sessionId))
return useTephraSessionId(request, sessionId);
sessionId = request.getParameter(SESSION_ID);
if (!validator.isEmpty(sessionId))
return useTephraSessionId(request, sessionId);
sessionId = converter.toString(request.getSession().getAttribute(SESSION_ID));
if (!validator.isEmpty(sessionId))
return sessionId;
return request.getSession().getId();
}
private String useTephraSessionId(HttpServletRequest request, String sessionId) {
request.getSession().setAttribute(SESSION_ID, sessionId);
return sessionId;
}
@Override
public String getUrl() {
return url;
}
}
|
phalodi/spark-semantic
|
src/main/java/com.ibm.research.quetzal.core/src/com/ibm/research/rdf/store/sparql11/model/UnaryExpression.java
|
/******************************************************************************
* Copyright (c) 2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package com.ibm.research.rdf.store.sparql11.model;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.antlr.stringtemplate.StringTemplate;
import com.ibm.research.rdf.store.Store;
import com.ibm.research.rdf.store.runtime.service.types.TypeMap;
import com.ibm.research.rdf.store.sparql11.sqlwriter.FilterContext;
/**
* unary expression
*/
public class UnaryExpression extends Expression {
private Expression expression;
private EUnaryOp operator;
private static final String UNARY = "unary_expression";
private static final String UNARY_NOT = "unary_not";
private static final String UNARY_MINUS = "unary_minus";
private static final String NOT_EBV = "NOT_RDF_EBV";
/**
* @param type
*/
public UnaryExpression(EUnaryOp op, Expression e) {
super(EExpressionType.UNARY);
operator = op;
expression = e;
}
public Expression getExpression() {
return expression;
}
public EUnaryOp getOperator() {
return operator;
}
@Override
public Short getReturnType() {
return expression.getReturnType();
}
public TypeMap.TypeCategory getTypeRestriction(Variable v) {
if (!this.gatherVariables().contains(v))
return TypeMap.TypeCategory.NONE;
else
return expression.getTypeRestriction(v);
}
public short getTypeEquality(Variable v) {
if (!this.gatherVariables().contains(v))
return TypeMap.NONE_ID;
else
return expression.getTypeEquality(v);
}
@Override
public String toString() {
return operator.toString() + " " + expression.toString();
}
@Override
public String getStringWithVarName() {
return operator.toString() + " " + expression.getStringWithVarName();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((expression == null) ? 0 : expression.hashCode());
result = prime * result
+ ((operator == null) ? 0 : operator.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UnaryExpression other = (UnaryExpression) obj;
if (expression == null) {
if (other.expression != null)
return false;
} else if (!expression.equals(other.expression))
return false;
if (operator != other.operator)
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.research.rdf.store.sparql11.model.Expression#renamePrefixes(java.lang.
* String, java.util.Map, java.util.Map)
*/
@Override
public void renamePrefixes(String base, Map<String, String> declared,
Map<String, String> internal) {
expression.renamePrefixes(base, declared, internal);
}
@Override
public void reverseIRIs() {
expression.reverseIRIs();
}
/*
* (non-Javadoc)
*
* @see com.ibm.research.rdf.store.sparql11.model.Expression#gatherBlankNodes()
*/
@Override
public Set<BlankNodeVariable> gatherBlankNodes() {
return expression.gatherBlankNodes();
}
/*
* (non-Javadoc)
*
* @see com.ibm.research.rdf.store.sparql11.model.Expression#gatherVariables()
*/
@Override
public Set<Variable> gatherVariables() {
return expression.gatherVariables();
}
@Override
public Set<Variable> getVariables() {
return Collections.emptySet();
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.research.rdf.store.sparql11.model.Expression#traverse(com.ibm.research.rdf.store
* .sparql11.model.IExpressionTraversalListener)
*/
@Override
public void traverse(IExpressionTraversalListener l) {
l.startExpression(this);
expression.traverse(l);
l.endExpression(this);
}
public boolean containsEBV() {
if (expression instanceof VariableExpression
&& ((VariableExpression) expression).getExpression() == null) {
return true;
} else
return false;
}
public boolean containsBound() {
return expression.containsBound();
}
public boolean containsNotBound() {
if (operator == EUnaryOp.NOT)
return expression.containsBound();
else
return expression.containsNotBound();
}
public boolean containsCast(Variable v) {
if (expression.containsCast(v))
return true;
return false;
}
@Override
public String visit(FilterContext context, Store store) {
String s = getExpression().visit(context, store);
if (s.equals(""))
return s;
StringTemplate t = null;
if (getOperator() == EUnaryOp.MINUS) {
t = store.getInstanceOf(UNARY_MINUS);
} else if ((getExpression() instanceof VariableExpression && ((VariableExpression) getExpression())
.getExpression() == null)) {
t = store.getInstanceOf(EBV);
String fType = null;
String fTerm = null;
for (Variable v : getExpression().gatherVariables()) {
fType = context.getVarMap().get(v.getName()).snd;
fTerm = context.getVarMap().get(v.getName()).fst;
}
if (fType == null)
fType = TypeMap.IRI_ID + "";
t.setAttribute("fterm", fTerm);
t.setAttribute("ftype", fType);
t.setAttribute("nrstart", TypeMap.DATATYPE_NUMERICS_IDS_START);
t.setAttribute("nrend", TypeMap.DATATYPE_NUMERICS_IDS_END);
t.setAttribute("tstring", TypeMap.STRING_ID);
t.setAttribute("pstring", TypeMap.SIMPLE_LITERAL_ID);
t.setAttribute("tboolean", TypeMap.BOOLEAN_ID);
s = t.toString();
if (getOperator() == EUnaryOp.NOT) {
t = store.getInstanceOf(NOT_EBV);
t.setAttribute("ebv", s);
t.setAttribute("type", fType);
t.setAttribute("unknownTypesStart", TypeMap.USER_ID_START);
t.setAttribute("unknownTypesEnd", TypeMap.NONE_ID);
return t.toString();
}
}
if (getOperator() == EUnaryOp.NOT) {
t = store.getInstanceOf(UNARY_NOT);
}
t.setAttribute("expression", s);
return t.toString();
}
}
|
alpmestan/haskell-igraph
|
igraph/src/igraph_strvector.c
|
/* -*- mode: C -*- */
/*
IGraph library.
Copyright (C) 2003-2012 <NAME> <<EMAIL>>
334 Harvard street, Cambridge, MA 02139 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include "igraph_types.h"
#include "igraph_strvector.h"
#include "igraph_memory.h"
#include "igraph_error.h"
#include "config.h"
#include <assert.h>
#include <string.h> /* memcpy & co. */
#include <stdlib.h>
/**
* \section igraph_strvector_t
* <para>The <type>igraph_strvector_t</type> type is a vector of strings.
* The current implementation is very simple and not too efficient. It
* works fine for not too many strings, e.g. the list of attribute
* names is returned in a string vector by \ref
* igraph_cattribute_list(). Do not expect great performance from this
* type.</para>
*
* <para>
* \example examples/simple/igraph_strvector.c
* </para>
*/
/**
* \ingroup strvector
* \function igraph_strvector_init
* \brief Initialize
*
* Reserves memory for the string vector, a string vector must be
* first initialized before calling other functions on it.
* All elements of the string vector are set to the empty string.
* \param sv Pointer to an initialized string vector.
* \param len The (initial) length of the string vector.
* \return Error code.
*
* Time complexity: O(\p len).
*/
int igraph_strvector_init(igraph_strvector_t *sv, long int len) {
long int i;
sv->data = igraph_Calloc(len, char*);
if (sv->data == 0) {
IGRAPH_ERROR("strvector init failed", IGRAPH_ENOMEM);
}
for (i = 0; i < len; i++) {
sv->data[i] = igraph_Calloc(1, char);
if (sv->data[i] == 0) {
igraph_strvector_destroy(sv);
IGRAPH_ERROR("strvector init failed", IGRAPH_ENOMEM);
}
sv->data[i][0] = '\0';
}
sv->len = len;
return 0;
}
/**
* \ingroup strvector
* \function igraph_strvector_destroy
* \brief Free allocated memory
*
* Destroy a string vector. It may be reinitialized with \ref
* igraph_strvector_init() later.
* \param sv The string vector.
*
* Time complexity: O(l), the total length of the strings, maybe less
* depending on the memory manager.
*/
void igraph_strvector_destroy(igraph_strvector_t *sv) {
long int i;
assert(sv != 0);
if (sv->data != 0) {
for (i = 0; i < sv->len; i++) {
if (sv->data[i] != 0) {
igraph_Free(sv->data[i]);
}
}
igraph_Free(sv->data);
}
}
/**
* \ingroup strvector
* \function igraph_strvector_get
* \brief Indexing
*
* Query an element of a string vector. See also the \ref STR macro
* for an easier way.
* \param sv The input string vector.
* \param idx The index of the element to query.
* \param Pointer to a <type>char*</type>, the address of the string
* is stored here.
*
* Time complexity: O(1).
*/
void igraph_strvector_get(const igraph_strvector_t *sv, long int idx,
char **value) {
assert(sv != 0);
assert(sv->data != 0);
assert(sv->data[idx] != 0);
*value = sv->data[idx];
}
/**
* \ingroup strvector
* \function igraph_strvector_set
* \brief Set an element
*
* The provided \p value is copied into the \p idx position in the
* string vector.
* \param sv The string vector.
* \param idx The position to set.
* \param value The new value.
* \return Error code.
*
* Time complexity: O(l), the length of the new string. Maybe more,
* depending on the memory management, if reallocation is needed.
*/
int igraph_strvector_set(igraph_strvector_t *sv, long int idx,
const char *value) {
assert(sv != 0);
assert(sv->data != 0);
if (sv->data[idx] == 0) {
sv->data[idx] = igraph_Calloc(strlen(value) + 1, char);
if (sv->data[idx] == 0) {
IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM);
}
} else {
char *tmp = igraph_Realloc(sv->data[idx], strlen(value) + 1, char);
if (tmp == 0) {
IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM);
}
sv->data[idx] = tmp;
}
strcpy(sv->data[idx], value);
return 0;
}
/**
* \ingroup strvector
* \function igraph_strvector_set2
* \brief Sets an element
*
* This is almost the same as \ref igraph_strvector_set, but the new
* value is not a zero terminated string, but its length is given.
* \param sv The string vector.
* \param idx The position to set.
* \param value The new value.
* \param len The length of the new value.
* \return Error code.
*
* Time complexity: O(l), the length of the new string. Maybe more,
* depending on the memory management, if reallocation is needed.
*/
int igraph_strvector_set2(igraph_strvector_t *sv, long int idx,
const char *value, int len) {
assert(sv != 0);
assert(sv->data != 0);
if (sv->data[idx] == 0) {
sv->data[idx] = igraph_Calloc(len + 1, char);
if (sv->data[idx] == 0) {
IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM);
}
} else {
char *tmp = igraph_Realloc(sv->data[idx], (size_t) len + 1, char);
if (tmp == 0) {
IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM);
}
sv->data[idx] = tmp;
}
memcpy(sv->data[idx], value, (size_t) len * sizeof(char));
sv->data[idx][len] = '\0';
return 0;
}
/**
* \ingroup strvector
* \function igraph_strvector_remove_section
* \brief Removes a section from a string vector.
* \todo repair realloc
*/
void igraph_strvector_remove_section(igraph_strvector_t *v, long int from,
long int to) {
long int i;
/* char **tmp; */
assert(v != 0);
assert(v->data != 0);
for (i = from; i < to; i++) {
if (v->data[i] != 0) {
igraph_Free(v->data[i]);
}
}
for (i = 0; i < v->len - to; i++) {
v->data[from + i] = v->data[to + i];
}
v->len -= (to - from);
/* try to make it smaller */
/* tmp=igraph_Realloc(v->data, v->len, char*); */
/* if (tmp!=0) { */
/* v->data=tmp; */
/* } */
}
/**
* \ingroup strvector
* \function igraph_strvector_remove
* \brief Removes a single element from a string vector.
*
* The string will be one shorter.
* \param The string vector.
* \param elem The index of the element to remove.
*
* Time complexity: O(n), the length of the string.
*/
void igraph_strvector_remove(igraph_strvector_t *v, long int elem) {
assert(v != 0);
assert(v->data != 0);
igraph_strvector_remove_section(v, elem, elem + 1);
}
/**
* \ingroup strvector
* \function igraph_strvector_move_interval
* \brief Copies an interval of a string vector.
*/
void igraph_strvector_move_interval(igraph_strvector_t *v, long int begin,
long int end, long int to) {
long int i;
assert(v != 0);
assert(v->data != 0);
for (i = to; i < to + end - begin; i++) {
if (v->data[i] != 0) {
igraph_Free(v->data[i]);
}
}
for (i = 0; i < end - begin; i++) {
if (v->data[begin + i] != 0) {
size_t len = strlen(v->data[begin + i]) + 1;
v->data[to + i] = igraph_Calloc(len, char);
memcpy(v->data[to + i], v->data[begin + i], sizeof(char)*len);
}
}
}
/**
* \ingroup strvector
* \function igraph_strvector_copy
* \brief Initialization by copying.
*
* Initializes a string vector by copying another string vector.
* \param to Pointer to an uninitialized string vector.
* \param from The other string vector, to be copied.
* \return Error code.
*
* Time complexity: O(l), the total length of the strings in \p from.
*/
int igraph_strvector_copy(igraph_strvector_t *to,
const igraph_strvector_t *from) {
long int i;
char *str;
assert(from != 0);
/* assert(from->data != 0); */
to->data = igraph_Calloc(from->len, char*);
if (to->data == 0) {
IGRAPH_ERROR("Cannot copy string vector", IGRAPH_ENOMEM);
}
to->len = from->len;
for (i = 0; i < from->len; i++) {
int ret;
igraph_strvector_get(from, i, &str);
ret = igraph_strvector_set(to, i, str);
if (ret != 0) {
igraph_strvector_destroy(to);
IGRAPH_ERROR("cannot copy string vector", ret);
}
}
return 0;
}
/**
* \function igraph_strvector_append
* Concatenate two string vectors.
*
* \param to The first string vector, the result is stored here.
* \param from The second string vector, it is kept unchanged.
* \return Error code.
*
* Time complexity: O(n+l2), n is the number of strings in the new
* string vector, l2 is the total length of strings in the \p from
* string vector.
*/
int igraph_strvector_append(igraph_strvector_t *to,
const igraph_strvector_t *from) {
long int len1 = igraph_strvector_size(to), len2 = igraph_strvector_size(from);
long int i;
igraph_bool_t error = 0;
IGRAPH_CHECK(igraph_strvector_resize(to, len1 + len2));
for (i = 0; i < len2; i++) {
if (from->data[i][0] != '\0') {
igraph_Free(to->data[len1 + i]);
to->data[len1 + i] = strdup(from->data[i]);
if (!to->data[len1 + i]) {
error = 1;
break;
}
}
}
if (error) {
igraph_strvector_resize(to, len1);
IGRAPH_ERROR("Cannot append string vector", IGRAPH_ENOMEM);
}
return 0;
}
/**
* \function igraph_strvector_clear
* Remove all elements
*
* After this operation the string vector will be empty.
* \param sv The string vector.
*
* Time complexity: O(l), the total length of strings, maybe less,
* depending on the memory manager.
*/
void igraph_strvector_clear(igraph_strvector_t *sv) {
long int i, n = igraph_strvector_size(sv);
char **tmp;
for (i = 0; i < n; i++) {
igraph_Free(sv->data[i]);
}
sv->len = 0;
/* try to give back some memory */
tmp = igraph_Realloc(sv->data, 1, char*);
if (tmp != 0) {
sv->data = tmp;
}
}
/**
* \ingroup strvector
* \function igraph_strvector_resize
* \brief Resize
*
* If the new size is bigger then empty strings are added, if it is
* smaller then the unneeded elements are removed.
* \param v The string vector.
* \param newsize The new size.
* \return Error code.
*
* Time complexity: O(n), the number of strings if the vector is made
* bigger, O(l), the total length of the deleted strings if it is made
* smaller, maybe less, depending on memory management.
*/
int igraph_strvector_resize(igraph_strvector_t* v, long int newsize) {
long int toadd = newsize - v->len, i, j;
char **tmp;
long int reallocsize = newsize;
if (reallocsize == 0) {
reallocsize = 1;
}
assert(v != 0);
assert(v->data != 0);
/* printf("resize %li to %li\n", v->len, newsize); */
if (newsize < v->len) {
for (i = newsize; i < v->len; i++) {
igraph_Free(v->data[i]);
}
/* try to give back some space */
tmp = igraph_Realloc(v->data, (size_t) reallocsize, char*);
/* printf("resize %li to %li, %p\n", v->len, newsize, tmp); */
if (tmp != 0) {
v->data = tmp;
}
} else if (newsize > v->len) {
igraph_bool_t error = 0;
tmp = igraph_Realloc(v->data, (size_t) reallocsize, char*);
if (tmp == 0) {
IGRAPH_ERROR("cannot resize string vector", IGRAPH_ENOMEM);
}
v->data = tmp;
for (i = 0; i < toadd; i++) {
v->data[v->len + i] = igraph_Calloc(1, char);
if (v->data[v->len + i] == 0) {
error = 1;
break;
}
v->data[v->len + i][0] = '\0';
}
if (error) {
/* There was an error, free everything we've allocated so far */
for (j = 0; j < i; j++) {
if (v->data[v->len + i] != 0) {
igraph_Free(v->data[v->len + i]);
}
}
/* Try to give back space */
tmp = igraph_Realloc(v->data, (size_t) (v->len), char*);
if (tmp != 0) {
v->data = tmp;
}
IGRAPH_ERROR("Cannot resize string vector", IGRAPH_ENOMEM);
}
}
v->len = newsize;
return 0;
}
/**
* \ingroup strvector
* \function igraph_strvector_size
* \brief Gives the size of a string vector.
*
* \param sv The string vector.
* \return The length of the string vector.
*
* Time complexity: O(1).
*/
long int igraph_strvector_size(const igraph_strvector_t *sv) {
assert(sv != 0);
assert(sv->data != 0);
return sv->len;
}
/**
* \ingroup strvector
* \function igraph_strvector_add
* \brief Adds an element to the back of a string vector.
*
* \param v The string vector.
* \param value The string to add, it will be copied.
* \return Error code.
*
* Time complexity: O(n+l), n is the total number of strings, l is the
* length of the new string.
*/
int igraph_strvector_add(igraph_strvector_t *v, const char *value) {
long int s = igraph_strvector_size(v);
char **tmp;
assert(v != 0);
assert(v->data != 0);
tmp = igraph_Realloc(v->data, (size_t) s + 1, char*);
if (tmp == 0) {
IGRAPH_ERROR("cannot add string to string vector", IGRAPH_ENOMEM);
}
v->data = tmp;
v->data[s] = igraph_Calloc(strlen(value) + 1, char);
if (v->data[s] == 0) {
IGRAPH_ERROR("cannot add string to string vector", IGRAPH_ENOMEM);
}
strcpy(v->data[s], value);
v->len += 1;
return 0;
}
/**
* \ingroup strvector
* \function igraph_strvector_permdelete
* \brief Removes elements from a string vector (for internal use)
*/
void igraph_strvector_permdelete(igraph_strvector_t *v, const igraph_vector_t *index,
long int nremove) {
long int i;
char **tmp;
assert(v != 0);
assert(v->data != 0);
for (i = 0; i < igraph_strvector_size(v); i++) {
if (VECTOR(*index)[i] != 0) {
v->data[ (long int) VECTOR(*index)[i] - 1 ] = v->data[i];
} else {
igraph_Free(v->data[i]);
}
}
/* Try to make it shorter */
tmp = igraph_Realloc(v->data, v->len - nremove ?
(size_t) (v->len - nremove) : 1, char*);
if (tmp != 0) {
v->data = tmp;
}
v->len -= nremove;
}
/**
* \ingroup strvector
* \function igraph_strvector_remove_negidx
* \brief Removes elements from a string vector (for internal use)
*/
void igraph_strvector_remove_negidx(igraph_strvector_t *v, const igraph_vector_t *neg,
long int nremove) {
long int i, idx = 0;
char **tmp;
assert(v != 0);
assert(v->data != 0);
for (i = 0; i < igraph_strvector_size(v); i++) {
if (VECTOR(*neg)[i] >= 0) {
v->data[idx++] = v->data[i];
} else {
igraph_Free(v->data[i]);
}
}
/* Try to give back some memory */
tmp = igraph_Realloc(v->data, v->len - nremove ?
(size_t) (v->len - nremove) : 1, char*);
if (tmp != 0) {
v->data = tmp;
}
v->len -= nremove;
}
int igraph_strvector_print(const igraph_strvector_t *v, FILE *file,
const char *sep) {
long int i, n = igraph_strvector_size(v);
if (n != 0) {
fprintf(file, "%s", STR(*v, 0));
}
for (i = 1; i < n; i++) {
fprintf(file, "%s%s", sep, STR(*v, i));
}
return 0;
}
int igraph_strvector_index(const igraph_strvector_t *v,
igraph_strvector_t *newv,
const igraph_vector_t *idx) {
long int i, newlen = igraph_vector_size(idx);
IGRAPH_CHECK(igraph_strvector_resize(newv, newlen));
for (i = 0; i < newlen; i++) {
long int j = (long int) VECTOR(*idx)[i];
char *str;
igraph_strvector_get(v, j, &str);
igraph_strvector_set(newv, i, str);
}
return 0;
}
|
scala-steward/fdb-pubsub
|
pubsub/src/it/scala/com/github/pwliwanow/fdb/pubsub/internal/common/TopicMetadataSubspaceSpec.scala
|
<reponame>scala-steward/fdb-pubsub
package com.github.pwliwanow.fdb.pubsub.internal.common
import com.apple.foundationdb.tuple.Versionstamp
import com.github.pwliwanow.fdb.pubsub.FdbPubSubSpec
import com.github.pwliwanow.fdb.pubsub.internal.metadata.TopicMetadata
class TopicMetadataSubspaceSpec extends FdbPubSubSpec {
it should "be able to serialize and then deserialize the value" in {
val versionstamp = Versionstamp.complete(Array.fill[Byte](10)(0x0: Byte))
val value =
TopicMetadata(
topic = "testTopic",
numberOfPartitions = 7,
createdAt = utcClock.instant(),
createdIn = versionstamp)
typedTopicMetadataSubspace.set(value).transact(database).await
val fromDb =
typedTopicMetadataSubspace
.getRange(typedTopicMetadataSubspace.range)
.transact(database)
.await
assert(fromDb === List(value))
}
}
|
Techjar/LEDCubeManager
|
src/main/java/com/techjar/ledcm/hardware/handler/SerialPortHandler.java
|
package com.techjar.ledcm.hardware.handler;
import com.techjar.ledcm.LEDCubeManager;
import java.io.IOException;
import com.techjar.ledcm.Main;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortTimeoutException;
/**
*
* @author Techjar
*/
public class SerialPortHandler implements PortHandler {
private final SerialPort port;
public SerialPortHandler() {
port = new SerialPort(Main.getSerialPortName());
}
@Override
public boolean isOpened() {
return port.isOpened();
}
@Override
public void open(int baudRate) throws IOException {
try {
port.openPort();
port.setParams(baudRate, 8, 1, 0);
} catch (SerialPortException ex) {
throw new IOException(ex);
}
}
@Override
public void close() throws IOException {
try {
port.closePort();
} catch (SerialPortException ex) {
throw new IOException(ex);
}
}
@Override
public byte[] readBytes() throws IOException {
try {
return port.readBytes();
} catch (SerialPortException ex) {
throw new IOException(ex);
}
}
@Override
public byte[] readBytes(int count) throws IOException {
try {
return port.readBytes(count);
} catch (SerialPortException ex) {
throw new IOException(ex);
}
}
@Override
public byte[] readBytes(int count, int timeout) throws IOException {
try {
return port.readBytes(count, timeout);
} catch (SerialPortException | SerialPortTimeoutException ex) {
throw new IOException(ex);
}
}
@Override
public void writeByte(byte b) throws IOException {
try {
port.writeByte(b);
} catch (SerialPortException ex) {
throw new IOException(ex);
}
}
@Override
public void writeBytes(byte[] b) throws IOException {
try {
port.writeBytes(b);
} catch (SerialPortException ex) {
throw new IOException(ex);
}
}
}
|
Ilyaki/ProtoInput
|
lib/EasyHook/EasyHookDll/RemoteHook/thread.c
|
// EasyHook (File: EasyHookDll\thread.c)
//
// Copyright (c) 2009 <NAME> & Copyright (c) 2015 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS 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.
//
// Please visit https://easyhook.github.io for more information
// about the project and latest updates.
#include "stdafx.h"
BYTE* GetInjectionPtr();
DWORD GetInjectionSize();
extern DWORD RhTlsIndex;
EASYHOOK_NT_INTERNAL RhSetWakeUpThreadID(ULONG InThreadID)
{
/*
Description:
Used in conjunction with RhCreateAndInject(). If the given thread
later is resumed in RhWakeUpProcess(), the injection target will
start its usual execution.
*/
NTSTATUS NtStatus;
if(!TlsSetValue(RhTlsIndex, (LPVOID)(size_t)InThreadID))
THROW(STATUS_INTERNAL_ERROR, L"Unable to set TLS value.");
RETURN(STATUS_SUCCESS);
THROW_OUTRO:
FINALLY_OUTRO:
return NtStatus;
}
EASYHOOK_NT_EXPORT RhWakeUpProcess()
{
/*
Description:
Used in conjunction with RhCreateAndInject(). Wakes up the
injection target. You should call this method after all hooks
(or whatever) are applied.
*/
NTSTATUS NtStatus;
ULONG ThreadID = (ULONG)TlsGetValue(RhTlsIndex);
HANDLE hThread = NULL;
if(ThreadID == 0)
RETURN(STATUS_SUCCESS);
if((hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, ThreadID)) == NULL)
THROW(STATUS_INTERNAL_ERROR, L"Unable to open wake up thread.");
if(!ResumeThread(hThread))
THROW(STATUS_INTERNAL_ERROR, L"Unable to resume process main thread.");
RETURN(STATUS_SUCCESS);
THROW_OUTRO:
FINALLY_OUTRO:
{
if(hThread != NULL)
CloseHandle(hThread);
return NtStatus;
}
}
EASYHOOK_NT_EXPORT RhGetProcessToken(
ULONG InProcessId,
HANDLE* OutToken)
{
/*
Description:
This method is intended for the managed layer and has no special
advantage in an unmanaged environment!
Parameters:
- InProcessId
The target process shall be accessible with PROCESS_QUERY_INFORMATION.
- OutToken
The identity token for the session the process was created in.
*/
HANDLE hProc = NULL;
NTSTATUS NtStatus;
if(!IsValidPointer(OutToken, sizeof(HANDLE)))
THROW(STATUS_INVALID_PARAMETER_2, L"The given token storage is invalid.");
if((hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, InProcessId)) == NULL)
{
if(GetLastError() == ERROR_ACCESS_DENIED)
THROW(STATUS_ACCESS_DENIED, L"The given process is not accessible.")
else
THROW(STATUS_NOT_FOUND, L"The given process does not exist.");
}
if(!OpenProcessToken(hProc, TOKEN_READ, OutToken))
THROW(STATUS_INTERNAL_ERROR, L"Unable to query process token.");
RETURN(STATUS_SUCCESS);
THROW_OUTRO:
FINALLY_OUTRO:
{
if(hProc != NULL)
CloseHandle(hProc);
return NtStatus;
}
}
EASYHOOK_BOOL_EXPORT RhIsAdministrator()
{
/*
Description:
If someone is able to open the SCM with all access he is also able to create and start system services
and so he is also able to act as a part of the system! We are just letting
windows decide and don't enforce that the user is in the builtin admin group.
*/
SC_HANDLE hSCManager = NULL;
if((hSCManager = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == NULL)
return FALSE;
CloseServiceHandle(hSCManager);
return TRUE;
}
typedef LONG WINAPI NtCreateThreadEx_PROC(
PHANDLE ThreadHandle,
ACCESS_MASK DesiredAccess,
LPVOID ObjectAttributes,
HANDLE ProcessHandle,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
BOOL CreateSuspended,
DWORD dwStackSize,
LPVOID Unknown1,
LPVOID Unknown2,
LPVOID Unknown3
);
EASYHOOK_NT_INTERNAL NtCreateThreadEx(
HANDLE InProcess,
LPTHREAD_START_ROUTINE InRemoteThreadStart,
void* InRemoteCallback,
BOOLEAN InCreateSuspended,
HANDLE* OutThread)
{
/*
Description:
Only intended for Vista and later... Will return NULL for all others which
should use CreateRemoteThread() and services instead!
In contrast to RtlCreateUserThread() this one will fortunately setup a proper activation
context stack, which is required to load the NET framework and many other
common APIs. This is why RtlCreateUserThread() can't be used for Windows XP
,for example, even if it would replace the windows service approach which is required
in order to get CreateRemoteThread() working.
Injection through WOW64 boundaries is still not directly supported and requires
a WOW64 bypass helper process.
Parameters:
- InProcess
A target process opened with PROCESS_ALL_ACCESS.
- InRemoteThreadStart
The method executed by the remote thread. Must be valid in the
context of the given process.
- InRemoteCallback
An uninterpreted callback passed to the remote start routine.
Must be valid in the context of the given process.
- OutThread
Receives a handle to the remote thread. This handle is valid
in the calling process.
Returns:
STATUS_NOT_SUPPORTED
Only Windows Vista and later supports NtCreateThreadEx, all other
platforms will return this error code.
*/
HANDLE hRemoteThread;
NTSTATUS NtStatus;
NtCreateThreadEx_PROC* VistaCreateThread;
if(!IsValidPointer(OutThread, sizeof(HANDLE)))
THROW(STATUS_INVALID_PARAMETER_4, L"The given handle storage is invalid.");
// this will only work for vista and later...
if((VistaCreateThread = (NtCreateThreadEx_PROC*)GetProcAddress(hNtDll, "NtCreateThreadEx")) == NULL)
THROW(STATUS_NOT_SUPPORTED, L"NtCreateThreadEx() is not supported.");
FORCE(VistaCreateThread(
&hRemoteThread,
0x1FFFFF, // all access
NULL,
InProcess,
(LPTHREAD_START_ROUTINE)InRemoteThreadStart,
InRemoteCallback,
InCreateSuspended,
0,
NULL,
NULL,
NULL
));
*OutThread = hRemoteThread;
RETURN;
THROW_OUTRO:
FINALLY_OUTRO:
return NtStatus;
}
EASYHOOK_NT_INTERNAL NtForceLdrInitializeThunk(HANDLE hProc)
{
/*
Description:
Allows us to retrieve remote function addresses for a suspended process by starting a
remote thread that runs a single instruction function (ret). Thanks to werker: https://github.com/EasyHook/EasyHook/issues/9
Parameters:
- hProcess
The handle to the remote process to force loader initialization
*/
HANDLE hRemoteThread = NULL;
UCHAR* RemoteInjectCode = NULL;
BYTE InjectCode[3];
ULONG CodeSize;
SIZE_T BytesWritten;
NTSTATUS NtStatus;
#ifdef _M_X64
InjectCode[0] = 0xC3; // ret
CodeSize = 1;
#else
InjectCode[0] = 0xC2; // ret 0x4
InjectCode[1] = 0x04;
InjectCode[2] = 0x00;
CodeSize = 3;
#endif
if ((RemoteInjectCode = (BYTE*)VirtualAllocEx(hProc, NULL, CodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) == NULL)
THROW(STATUS_NO_MEMORY, L"Unable to allocate memory in target process.");
if (!WriteProcessMemory(hProc, RemoteInjectCode, InjectCode, CodeSize, &BytesWritten) || (BytesWritten != CodeSize))
THROW(STATUS_INTERNAL_ERROR, L"Unable to write into target process memory.");
if (!RTL_SUCCESS(NtCreateThreadEx(hProc, (LPTHREAD_START_ROUTINE)RemoteInjectCode, NULL, FALSE, &hRemoteThread)))
{
if ((hRemoteThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)RemoteInjectCode, NULL, 0, NULL)) == NULL)
THROW(STATUS_ACCESS_DENIED, L"Unable to create remote thread.");
}
WaitForSingleObject(hRemoteThread, INFINITE);
RETURN;
THROW_OUTRO:
FINALLY_OUTRO :
return NtStatus;
}
typedef BOOL __stdcall IsWow64Process_PROC(HANDLE InProc, BOOL* OutResult);
typedef void GetNativeSystemInfo_PROC(LPSYSTEM_INFO OutSysInfo);
EASYHOOK_NT_EXPORT RhIsX64Process(
ULONG InProcessId,
BOOL* OutResult)
{
/*
Description:
Detects the bitness of a given process.
Parameters:
- InProcessId
The calling process must have PROCESS_QUERY_INFORMATION access
to the process represented by this ID.
- OutResult
Is set to TRUE if the given process is running under 64-Bit,
FALSE otherwise.
*/
BOOL IsTarget64Bit = FALSE;
HANDLE hProc = NULL;
IsWow64Process_PROC* pIsWow64Process;
NTSTATUS NtStatus;
#ifndef _M_X64
GetNativeSystemInfo_PROC* pGetNativeSystemInfo;
SYSTEM_INFO SysInfo;
#endif
if(!IsValidPointer(OutResult, sizeof(BOOL)))
THROW(STATUS_INVALID_PARAMETER_2, L"The given result storage is invalid.");
// open target process
if((hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, InProcessId)) == NULL)
{
if(GetLastError() == ERROR_ACCESS_DENIED)
THROW(STATUS_ACCESS_DENIED, L"The given process is not accessible.")
else
THROW(STATUS_NOT_FOUND, L"The given process does not exist.");
}
// if WOW64 is not available then target must be 32-bit
pIsWow64Process = (IsWow64Process_PROC*)GetProcAddress(hKernel32, "IsWow64Process");
#ifdef _M_X64
// if the target is not WOW64, then it is 64-bit
if(!pIsWow64Process(hProc, &IsTarget64Bit))
THROW(STATUS_INTERNAL_ERROR, L"Unable to detect wether target process is 64-bit or not.");
IsTarget64Bit = !IsTarget64Bit;
#else
IsTarget64Bit = FALSE;
if(pIsWow64Process != NULL)
{
// check if we are running on a 32-bit OS
pGetNativeSystemInfo = (GetNativeSystemInfo_PROC*)GetProcAddress(hKernel32, "GetNativeSystemInfo");
if(pGetNativeSystemInfo != NULL)
{
pGetNativeSystemInfo(&SysInfo);
if(SysInfo.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_INTEL)
{
// if not, then and only then a 32-bit process will be marked as WOW64 process!
if(!pIsWow64Process(hProc, &IsTarget64Bit))
THROW(STATUS_INTERNAL_ERROR, L"Unable to detect wether target process is 64-bit or not.");
IsTarget64Bit = !IsTarget64Bit;
}
}
}
#endif
*OutResult = IsTarget64Bit;
RETURN(STATUS_SUCCESS);
THROW_OUTRO:
FINALLY_OUTRO:
{
if(hProc != NULL)
CloseHandle(hProc);
return NtStatus;
}
}
#ifndef _DEBUG
#pragma optimize ("", off) // suppress _memcpy
#endif
EASYHOOK_BOOL_EXPORT RhIsX64System()
{
/*
Description:
Determines whether the calling PC is running a 64-Bit version
of windows.
*/
#ifndef _M_X64
GetNativeSystemInfo_PROC* pGetNativeSystemInfo;
SYSTEM_INFO SysInfo;
pGetNativeSystemInfo = (GetNativeSystemInfo_PROC*)GetProcAddress(hKernel32, "GetNativeSystemInfo");
if(pGetNativeSystemInfo == NULL)
return FALSE;
pGetNativeSystemInfo(&SysInfo);
if(SysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
return FALSE;
#endif
return TRUE;
}
EASYHOOK_NT_EXPORT RtlCreateSuspendedProcess(
WCHAR* InEXEPath,
WCHAR* InCommandLine,
ULONG InCustomFlags,
ULONG* OutProcessId,
ULONG* OutThreadId,
PVOID lpEnvironment)
{
/*
Description:
Creates a suspended process with the given parameters.
This is only intended for the managed layer.
Parameters:
- InEXEPath
A relative or absolute path to the EXE file of the process being created.
- InCommandLine
Optional command line parameters passed to the newly created process.
- InCustomFlags
Additional process creation flags.
- OutProcessId
Receives the PID of the newly created process.
- OutThreadId
Receives the initial TID of the newly created process.
*/
#define MAX_CREATEPROCESS_COMMANDLINE 32768
STARTUPINFO StartInfo;
PROCESS_INFORMATION ProcessInfo;
WCHAR FullExePath[MAX_PATH + 1];
WCHAR FullCommandLine[MAX_CREATEPROCESS_COMMANDLINE];
WCHAR CurrentDir[MAX_PATH + 1];
WCHAR* FilePart;
NTSTATUS NtStatus;
// must be executed before any THROW or RETURN!
RtlZeroMemory(&StartInfo, sizeof(StartInfo));
RtlZeroMemory(&ProcessInfo, sizeof(ProcessInfo));
if(!IsValidPointer(OutProcessId, sizeof(ULONG)))
THROW(STATUS_INVALID_PARAMETER_3, L"The given process ID storage is invalid.");
if(!IsValidPointer(OutThreadId, sizeof(ULONG)))
THROW(STATUS_INVALID_PARAMETER_4, L"The given thread ID storage is invalid.");
// parse path
if(!RtlFileExists(InEXEPath))
THROW(STATUS_INVALID_PARAMETER_1, L"The given process file does not exist.");
if(GetFullPathName(InEXEPath, MAX_PATH, CurrentDir, &FilePart) > MAX_PATH)
THROW(STATUS_INVALID_PARAMETER_1, L"Full path information exceeds MAX_PATH characters.");
// compute current directory...
RtlCopyMemory(FullExePath, CurrentDir, sizeof(FullExePath));
swprintf_s(FullCommandLine, MAX_CREATEPROCESS_COMMANDLINE, L"\"%s\" %s", FullExePath, InCommandLine);
*FilePart = 0;
// create suspended process
StartInfo.cb = sizeof(StartInfo);
StartInfo.wShowWindow = TRUE;
if(!CreateProcessW(
FullExePath,
FullCommandLine,
NULL, NULL,
FALSE,
InCustomFlags | CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT,
lpEnvironment,
CurrentDir,
&StartInfo,
&ProcessInfo))
THROW(STATUS_INVALID_PARAMETER, L"Unable to start process; please check the given parameters.");
*OutProcessId = ProcessInfo.dwProcessId;
*OutThreadId = ProcessInfo.dwThreadId;
RETURN;
THROW_OUTRO:
FINALLY_OUTRO:
{
if(ProcessInfo.hProcess != NULL)
CloseHandle(ProcessInfo.hProcess);
if(ProcessInfo.hThread != NULL)
CloseHandle(ProcessInfo.hThread);
return NtStatus;
}
}
// NTSTATUS EASYHOOK_API RtlCreateSuspendedProcess(
// WCHAR* InEXEPath,
// WCHAR* InCommandLine,
// ULONG InCustomFlags,
// ULONG* OutProcessId,
// ULONG* OutThreadId)
// {
// return RtlCreateSuspendedProcess(InEXEPath, InCommandLine, InCustomFlags, OutProcessId, OutThreadId, 0);
// }
EASYHOOK_NT_EXPORT RhCreateAndInject(
WCHAR* InEXEPath,
WCHAR* InCommandLine,
ULONG InProcessCreationFlags,
ULONG InInjectionOptions,
WCHAR* InLibraryPath_x86,
WCHAR* InLibraryPath_x64,
PVOID InPassThruBuffer,
ULONG InPassThruSize,
ULONG* OutProcessId)
{
/*
Description:
Creates a suspended process and immediately injects the user library.
This is done BEFORE any of the usual process initialization is called.
When the injection is made, NO thread has actually executed any instruction
so far... It is just like your library entry point is the first thing
executed in such a process and you can allow the original execution to
take place by calling RhWakeUpProcess() in the injected library. But even
that is no requirement for the process to work...
Parameters:
- InEXEPath
A relative or absolute path to the EXE file of the process being created.
- InCommandLine
Optional command line parameters passed to the newly created process.
- InProcessCreationFlags
Custom process creation flags.
- InInjectionOptions
All flags can be combined.
EASYHOOK_INJECT_DEFAULT:
No special behavior. The given libraries are expected to be unmanaged DLLs.
Further they should export an entry point named
"NativeInjectionEntryPoint" (in case of 64-bit) and
"_NativeInjectionEntryPoint@4" (in case of 32-bit). The expected entry point
signature is REMOTE_ENTRY_POINT.
EASYHOOK_INJECT_MANAGED:
The given user library is a NET assembly. Further they should export a class
named "EasyHook.InjectionLoader" with a static method named "Main". The
signature of this method is expected to be "int (String)". Please refer
to the managed injection loader of EasyHook for more information about
writing such managed entry points.
EASYHOOK_INJECT_STEALTH:
Uses the experimental stealth thread creation. If it fails
you may try it with default settings.
- InLibraryPath_x86
A relative or absolute path to the 32-bit version of the user library being injected.
If you don't want to inject into 32-Bit processes, you may set this parameter to NULL.
- InLibraryPath_x64
A relative or absolute path to the 64-bit version of the user library being injected.
If you don't want to inject into 64-Bit processes, you may set this parameter to NULL.
- InPassThruBuffer
An optional buffer containg data to be passed to the injection entry point. Such data
is available in both, the managed and unmanaged user library entry points.
Set to NULL if no used.
- InPassThruSize
Specifies the size in bytes of the pass thru data. If "InPassThruBuffer" is NULL, this
parameter shall also be zero.
- OutProcessId
Receives the PID of the newly created process.
*/
ULONG ProcessId = 0;
ULONG ThreadId = 0;
HANDLE hProcess = NULL;
NTSTATUS NtStatus;
if(!IsValidPointer(OutProcessId, sizeof(ULONG)))
THROW(STATUS_INVALID_PARAMETER_8, L"The given process ID storage is invalid.");
// all other parameters are validate by called APIs...
FORCE(RtlCreateSuspendedProcess(InEXEPath, InCommandLine, InProcessCreationFlags, &ProcessId, &ThreadId, 0));
// inject library
FORCE(RhInjectLibrary(
ProcessId,
ThreadId,
InInjectionOptions,
InLibraryPath_x86,
InLibraryPath_x64,
InPassThruBuffer,
InPassThruSize));
*OutProcessId = ProcessId;
RETURN;
THROW_OUTRO:
{
if(ProcessId != 0)
{
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId);
TerminateProcess(hProcess, 0);
CloseHandle(hProcess);
}
}
FINALLY_OUTRO:
return NtStatus;
}
#ifndef _DEBUG
#pragma optimize ("", on)
#endif
BOOL EASYHOOK_API GetRemoteModuleExportDirectory(HANDLE hProcess, HMODULE hRemote, PIMAGE_EXPORT_DIRECTORY ExportDirectory, IMAGE_DOS_HEADER DosHeader, IMAGE_NT_HEADERS NtHeaders) {
/*
Description:
Retrieves the export dictionary for the provided module.
Parameters:
- hProcess
The handle to the remote process to read from
- hRemote
The handle to the remote module to retrieve the export dictionary for
- ExportDictionary
Will contain the resulting export dictionary
- DosHeader
The preloaded DOS PE Header
e.g.: ReadProcessMemory(hProcess, (void*)hRemote, &DosHeader, sizeof(IMAGE_DOS_HEADER), NULL)
- NtHeaders
The preloaded NT PE headers
e.g.: dwNTHeaders = (PDWORD)((DWORD)hRemote + DosHeader.e_lfanew);
ReadProcessMemory(hProcess, dwNTHeaders, &NtHeaders, sizeof(IMAGE_NT_HEADERS), NULL)
*/
PUCHAR ucAllocatedPEHeader;
PIMAGE_SECTION_HEADER pImageSectionHeader;
int i;
DWORD dwEATAddress;
if(!ExportDirectory)
return FALSE;
ucAllocatedPEHeader = (PUCHAR)malloc(1000 * sizeof(UCHAR));
memset(ExportDirectory, 0, sizeof(IMAGE_EXPORT_DIRECTORY));
if(!ReadProcessMemory(hProcess, (void*)hRemote, ucAllocatedPEHeader, (SIZE_T)1000, NULL))
return FALSE;
pImageSectionHeader = (PIMAGE_SECTION_HEADER)(ucAllocatedPEHeader + DosHeader.e_lfanew + sizeof(IMAGE_NT_HEADERS));
for(i = 0; i < NtHeaders.FileHeader.NumberOfSections; i++, pImageSectionHeader++) {
if(!pImageSectionHeader)
continue;
if(_stricmp((char*)pImageSectionHeader->Name, ".edata") == 0) {
if(!ReadProcessMemory(hProcess, (void*)pImageSectionHeader->VirtualAddress, ExportDirectory, sizeof(IMAGE_EXPORT_DIRECTORY), NULL))
continue;
free(ucAllocatedPEHeader);
return TRUE;
}
}
dwEATAddress = NtHeaders.OptionalHeader.DataDirectory[0].VirtualAddress;
if(!dwEATAddress)
return FALSE;
if(!ReadProcessMemory(hProcess, (void*)((DWORD_PTR)hRemote + dwEATAddress), ExportDirectory, sizeof(IMAGE_EXPORT_DIRECTORY), NULL))
return FALSE;
free(ucAllocatedPEHeader);
return TRUE;
}
HMODULE GetRemoteModuleHandle(unsigned long pId, char *module)
{
/*
Description:
Get Remote Module Handle retrieves a handle to the specified module within the provided process Id
Parameters:
- pId
The Id of the target process to find the module within
- module
The name of the module
Example:
GetRemoteModuleHandle(PID, "kernel32.dll");
*/
MODULEENTRY32 modEntry;
HANDLE tlh = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pId);
char moduleChar[256] = { 0 };
modEntry.dwSize = sizeof(MODULEENTRY32);
Module32First(tlh, &modEntry);
do
{
size_t i;
wcstombs_s(&i, moduleChar, 256, modEntry.szModule, 256);
if(!_stricmp(moduleChar, module))
{
CloseHandle(tlh);
return modEntry.hModule;
}
modEntry.dwSize = sizeof(MODULEENTRY32);
}
while(Module32Next(tlh, &modEntry));
CloseHandle(tlh);
return NULL;
}
void * GetRemoteFuncAddress(unsigned long pId, HANDLE hProcess, char* module, char* func) {
/*
Description:
Get remote function address for the module within the remote process.
This is done by retrieving the exports found within the specified module and
finding a match for "func". The export name must exactly match "func".
Parameters:
- pId
The Id of the remote process
- hProcess
The handle of the remote process as returned by a call to OpenProcess
- module
The name of the module that contains the function within the remote process
- func
The name of the function within the module to find the address for
Example:
INT_PTR fAddress = GetRemoteFuncAddress(pId, hProcess, "kernel32.dll", "GetProcAddress");
*/
HMODULE hRemote = GetRemoteModuleHandle(pId, module);
IMAGE_DOS_HEADER DosHeader;
IMAGE_NT_HEADERS NtHeaders;
IMAGE_EXPORT_DIRECTORY EATDirectory;
DWORD* AddressOfFunctions;
DWORD* AddressOfNames;
WORD* AddressOfOrdinals;
unsigned int i;
DWORD_PTR dwExportBase;
DWORD_PTR dwExportSize;
DWORD_PTR dwAddressOfFunction;
DWORD_PTR dwAddressOfName;
char pszFunctionName[256] = { 0 };
char pszRedirectName[256] = { 0 };
char pszModuleName[256] = { 0 };
char pszFunctionRedi[256] = { 0 };
int a = 0;
int b = 0;
WORD OrdinalValue;
DWORD_PTR dwAddressOfRedirectedFunction;
DWORD_PTR dwAddressOfRedirectedName;
char pszRedirectedFunctionName[ 256 ] = { 0 };
if(!hRemote)
return NULL;
// Load DOS PE header
if(!ReadProcessMemory(hProcess, (void*)hRemote, &DosHeader, sizeof(IMAGE_DOS_HEADER), NULL) || DosHeader.e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
// Load NT PE headers
if(!ReadProcessMemory(hProcess, (void *)((DWORD_PTR)hRemote + DosHeader.e_lfanew), &NtHeaders, sizeof(IMAGE_NT_HEADERS), NULL) || NtHeaders.Signature != IMAGE_NT_SIGNATURE)
return NULL;
// Load image export directory
if(!GetRemoteModuleExportDirectory(hProcess, hRemote, &EATDirectory, DosHeader, NtHeaders))
return NULL;
// Allocate room for all the function information
AddressOfFunctions = (DWORD*)malloc(EATDirectory.NumberOfFunctions * sizeof(DWORD));
AddressOfNames = (DWORD*)malloc(EATDirectory.NumberOfNames * sizeof(DWORD));
AddressOfOrdinals = (WORD*)malloc(EATDirectory.NumberOfNames * sizeof(WORD));
// Read function address locations
if(!ReadProcessMemory(hProcess, (void*)((DWORD_PTR)hRemote + (DWORD_PTR)EATDirectory.AddressOfFunctions), AddressOfFunctions, EATDirectory.NumberOfFunctions * sizeof(DWORD), NULL)) {
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return NULL;
}
// Read function name locations
if(!ReadProcessMemory(hProcess, (void*)((DWORD_PTR)hRemote + (DWORD_PTR)EATDirectory.AddressOfNames), AddressOfNames, EATDirectory.NumberOfNames * sizeof(DWORD), NULL)) {
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return NULL;
}
// Read function name ordinal locations
if(!ReadProcessMemory(hProcess, (void*)((DWORD_PTR)hRemote + (DWORD_PTR)EATDirectory.AddressOfNameOrdinals), AddressOfOrdinals, EATDirectory.NumberOfNames * sizeof(WORD), NULL)) {
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return NULL;
}
dwExportBase = ((DWORD_PTR)hRemote + NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
dwExportSize = (dwExportBase + NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size);
// Check each name for a match
for(i = 0; i < EATDirectory.NumberOfNames; ++i) {
dwAddressOfFunction = (DWORD_PTR)hRemote + AddressOfFunctions[i];
dwAddressOfName = (DWORD_PTR)hRemote + AddressOfNames[i];
memset(&pszFunctionName, 0, 256);
if(!ReadProcessMemory(hProcess, (void*)dwAddressOfName, pszFunctionName, 256, NULL))
continue;
// Skip until we find the matching function name
if(_stricmp(pszFunctionName, func) != 0)
continue;
// Check if address of function is found in another module
if(dwAddressOfFunction >= dwExportBase && dwAddressOfFunction <= dwExportSize) {
memset(&pszRedirectName, 0, 256);
if(!ReadProcessMemory(hProcess, (void*)dwAddressOfFunction, pszRedirectName, 256, NULL))
continue;
memset(&pszModuleName, 0, 256);
memset(&pszFunctionRedi, 0, 256);
a = 0;
for(; pszRedirectName[a] != '.'; a++)
pszModuleName[a] = pszRedirectName[a];
a++;
pszModuleName[a] = '\0';
b = 0;
for(; pszRedirectName[a] != '\0'; a++, b++)
pszFunctionRedi[b] = pszRedirectName[a];
b++;
pszFunctionRedi[b] = '\0';
strcat_s(pszModuleName, 256, ".dll");
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return GetRemoteFuncAddress(pId, hProcess, pszModuleName, pszFunctionRedi);
}
OrdinalValue = AddressOfOrdinals[i];
if (OrdinalValue >= EATDirectory.NumberOfNames)
{
return NULL;
}
// If ordinal doesn't match index retrieve correct address
if(OrdinalValue != i) {
dwAddressOfRedirectedFunction = ((DWORD_PTR)hRemote + (DWORD_PTR)AddressOfFunctions[OrdinalValue]);
dwAddressOfRedirectedName = ((DWORD_PTR)hRemote + (DWORD_PTR)AddressOfNames[OrdinalValue]);
memset(&pszRedirectedFunctionName, 0, 256);
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
if(!ReadProcessMemory(hProcess, (void*)dwAddressOfRedirectedName, pszRedirectedFunctionName, 256, NULL))
return NULL;
else
return (void*)dwAddressOfRedirectedFunction;
}
// Otherwise return the address
else {
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return (void*)dwAddressOfFunction;
}
}
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return NULL;
}
EASYHOOK_NT_EXPORT RhInjectLibrary(
ULONG InTargetPID,
ULONG InWakeUpTID,
ULONG InInjectionOptions,
WCHAR* InLibraryPath_x86,
WCHAR* InLibraryPath_x64,
PVOID InPassThruBuffer,
ULONG InPassThruSize)
{
/*
Description:
Injects a library into the target process. This is a very stable operation.
The problem so far is, that only the NET layer will support injection
through WOW64 boundaries and into other terminal sessions. It is quite
complex to realize with unmanaged code and that's why it is not supported!
If you really need this feature I highly recommend to at least look at C++.NET
because using the managed injection can speed up your development progress
about orders of magnitudes. I know by experience that writing the required
multi-process injection code in any unmanaged language is a rather daunting task!
Parameters:
- InTargetPID
The process in which the library should be injected.
- InWakeUpTID
If the target process was created suspended (RhCreateAndInject), then
this parameter should be set to the main thread ID of the target.
You may later resume the process from within the injected library
by calling RhWakeUpProcess(). If the process is already running, you
should specify zero.
- InInjectionOptions
All flags can be combined.
EASYHOOK_INJECT_DEFAULT:
No special behavior. The given libraries are expected to be unmanaged DLLs.
Further they should export an entry point named
"NativeInjectionEntryPoint" (in case of 64-bit) and
"_NativeInjectionEntryPoint@4" (in case of 32-bit). The expected entry point
signature is REMOTE_ENTRY_POINT.
EASYHOOK_INJECT_MANAGED:
The given user library is a NET assembly. Further they should export a class
named "EasyHook.InjectionLoader" with a static method named "Main". The
signature of this method is expected to be "int (String)". Please refer
to the managed injection loader of EasyHook for more information about
writing such managed entry points.
EASYHOOK_INJECT_STEALTH:
Uses the experimental stealth thread creation. If it fails
you may try it with default settings.
EASYHOOK_INJECT_HEART_BEAT:
Is only used internally to workaround the managed process creation bug.
For curiosity, NET seems to hijack our remote thread if a managed process
is created suspended. It doesn't do anything with the suspended main thread,
- InLibraryPath_x86
A relative or absolute path to the 32-bit version of the user library being injected.
If you don't want to inject into 32-Bit processes, you may set this parameter to NULL.
- InLibraryPath_x64
A relative or absolute path to the 64-bit version of the user library being injected.
If you don't want to inject into 64-Bit processes, you may set this parameter to NULL.
- InPassThruBuffer
An optional buffer containg data to be passed to the injection entry point. Such data
is available in both, the managed and unmanaged user library entry points.
Set to NULL if no used.
- InPassThruSize
Specifies the size in bytes of the pass thru data. If "InPassThruBuffer" is NULL, this
parameter shall also be zero.
Returns:
*/
HANDLE hProc = NULL;
HANDLE hRemoteThread = NULL;
HANDLE hSignal = NULL;
UCHAR* RemoteInjectCode = NULL;
LPREMOTE_INFO Info = NULL;
LPREMOTE_INFO RemoteInfo = NULL;
ULONG RemoteInfoSize = 0;
BYTE* Offset = 0;
ULONG CodeSize;
BOOL Is64BitTarget;
NTSTATUS NtStatus;
LONGLONG Diff;
HANDLE Handles[2];
ULONG UserLibrarySize;
ULONG PATHSize;
ULONG EasyHookPathSize;
ULONG EasyHookEntrySize;
ULONG Code;
SIZE_T BytesWritten;
WCHAR UserLibrary[MAX_PATH+1];
WCHAR PATH[MAX_PATH + 1];
WCHAR EasyHookPath[MAX_PATH + 1];
#ifdef _M_X64
CHAR* EasyHookEntry = "HookCompleteInjection";
#else
CHAR* EasyHookEntry = "_HookCompleteInjection@4";
#endif
// validate parameters
if(InPassThruSize > MAX_PASSTHRU_SIZE)
THROW(STATUS_INVALID_PARAMETER_7, L"The given pass thru buffer is too large.");
if(InPassThruBuffer != NULL)
{
if(!IsValidPointer(InPassThruBuffer, InPassThruSize))
THROW(STATUS_INVALID_PARAMETER_6, L"The given pass thru buffer is invalid.");
}
else if(InPassThruSize != 0)
THROW(STATUS_INVALID_PARAMETER_7, L"If no pass thru buffer is specified, the pass thru length also has to be zero.");
if(InTargetPID == GetCurrentProcessId())
THROW(STATUS_NOT_SUPPORTED, L"For stability reasons it is not supported to inject into the calling process.");
// open target process
if((hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, InTargetPID)) == NULL)
{
if(GetLastError() == ERROR_ACCESS_DENIED)
THROW(STATUS_ACCESS_DENIED, L"Unable to open target process. Consider using a system service.")
else
THROW(STATUS_NOT_FOUND, L"The given target process does not exist!");
}
/*
Check bitness...
After this we can assume hooking a target that is running in the same
WOW64 level.
*/
#ifdef _M_X64
FORCE(RhIsX64Process(InTargetPID, &Is64BitTarget));
if(!Is64BitTarget)
THROW(STATUS_WOW_ASSERTION, L"It is not supported to directly hook through the WOW64 barrier.");
if(!GetFullPathNameW(InLibraryPath_x64, MAX_PATH, UserLibrary, NULL))
THROW(STATUS_INVALID_PARAMETER_5, L"Unable to get full path to the given 64-bit library.");
#else
FORCE(RhIsX64Process(InTargetPID, &Is64BitTarget));
if(Is64BitTarget)
THROW(STATUS_WOW_ASSERTION, L"It is not supported to directly hook through the WOW64 barrier.");
if(!GetFullPathNameW(InLibraryPath_x86, MAX_PATH, UserLibrary, NULL))
THROW(STATUS_INVALID_PARAMETER_4, L"Unable to get full path to the given 32-bit library.");
#endif
/*
Validate library path...
*/
if(!RtlFileExists(UserLibrary))
{
#ifdef _M_X64
THROW(STATUS_INVALID_PARAMETER_5, L"The given 64-Bit library does not exist!");
#else
THROW(STATUS_INVALID_PARAMETER_4, L"The given 32-Bit library does not exist!");
#endif
}
// import strings...
RtlGetWorkingDirectory(PATH, MAX_PATH - 1);
RtlGetCurrentModulePath(EasyHookPath, MAX_PATH);
// allocate remote information block
EasyHookPathSize = (RtlUnicodeLength(EasyHookPath) + 1) * 2;
EasyHookEntrySize = (RtlAnsiLength(EasyHookEntry) + 1);
PATHSize = (RtlUnicodeLength(PATH) + 1 + 1) * 2;
UserLibrarySize = (RtlUnicodeLength(UserLibrary) + 1 + 1) * 2;
PATH[PATHSize / 2 - 2] = ';';
PATH[PATHSize / 2 - 1] = 0;
RemoteInfoSize = EasyHookPathSize + EasyHookEntrySize + PATHSize + InPassThruSize + UserLibrarySize;
RemoteInfoSize += sizeof(REMOTE_INFO);
if((Info = (LPREMOTE_INFO)RtlAllocateMemory(TRUE, RemoteInfoSize)) == NULL)
THROW(STATUS_NO_MEMORY, L"Unable to allocate memory in current process.");
// Ensure that if we have injected into a suspended process that we can retrieve the remote function addresses
FORCE(NtForceLdrInitializeThunk(hProc));
// https://github.com/EasyHook/EasyHook/issues/295#issuecomment-705084216
Sleep(1000);
// Determine function addresses within remote process
Info->LoadLibraryW = (PVOID)GetRemoteFuncAddress(InTargetPID, hProc, "kernel32.dll", "LoadLibraryW");
Info->FreeLibrary = (PVOID)GetRemoteFuncAddress(InTargetPID, hProc, "kernel32.dll", "FreeLibrary");
Info->GetProcAddress = (PVOID)GetRemoteFuncAddress(InTargetPID, hProc, "kernel32.dll", "GetProcAddress");
Info->VirtualFree = (PVOID)GetRemoteFuncAddress(InTargetPID, hProc, "kernel32.dll", "VirtualFree");
Info->VirtualProtect = (PVOID)GetRemoteFuncAddress(InTargetPID, hProc, "kernel32.dll", "VirtualProtect");
Info->ExitThread = (PVOID)GetRemoteFuncAddress(InTargetPID, hProc, "kernel32.dll", "ExitThread");
Info->GetLastError = (PVOID)GetRemoteFuncAddress(InTargetPID, hProc, "kernel32.dll", "GetLastError");
Info->WakeUpThreadID = InWakeUpTID;
Info->IsManaged = InInjectionOptions & EASYHOOK_INJECT_MANAGED;
// allocate memory in target process
CodeSize = GetInjectionSize();
if((RemoteInjectCode = (BYTE*)VirtualAllocEx(hProc, NULL, CodeSize + RemoteInfoSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) == NULL)
THROW(STATUS_NO_MEMORY, L"Unable to allocate memory in target process.");
// save strings
Offset = (BYTE*)(Info + 1);
Info->EasyHookEntry = (char*)Offset;
Info->EasyHookPath = (wchar_t*)(Offset += EasyHookEntrySize);
Info->PATH = (wchar_t*)(Offset += EasyHookPathSize);
Info->UserData = (BYTE*)(Offset += PATHSize);
Info->UserLibrary = (WCHAR*)(Offset += InPassThruSize);
Info->Size = RemoteInfoSize;
Info->HostProcess = GetCurrentProcessId();
Info->UserDataSize = 0;
Offset += UserLibrarySize;
if((ULONG)(Offset - ((BYTE*)Info)) > Info->Size)
THROW(STATUS_BUFFER_OVERFLOW, L"A buffer overflow in internal memory was detected.");
RtlCopyMemory(Info->EasyHookPath, EasyHookPath, EasyHookPathSize);
RtlCopyMemory(Info->PATH, PATH, PATHSize);
RtlCopyMemory(Info->EasyHookEntry, EasyHookEntry, EasyHookEntrySize);
RtlCopyMemory(Info->UserLibrary, UserLibrary, UserLibrarySize);
if(InPassThruBuffer != NULL)
{
RtlCopyMemory(Info->UserData, InPassThruBuffer, InPassThruSize);
Info->UserDataSize = InPassThruSize;
}
// copy code into target process
if(!WriteProcessMemory(hProc, RemoteInjectCode, GetInjectionPtr(), CodeSize, &BytesWritten) || (BytesWritten != CodeSize))
THROW(STATUS_INTERNAL_ERROR, L"Unable to write into target process memory.");
// create and export signal event>
if((hSignal = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL)
THROW(STATUS_INSUFFICIENT_RESOURCES, L"Unable to create event.");
// Possible resource leck: the remote handles cannt be closed here if an error occurs
if(!DuplicateHandle(GetCurrentProcess(), hSignal, hProc, &Info->hRemoteSignal, EVENT_ALL_ACCESS, FALSE, 0))
THROW(STATUS_INTERNAL_ERROR, L"Failed to duplicate remote event.");
// relocate remote information
RemoteInfo = (LPREMOTE_INFO)(RemoteInjectCode + CodeSize);
Diff = ((BYTE*)RemoteInfo - (BYTE*)Info);
Info->EasyHookEntry = (char*)(((BYTE*)Info->EasyHookEntry) + Diff);
Info->EasyHookPath = (wchar_t*)(((BYTE*)Info->EasyHookPath) + Diff);
Info->PATH = (wchar_t*)(((BYTE*)Info->PATH) + Diff);
Info->UserLibrary = (wchar_t*)(((BYTE*)Info->UserLibrary) + Diff);
if(Info->UserData != NULL)
Info->UserData = (BYTE*)(((BYTE*)Info->UserData) + Diff);
Info->RemoteEntryPoint = RemoteInjectCode;
if(!WriteProcessMemory(hProc, RemoteInfo, Info, RemoteInfoSize, &BytesWritten) || (BytesWritten != RemoteInfoSize))
THROW(STATUS_INTERNAL_ERROR, L"Unable to write into target process memory.");
if((InInjectionOptions & EASYHOOK_INJECT_STEALTH) != 0)
{
FORCE(RhCreateStealthRemoteThread(InTargetPID, (LPTHREAD_START_ROUTINE)RemoteInjectCode, RemoteInfo, &hRemoteThread));
}
else
{
if(!RTL_SUCCESS(NtCreateThreadEx(hProc, (LPTHREAD_START_ROUTINE)RemoteInjectCode, RemoteInfo, FALSE, &hRemoteThread)))
{
// create remote thread and wait for injection completion
if((hRemoteThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)RemoteInjectCode, RemoteInfo, 0, NULL)) == NULL)
THROW(STATUS_ACCESS_DENIED, L"Unable to create remote thread.");
}
}
/*
* The assembler codes are designed to let us derive extensive error information...
*/
Handles[1] = hSignal;
Handles[0] = hRemoteThread;
Code = WaitForMultipleObjects(2, Handles, FALSE, INFINITE);
if(Code == WAIT_OBJECT_0)
{
// parse error code
GetExitCodeThread(hRemoteThread, &Code);
SetLastError(Code & 0x0FFFFFFF);
switch(Code & 0xF0000000)
{
case 0x10000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to find internal entry point.");
case 0x20000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to make stack executable.");
case 0x30000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to release injected library.");
case 0x40000000: THROW(STATUS_INTERNAL_ERROR, L"Unable to find EasyHook library in target process context.");
case 0xF0000000: // error in C++ injection completion
{
switch(Code & 0xFF)
{
#ifdef _M_X64
case 20: THROW(STATUS_INVALID_PARAMETER_5, L"Unable to load the given 64-bit library into target process.");
case 21: THROW(STATUS_INVALID_PARAMETER_5, L"Unable to find the required native entry point in the given 64-bit library.");
case 12: THROW(STATUS_INVALID_PARAMETER_5, L"Unable to find the required managed entry point in the given 64-bit library.");
#else
case 20: THROW(STATUS_INVALID_PARAMETER_4, L"Unable to load the given 32-bit library into target process.");
case 21: THROW(STATUS_INVALID_PARAMETER_4, L"Unable to find the required native entry point in the given 32-bit library.");
case 12: THROW(STATUS_INVALID_PARAMETER_4, L"Unable to find the required managed entry point in the given 32-bit library.");
#endif
case 13: THROW(STATUS_DLL_INIT_FAILED, L"The user defined managed entry point failed in the target process. Make sure that EasyHook is registered in the GAC. Refer to event logs for more information.");
case 1: THROW(STATUS_INTERNAL_ERROR, L"Unable to allocate memory in target process.");
case 2: THROW(STATUS_INTERNAL_ERROR, L"Unable to adjust target's PATH variable.");
case 10: THROW(STATUS_INTERNAL_ERROR, L"Unable to load 'mscoree.dll' into target process.");
case 11: THROW(STATUS_INTERNAL_ERROR, L"Unable to bind NET Runtime to target process.");
case 22: THROW(STATUS_INTERNAL_ERROR, L"Unable to signal remote event.");
default: THROW(STATUS_INTERNAL_ERROR, L"Unknown error in injected C++ completion routine.");
}
}break;
case 0:
THROW(STATUS_INTERNAL_ERROR, L"C++ completion routine has returned success but didn't raise the remote event.");
default:
THROW(STATUS_INTERNAL_ERROR, L"Unknown error in injected assembler code.");
}
}
else if(Code != WAIT_OBJECT_0 + 1)
THROW(STATUS_INTERNAL_ERROR, L"Unable to wait for injection completion due to timeout. ");
RETURN;
THROW_OUTRO:
FINALLY_OUTRO:
{
// release resources
if(hProc != NULL)
CloseHandle(hProc);
if(Info != NULL)
RtlFreeMemory(Info);
if(hRemoteThread != NULL)
CloseHandle(hRemoteThread);
if(hSignal != NULL)
CloseHandle(hSignal);
return NtStatus;
}
}
/*/////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////// GetInjectionSize
///////////////////////////////////////////////////////////////////////////////////////
Dynamically retrieves the size of the trampoline method.
*/
static DWORD ___InjectionSize = 0;
#ifdef _M_X64
EXTERN_C void Injection_ASM_x64();
#else
EXTERN_C void __stdcall Injection_ASM_x86();
#endif
BYTE* GetInjectionPtr()
{
#ifdef _M_X64
BYTE* Ptr = (BYTE*)Injection_ASM_x64;
#else
BYTE* Ptr = (BYTE*)Injection_ASM_x86;
#endif
// bypass possible VS2008 debug jump table
if(*Ptr == 0xE9)
Ptr += *((int*)(Ptr + 1)) + 5;
return Ptr;
}
ULONG GetInjectionSize()
{
UCHAR* Ptr;
UCHAR* BasePtr;
ULONG Index;
ULONG Signature;
if(___InjectionSize != 0)
return ___InjectionSize;
// search for signature
BasePtr = Ptr = GetInjectionPtr();
for(Index = 0; Index < 2000 /* some always large enough value*/; Index++)
{
Signature = *((ULONG*)Ptr);
if(Signature == 0x12345678)
{
___InjectionSize = (ULONG)(Ptr - BasePtr);
return ___InjectionSize;
}
Ptr++;
}
ASSERT(FALSE,L"thread.c - ULONG GetInjectionSize()");
return 0;
}
EASYHOOK_NT_EXPORT TestFuncHooks(ULONG pId,
PCHAR module,
TEST_FUNC_HOOKS_OPTIONS options,
TEST_FUNC_HOOKS_RESULT** outResults,
int* resultCount)
{
/*
Description:
Tests whether it is possible to hook DLL exports found within the specified module.
Parameters:
- pId
The process Id to test.
- module
The name of the module to look for exports within.
- options
Optionally specifies whether to output the results to a text file, or
the name of a single export to test.
- outResults
Returns the array of results. This should be freed by a subsequent
call to ReleaseTestFuncHookResults.
- resultCount
The number of items added to outResults.
Returns:
NTSTATUS
*/
FILE *f = NULL;
HANDLE hProcess;
HMODULE hRemote = GetRemoteModuleHandle(pId, module);
IMAGE_DOS_HEADER DosHeader;
IMAGE_NT_HEADERS NtHeaders;
IMAGE_EXPORT_DIRECTORY EATDirectory;
DWORD* AddressOfFunctions;
DWORD* AddressOfNames;
WORD* AddressOfOrdinals;
unsigned int i;
DWORD_PTR dwExportBase;
DWORD_PTR dwExportSize;
DWORD_PTR dwAddressOfFunction;
DWORD_PTR dwAddressOfName;
char pszFunctionName[256] = { 0 };
char pszRedirectName[256] = { 0 };
char pszModuleName[256] = { 0 };
char pszFunctionRedi[256] = { 0 };
unsigned int a = 0;
int b = 0;
WORD OrdinalValue;
DWORD_PTR dwAddressOfRedirectedFunction;
DWORD_PTR dwAddressOfRedirectedName;
ULONG asmLength;
ULONG64 nextInstr;
CHAR buf[MAX_PATH];
CHAR asmBuf[MAX_PATH];
unsigned char *opcodes;
ULONG entryPointSize = 0;
UCHAR entryPoint[ 256 ] = { 0 };
DWORD_PTR pEntryPoint = 0;
LOCAL_HOOK_INFO* hookBuf = NULL;
ULONG relocBufSize = 0;
CHAR outputBuf[1024] = { 0 };
TEST_FUNC_HOOKS_RESULT* results = NULL;
TEST_FUNC_HOOKS_RESULT* result;
unsigned int count = 0;
char pszRedirectedFunctionName[ 256 ] = { 0 };
// Initialise results
*resultCount = 0;
*outResults = NULL;
// open target process
if((hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pId)) == NULL)
{
if(GetLastError() == ERROR_ACCESS_DENIED)
return STATUS_ACCESS_DENIED;
else
return STATUS_NOT_FOUND;
}
if(!hRemote)
return STATUS_NOT_FOUND;
// Load DOS PE header
if(!ReadProcessMemory(hProcess, (void*)hRemote, &DosHeader, sizeof(IMAGE_DOS_HEADER), NULL) || DosHeader.e_magic != IMAGE_DOS_SIGNATURE)
return STATUS_NOT_FOUND;
// Load NT PE headers
if(!ReadProcessMemory(hProcess, (void *)((DWORD_PTR)hRemote + DosHeader.e_lfanew), &NtHeaders, sizeof(IMAGE_NT_HEADERS), NULL) || NtHeaders.Signature != IMAGE_NT_SIGNATURE)
return STATUS_NOT_FOUND;
// Load image export directory
if(!GetRemoteModuleExportDirectory(hProcess, hRemote, &EATDirectory, DosHeader, NtHeaders))
return STATUS_NOT_FOUND;
// Allocate room for all the function information
AddressOfFunctions = (DWORD*)malloc(EATDirectory.NumberOfFunctions * sizeof(DWORD));
AddressOfNames = (DWORD*)malloc(EATDirectory.NumberOfNames * sizeof(DWORD));
AddressOfOrdinals = (WORD*)malloc(EATDirectory.NumberOfNames * sizeof(WORD));
// Read function address locations
if(!ReadProcessMemory(hProcess, (void*)((DWORD_PTR)hRemote + (DWORD_PTR)EATDirectory.AddressOfFunctions), AddressOfFunctions, EATDirectory.NumberOfFunctions * sizeof(DWORD), NULL)) {
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return STATUS_NOT_FOUND;
}
// Read function name locations
if(!ReadProcessMemory(hProcess, (void*)((DWORD_PTR)hRemote + (DWORD_PTR)EATDirectory.AddressOfNames), AddressOfNames, EATDirectory.NumberOfNames * sizeof(DWORD), NULL)) {
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return STATUS_NOT_FOUND;
}
// Read function name ordinal locations
if(!ReadProcessMemory(hProcess, (void*)((DWORD_PTR)hRemote + (DWORD_PTR)EATDirectory.AddressOfNameOrdinals), AddressOfOrdinals, EATDirectory.NumberOfNames * sizeof(WORD), NULL)) {
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return STATUS_NOT_FOUND;
}
dwExportBase = ((DWORD_PTR)hRemote + NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
dwExportSize = (dwExportBase + NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size);
// Determine result count
for(i = 0; i < EATDirectory.NumberOfNames; ++i) {
dwAddressOfFunction = (DWORD_PTR)hRemote + AddressOfFunctions[i];
dwAddressOfName = (DWORD_PTR)hRemote + AddressOfNames[i];
memset(&pszFunctionName, 0, 256);
if(!ReadProcessMemory(hProcess, (void*)dwAddressOfName, pszFunctionName, 256, NULL))
continue;
// Skip until we find the matching function name
if (options.FilterByName != NULL && strlen(options.FilterByName) > 0)
{
if (_stricmp(pszFunctionName, options.FilterByName) == 0)
count++;
}
else
{
count++;
}
}
// Allocate memory for the results
*resultCount = count;
results = (TEST_FUNC_HOOKS_RESULT *)CoTaskMemAlloc(count * sizeof(TEST_FUNC_HOOKS_RESULT));
*outResults = results;
if (results == NULL)
{
*outResults = NULL;
*resultCount = 0;
return STATUS_NO_MEMORY;
}
memset(results, 0, count * sizeof(TEST_FUNC_HOOKS_RESULT));
for (a = 0; a < count; a++) {
result = &results[a];
result->FnName = (LPSTR)CoTaskMemAlloc(MAX_PATH);
memset(result->FnName, 0, MAX_PATH);
result->ModuleRedirect = (LPSTR)CoTaskMemAlloc(MAX_PATH);
memset(result->ModuleRedirect, 0, MAX_PATH);
result->FnRedirect = (LPSTR)CoTaskMemAlloc(MAX_PATH);
memset(result->FnRedirect, 0, MAX_PATH);
result->EntryDisasm = (LPSTR)CoTaskMemAlloc(1024);
memset(result->EntryDisasm, 0, 1024);
result->RelocDisasm = (LPSTR)CoTaskMemAlloc(1024);
memset(result->RelocDisasm, 0, 1024);
result->Error = (LPSTR)CoTaskMemAlloc(1024);
memset(result->Error, 0, 1024);
}
count = a = b = 0;
// Check each name for a match
for(i = 0; i < EATDirectory.NumberOfNames; ++i) {
dwAddressOfFunction = (DWORD_PTR)hRemote + AddressOfFunctions[i];
dwAddressOfName = (DWORD_PTR)hRemote + AddressOfNames[i];
memset(&pszFunctionName, 0, 256);
if(!ReadProcessMemory(hProcess, (void*)dwAddressOfName, pszFunctionName, 256, NULL))
continue;
memset(&outputBuf, 0, 1024);
// Skip until we find the matching function name
if (options.FilterByName != NULL && strlen(options.FilterByName) > 0 && (_stricmp(pszFunctionName, options.FilterByName) != 0))
continue;
// Get next result obj
result = &results[count++];
strcpy_s(result->FnName, MAX_PATH, pszFunctionName);
// Check if address of function is found in another module
if(dwAddressOfFunction >= dwExportBase && dwAddressOfFunction <= dwExportSize) {
memset(&pszRedirectName, 0, 256);
if(!ReadProcessMemory(hProcess, (void*)dwAddressOfFunction, pszRedirectName, 256, NULL))
continue;
memset(&pszModuleName, 0, 256);
memset(&pszFunctionRedi, 0, 256);
a = 0;
for(; pszRedirectName[a] != '.'; a++)
pszModuleName[a] = pszRedirectName[a];
a++;
pszModuleName[a] = '\0';
b = 0;
for(; pszRedirectName[a] != '\0'; a++, b++)
pszFunctionRedi[b] = pszRedirectName[a];
b++;
pszFunctionRedi[b] = '\0';
strcat_s(pszModuleName, 256, ".dll");
strcpy_s(result->ModuleRedirect, MAX_PATH, pszModuleName);
dwAddressOfFunction = (DWORD_PTR)GetRemoteFuncAddress(pId, hProcess, pszModuleName, pszFunctionRedi);
if (dwAddressOfFunction == 0) {
strcpy_s(result->Error, 1024, "DLL redirect unreadable");
continue;
}
else {
strcpy_s(result->FnRedirect, MAX_PATH, pszFunctionRedi);
}
}
else {
OrdinalValue = AddressOfOrdinals[i];
if (OrdinalValue >= EATDirectory.NumberOfNames)
{
strcpy_s(result->Error, 1024, "Ordinal redirect out of range");
continue;
}
// If ordinal doesn't match index retrieve correct address
if(OrdinalValue != i) {
dwAddressOfRedirectedFunction = ((DWORD_PTR)hRemote + (DWORD_PTR)AddressOfFunctions[OrdinalValue]);
dwAddressOfRedirectedName = ((DWORD_PTR)hRemote + (DWORD_PTR)AddressOfNames[OrdinalValue]);
memset(&pszRedirectedFunctionName, 0, 256);
if(!ReadProcessMemory(hProcess, (void*)dwAddressOfRedirectedName, pszRedirectedFunctionName, 256, NULL))
{
strcpy_s(result->Error, 1024, "Ordinal redirect unreadable");
continue;
}
else
{
strcpy_s(result->FnRedirect, MAX_PATH, pszRedirectedFunctionName);
dwAddressOfFunction = dwAddressOfRedirectedFunction;
}
}
}
result->FnAddress = (void*)dwAddressOfFunction;
entryPointSize = 0;
a = 0;
// 1. Allocate memory and prepare the hook
if (!RTL_SUCCESS(LhAllocateHook((void*)dwAddressOfFunction, (void*)dwAddressOfFunction, NULL, &hookBuf, &relocBufSize)))
{
// Unable to allocate hook or unable to relocate instructions
BOOL usedDefault = FALSE;
WideCharToMultiByte(CP_ACP,
WC_COMPOSITECHECK | WC_DEFAULTCHAR,
RtlGetLastErrorString(),
lstrlenW(RtlGetLastErrorString()),
outputBuf,
1024,
"?",
&usedDefault);
sprintf_s(result->Error, 1024, "Unable to allocate hook: %s", outputBuf);
memset(&asmBuf, 0, MAX_PATH);
pEntryPoint = dwAddressOfFunction;
// Disassemble instructions
while ((a < 2 || (pEntryPoint - dwAddressOfFunction < 5)) && RTL_SUCCESS(LhDisassembleInstruction((void*)pEntryPoint, &asmLength, buf, MAX_PATH, &nextInstr)))
{
opcodes = (unsigned char *)pEntryPoint;
sprintf_s(asmBuf, 260, "\t");
for (b = 0; b < (int)(nextInstr - pEntryPoint); b++)
{
entryPoint[entryPointSize + b] = *opcodes;
sprintf_s(asmBuf + strlen(asmBuf), 260 - strlen(asmBuf), "%02X ", *opcodes);
opcodes++;
}
sprintf_s(result->EntryDisasm + strlen(result->EntryDisasm), 1024 - strlen(result->EntryDisasm), "%-35s%-30sIP:%x\n", asmBuf, buf, nextInstr);
a++;
pEntryPoint = (DWORD_PTR)nextInstr;
}
continue;
}
entryPointSize = hookBuf->EntrySize;
// 2. Disassemble entry point and relocated buffer
if (entryPointSize == 0)
strcpy_s(result->Error, 1024, "Entry point size is Zero");
else if (entryPointSize >= 20)
sprintf_s(result->Error, 1024, "Entry point is too large: %d", entryPointSize);
else
{
pEntryPoint = dwAddressOfFunction;
memset(asmBuf, 0, MAX_PATH);
while ((pEntryPoint - (DWORD_PTR)dwAddressOfFunction < entryPointSize) && RTL_SUCCESS(LhDisassembleInstruction((void*)pEntryPoint, &asmLength, buf, MAX_PATH, &nextInstr)))
{
opcodes = (PUCHAR)pEntryPoint;
sprintf_s(asmBuf, 260, "\t");
for (b = 0; b < (int)(nextInstr - pEntryPoint); b++)
{
sprintf_s(asmBuf + strlen(asmBuf), 260 - strlen(asmBuf), "%02X ", *opcodes);
opcodes++;
}
sprintf_s(result->EntryDisasm + strlen(result->EntryDisasm), 1024 - strlen(result->EntryDisasm), "%-35s%-30sIP:%x\n", asmBuf, buf, nextInstr);
pEntryPoint = (DWORD_PTR)nextInstr;
}
pEntryPoint = (DWORD_PTR)hookBuf->OldProc;
result->RelocAddress = (void*)pEntryPoint;
memset(asmBuf, 0, MAX_PATH);
while ((pEntryPoint - (DWORD_PTR)hookBuf->OldProc < relocBufSize) && RTL_SUCCESS(LhDisassembleInstruction((void*)pEntryPoint, &asmLength, buf, MAX_PATH, &nextInstr)))
{
opcodes = (PUCHAR)pEntryPoint;
sprintf_s(asmBuf, 260, "\t");
for (b = 0; b < (int)(nextInstr - pEntryPoint); b++)
{
sprintf_s(asmBuf + strlen(asmBuf), 260 - strlen(asmBuf), "%02X ", *opcodes);
opcodes++;
}
sprintf_s(result->RelocDisasm + strlen(result->RelocDisasm), 1024 - strlen(result->RelocDisasm), "%-35s%-30sIP:%x\n", asmBuf, buf, nextInstr);
pEntryPoint = (DWORD_PTR)nextInstr;
}
}
if (hookBuf != NULL)
LhFreeMemory(&hookBuf);
hookBuf = NULL;
}
// Write to file
if (options.Filename != NULL && strlen(options.Filename) > 0)
{
fopen_s(&f, options.Filename, "w");
if (f == NULL)
{
printf("Error opening file!\n");
return STATUS_NOT_FOUND;
}
for (i = 0; i < count; i++)
{
result = &results[i];
fprintf(f, "\nFunction: %s\n", result->FnName);
if (result->ModuleRedirect != NULL && strlen(result->ModuleRedirect))
fprintf(f, "\t(redirected to DLL: %s!%s)\n", result->ModuleRedirect, result->FnRedirect);
if (result->FnRedirect != NULL && strlen(result->FnRedirect))
fprintf(f, "\t(redirected to function: %s)\n", result->FnRedirect);
if (result->Error != NULL && strlen(result->Error) > 0)
{
fprintf(f, "ERROR: %s\n", result->Error);
if (result->EntryDisasm != NULL && strlen(result->EntryDisasm) > 0) {
fprintf(f, "%s", result->EntryDisasm);
}
}
else
{
fprintf(f, "Entry point:@ %p\n", result->FnAddress);
fprintf(f, "%s", result->EntryDisasm);
fprintf(f, "Relocated entry point:@ %p\n", result->RelocAddress);
fprintf(f, "%s", result->RelocDisasm);
}
}
fclose(f);
}
free(AddressOfFunctions);
free(AddressOfNames);
free(AddressOfOrdinals);
return 0;
}
EASYHOOK_NT_EXPORT ReleaseTestFuncHookResults(TEST_FUNC_HOOKS_RESULT* results, int count)
{
/*
Description:
Free the memory allocated for the results from a previous call to TestFuncHooks.
Parameters:
- results
Pointer to array of TEST_FUNC_HOOKS_RESULT to be freed.
- count
The number of elements within results.
Returns:
STATUS_SUCCESS
*/
int i = 0;
TEST_FUNC_HOOKS_RESULT* result;
for (i = 0; i < count; i++)
{
result = &results[i];
CoTaskMemFree(result->FnName);
CoTaskMemFree(result->ModuleRedirect);
CoTaskMemFree(result->FnRedirect);
CoTaskMemFree(result->EntryDisasm);
CoTaskMemFree(result->RelocDisasm);
CoTaskMemFree(result->Error);
}
CoTaskMemFree(results);
return STATUS_SUCCESS;
}
|
Minjung-Kwon/bangtal-game1_20180651-Minjung-Kwon
|
bangtal-0.3.1/_api/navtreeindex0.js
|
<reponame>Minjung-Kwon/bangtal-game1_20180651-Minjung-Kwon
var NAVTREEINDEX0 =
{
"_object_8h.html":[2,0,2],
"_object_8h.html#a58bcfbb10dc18b44fb41c19c4d850a59":[2,0,2,1],
"_object_8h_source.html":[2,0,2],
"_scene_8h.html":[2,0,3],
"_scene_8h.html#abb35c3c750f71093eb016b9d812066e3":[2,0,3,1],
"_scene_8h_source.html":[2,0,3],
"_sound_8h.html":[2,0,4],
"_sound_8h.html#a8d3868b6dff966e69e1bb0d6f1ee5e40":[2,0,4,1],
"_sound_8h_source.html":[2,0,4],
"_timer_8h.html":[2,0,5],
"_timer_8h.html#ad66ed2b2b36b443dfc7e8987cdfaf0d8":[2,0,5,1],
"_timer_8h_source.html":[2,0,5],
"annotated.html":[1,0],
"bangtal.html":[2,0,0],
"bangtal.html#a3532e67e12de8b00991f500e5af97bf3":[2,0,0,4],
"bangtal.html#a8eb706a2a0ed55817c95ef990086d99b":[2,0,0,6],
"bangtal.html#a97a439a0bf46cf493cfeaa9e03f7fd2b":[2,0,0,3],
"bangtal.html#a9c5b0d72a37bf89ce507dca1c8a049b6":[2,0,0,2],
"bangtal.html#aa883eb18b1eb1c035ffd844e6d321350":[2,0,0,1],
"bangtal.html#abbff3cdabb39f2b9ff70ceb7d84f48f7":[2,0,0,0],
"bangtal.html#ad3702480923fdd628e9d50332177bb12":[2,0,0,5],
"bangtal_8h.html":[2,0,1],
"bangtal_8h.html#a01cb8d8c3db5ca59dae883ca3890850c":[2,0,1,44],
"bangtal_8h.html#a06105107cc05b45e5ac8d866bcf44dbd":[2,0,1,56],
"bangtal_8h.html#a09691fd0cc143d929c4bd2b02fe356e6":[2,0,1,0],
"bangtal_8h.html#a0b0121f4e88b1abdb4ace47403db888e":[2,0,1,37],
"bangtal_8h.html#a0c607e8241b4d3293c69b813ad9771ad":[2,0,1,38],
"bangtal_8h.html#a0d0dd5b506199c1e936bc808ce84523f":[2,0,1,22],
"bangtal_8h.html#a0e7f05670de47ad24a63591b69bbe793":[2,0,1,20],
"bangtal_8h.html#a13a03dacd0c6849ae3f16d2e694fc280":[2,0,1,47],
"bangtal_8h.html#a175c217df5ff45b29cd59baf6a54b05a":[2,0,1,1],
"bangtal_8h.html#a1c79e880a8b61c16f168a235da3f6303":[2,0,1,7],
"bangtal_8h.html#a1f4f4b2856928a0bdf29609ee81f510d":[2,0,1,36],
"bangtal_8h.html#a24c292b7d1ab92d00f10d75c06db3f48":[2,0,1,43],
"bangtal_8h.html#a261ab22c4a42a9c6bd33ff6146f334dd":[2,0,1,64],
"bangtal_8h.html#a290f97199c0fec4dd692726a44d25d26":[2,0,1,26],
"bangtal_8h.html#a2c710d58c45f43834f4fc7f362f70266":[2,0,1,55],
"bangtal_8h.html#a3b2c14502ab6ce66c317b12308915234":[2,0,1,21],
"bangtal_8h.html#a4276516c60e90dcc61adda40ef8dd0e5":[2,0,1,8],
"bangtal_8h.html#a441bb74d3b955c123c47ce5b5cb59487":[2,0,1,58],
"bangtal_8h.html#a4426589c4897d66f1af5e856056a33a7":[2,0,1,57],
"bangtal_8h.html#a46a79edf8de643e2431a15f55a193ee3":[2,0,1,14],
"bangtal_8h.html#a47a52bcc4dd3b52f9a555e907e75901d":[2,0,1,51],
"bangtal_8h.html#a4c98327986f715b67c5c2552638f5df4":[2,0,1,59],
"bangtal_8h.html#a537d96924958a57df4f79361694478d1":[2,0,1,6],
"bangtal_8h.html#a53bae382c608281427e5c3cafd86b50c":[2,0,1,11],
"bangtal_8h.html#a548f9a09e6eee1f6c6963b658e05fc62":[2,0,1,30],
"bangtal_8h.html#a5677061589db77a1570d9a9f6a73988c":[2,0,1,60],
"bangtal_8h.html#a573a77599a5b26b39570733caa8ae11a":[2,0,1,63],
"bangtal_8h.html#a5c08c0353fd36f12c1b2ef409eb6db10":[2,0,1,10],
"bangtal_8h.html#a6226654844cd48ef408c1ca38d3c7fa6":[2,0,1,29],
"bangtal_8h.html#a65dc90fa00b1e4d61a3a521e48e5f7ed":[2,0,1,48],
"bangtal_8h.html#a67ee81aa37d3b4804e61b57c61b03213":[2,0,1,33],
"bangtal_8h.html#a6ba3385cbe76afca5db6ff18ae1bbd88":[2,0,1,2],
"bangtal_8h.html#a73a1311d525ad641bedca5d01369aa85":[2,0,1,13],
"bangtal_8h.html#a73c8b044ab55f62cc5791e46d61fe930":[2,0,1,31],
"bangtal_8h.html#a7a1514482b3f206232e2474a8e24b8d0":[2,0,1,61],
"bangtal_8h.html#a841791c660e8b5781662fbaf28620182":[2,0,1,35],
"bangtal_8h.html#a8796ad85a1ac86190555c7b4da112797":[2,0,1,24],
"bangtal_8h.html#a89e3ce10006c78eec7e29a9a1abd84ad":[2,0,1,50],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0d":[2,0,1,17],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da01371b7a167b1216dea813305ed91b2d":[2,0,1,17,145],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da02b736a597aa578d9d51060ad359b5a0":[2,0,1,17,96],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da02faa88a42bb6e5e1f2c62db6520e1b6":[2,0,1,17,28],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da045fb70fafbcaf257eff3209601153ff":[2,0,1,17,152],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da04a1e1cf83a4ca28bff7212d7315f65d":[2,0,1,17,101],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da0719994e9b3ee53325ba7a7f20fe6abe":[2,0,1,17,123],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da0731b2c143ec43d921e63fe492d83efe":[2,0,1,17,32],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da09051ab75e2658aa9c25e5e89402413f":[2,0,1,17,51],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da0caec4c31d6b0de6cf0ecd39bdab0e44":[2,0,1,17,94],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da0db640bbf596ede5c622a02b20e668fe":[2,0,1,17,65],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da0e6fd7d18e74add759b8c0fbdfa1e349":[2,0,1,17,126],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da10c145d098b9fc8874de1aca079426e0":[2,0,1,17,104],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da115e2285c81211c38c6a470c0440d9a1":[2,0,1,17,58],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da126c6be5f82a5d28208b095c9e45f4b0":[2,0,1,17,54],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da15a998ed5757a2246ff4e50704ae0620":[2,0,1,17,127],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da170e1044e77c06d3b75edfadd7aba6cb":[2,0,1,17,40],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da1a4614e7525e2668bfac739b8b289d11":[2,0,1,17,95],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da1dc3e405e3d1145e01c0689969596986":[2,0,1,17,163],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da20032871e1dec9155433946ecbfbcf61":[2,0,1,17,82],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da233a2efe8473ee0a18d23472ea860f44":[2,0,1,17,0],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da27e8a917c5d5e4c440c4dbc160e96f45":[2,0,1,17,129],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da2a753604f02698b1ecaf2c73f0de8e93":[2,0,1,17,70],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da2b60a0071352037dd82b34df771b5753":[2,0,1,17,118],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da2d527327b1e579cd00a92446d3ed5f2a":[2,0,1,17,64],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da2e12c9274ce8e2f09de6aff642692b45":[2,0,1,17,53],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da2e45b57904c831150fb002bd0b3c98d5":[2,0,1,17,52],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da2e617558c7d5743dd59fe487562e6405":[2,0,1,17,30],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da318bd217f20261f6eec3f4afbf965f9c":[2,0,1,17,86],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da31b0d3badb0ecf74610af9069b83c30d":[2,0,1,17,134],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da367119ff5a44495c678413bc66e481e5":[2,0,1,17,37],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da391eec91337354534bd3b97938d7e967":[2,0,1,17,105],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da39b26c85a5cec1375a8efffbb538b1a1":[2,0,1,17,168],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da3c84570b40081bb7df1b83d4a573dbb9":[2,0,1,17,165],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da3ce84bda089f9aedc81f56ae968837cc":[2,0,1,17,121],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da3e5c0293091cb077fcf3a86191b39cbf":[2,0,1,17,21],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da3fcaa1a9b24cbc65a498028c653046c0":[2,0,1,17,41],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da40a30d27cd7724dbd18532078cb6d22a":[2,0,1,17,153],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da4225fd198cc84a8439796181091d8e65":[2,0,1,17,169],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da4325fd3c81c734b069ecb0b9c46c45b2":[2,0,1,17,77],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da43f1c1b2bb217aa04013aa12fb9695a8":[2,0,1,17,81],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da45151127db0501a62165dd1f5db29cfa":[2,0,1,17,29],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da4ab970860f7ed213357d82e44cb3d904":[2,0,1,17,35],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da4b83fc98b75c2d07a8e40f12680a9f2c":[2,0,1,17,22],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da4dc1b3588491b9cb5dbb862fd2f95c47":[2,0,1,17,159],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da4dc23d4624db5f8f192c3cf4faae532b":[2,0,1,17,112],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da4e650667ebf23275e5bbd5275a1ff1fd":[2,0,1,17,99],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5117a084c57c2ab875e0bfe86c4a638d":[2,0,1,17,85],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da516e974c0778bebd810e596471f03da9":[2,0,1,17,78],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da52f17fd10c9aa000f4df7075d3ef3f45":[2,0,1,17,149],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da54b050eaddc06ffa5ae3d6f7f3fd565c":[2,0,1,17,111],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5663eaca1f79b78ebb57f62ff897b173":[2,0,1,17,20],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da56ee05d27060b80811d25784a5cce206":[2,0,1,17,87],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5707c0e8a97ceba2f2a589404e145e29":[2,0,1,17,122],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5906c66cc4ebc14298b7412d1c643c66":[2,0,1,17,147],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5953bf72e4e1cee4aa6cd7142762f077":[2,0,1,17,8],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5bd00d26b5f20de6bdee3e40b90ff15e":[2,0,1,17,69],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5d7c5526a3f71ac11cae0da58e0d59d2":[2,0,1,17,19],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5df3f2093c573770f204c77c0dd75a31":[2,0,1,17,128],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da5e16613aa5304abcfa26ba1698510cbb":[2,0,1,17,148],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da643f5288553b7f32aac8606880313ba6":[2,0,1,17,158],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da64419b7d6e7e0e2d8ebef88267abd103":[2,0,1,17,113],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da648e3c495192b878e7e3c402815236df":[2,0,1,17,34],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da64ff3fb5cb0d086ced450b32d71572de":[2,0,1,17,12],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da65c4491533472748cea743351f847427":[2,0,1,17,160],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da66a15ba2712e36034e81a03cef6e9d64":[2,0,1,17,44],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da66fb2eeb0cd140210a0279c50a00336b":[2,0,1,17,33],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da681e59004597d9cd5698900b2ded20b7":[2,0,1,17,164],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da6c577a7f141e65f0179d9a5f7448600b":[2,0,1,17,9],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da6e1d97546236cb1005aed72e5fb5312e":[2,0,1,17,46],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da7137cfb139c48876fdee5cd87d3f8dee":[2,0,1,17,11],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da71704324bc9bf0e734aa5056feb20edb":[2,0,1,17,135],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da73088fdfdc1444a9fc38467104911098":[2,0,1,17,50],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da74ef48dc6bacbbf660cf422396900a67":[2,0,1,17,92],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da751c9009d0068fa1bd940e88d6387ea2":[2,0,1,17,167],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da7a5c55ed490b51b0b92a22b7228adb0c":[2,0,1,17,138],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da7a6496e1a9d123a6d5edf2d3a8e9d97e":[2,0,1,17,119],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da7a974026bf12b68f251f02eacf1f6626":[2,0,1,17,154],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da8133433c20f714c5a0fd3d878fae6f8c":[2,0,1,17,144],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da8350baa5fded880538b27097753a9ce8":[2,0,1,17,80],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da845f27897cfde06707ca1ae312a2fc8e":[2,0,1,17,71],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da84985fa3c485aa49a3084c8c6e75eaf4":[2,0,1,17,72],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da85cee0ef43372a96e47be1b549e29f18":[2,0,1,17,76],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da85de2b5ecd586b46d5cea0015a15afac":[2,0,1,17,88],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da8686d639be3a19180a77295f78adf86c":[2,0,1,17,106],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da885f51d482d335f77ba1421700f48368":[2,0,1,17,141],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da89b46dbd5707c5009f5c5d5bdd989c37":[2,0,1,17,137],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da89b67010fd0b3a9260724a6698f9e2b6":[2,0,1,17,102],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da8ada72cfcaaf199335c60442dcce7533":[2,0,1,17,23],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da8dadaf1fb0ae25581ab9b3f5b3207c2a":[2,0,1,17,39],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da912b7b4b72393278cbe174fef3b40745":[2,0,1,17,143],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da931dbf1fe2254857607fa1d78dbdd370":[2,0,1,17,91],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da94d374d9eef93ce69924a0edaa193eeb":[2,0,1,17,156],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da954e8b825fe85b083fbc2b64edad125e":[2,0,1,17,84],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da98816004c1056a2dca9aa6bcbb3248c8":[2,0,1,17,61],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da99cc0a9d07d59e7ecae1a1b2fe7b19ee":[2,0,1,17,59],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da99f034940f93cf233eb2ac703eb272c5":[2,0,1,17,5],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da9a42aa7a370ebfa870483d16df848aff":[2,0,1,17,36],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da9aa5b26f3b76b219ab08fe0259df2483":[2,0,1,17,130],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da9c08f1ce677fc6d976c0c76889153865":[2,0,1,17,7],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da9eef027fe3d51dc434f92ce3a54fd361":[2,0,1,17,15],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0da9f68c9fb9ce74b843c0984e64e9715ce":[2,0,1,17,67],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa1635f4bc5fff540881ce6d11e64acd6":[2,0,1,17,60],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa1a07c7abf4e6b2b14e22cee97038048":[2,0,1,17,47],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa22887137c52454a79eaed2de448ce8e":[2,0,1,17,79],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa3f39e5eeb1c1413926327e5f216b1c6":[2,0,1,17,24],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa4746644fd4c86edcd92bad29da474d3":[2,0,1,17,68],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa4a7bcce597644128fbeb7cdebbeb666":[2,0,1,17,89],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa526cf087f5ab1a7827d014e3bd10725":[2,0,1,17,132],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa572c9c762af712cf8c3fdb0af4307fe":[2,0,1,17,90],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa63de1f14fa63c31187b30e706d4fcdc":[2,0,1,17,66],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa881bf8fa196edb5445a4a1c85ffc7de":[2,0,1,17,4],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daa9ad8aa86d5adff6573f3f7532f2f5d7":[2,0,1,17,114],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daacfdb1d8d98dae7c9f8889308af0d542":[2,0,1,17,49],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daae848ca92fa46bd4bf34b825f757a527":[2,0,1,17,150],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daaf5153d3debe4075f7e764e724e50dde":[2,0,1,17,103],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab0c514a9a11ed6a9b20285c1bf615cd6":[2,0,1,17,146],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab11e69d64d5a1beaee88911f5d2c208d":[2,0,1,17,161],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab129b7f084e2e697de71e420faeaa8f5":[2,0,1,17,1],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab32dcb700690b2d9085d588337b7db6e":[2,0,1,17,74],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab49ebfe5455ce3e4c140e0f8bb226d33":[2,0,1,17,42],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab4c44a229e114c7e2948c7da9291c1d4":[2,0,1,17,43],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab53b75d7f6543b71273a9e4f58d54046":[2,0,1,17,83],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab5926a5b1b103f3f0055a130fbe8f9dc":[2,0,1,17,75],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dab7478fc3124231eb77598b628218f6c4":[2,0,1,17,98],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dabc39a2087197bb10b7248798a6e26c6c":[2,0,1,17,115],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dabe8c42628328fa071e92e9d714c92e3a":[2,0,1,17,62],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac25f449d9d3de62aa6df6bbf87dc62e0":[2,0,1,17,125],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac332c432b41a7b3e844025b9e5c590f1":[2,0,1,17,140],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac3f5af37efb6eac8b98f6603c5dd1c09":[2,0,1,17,155],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac6128a3cff211d89b1ad604db5684817":[2,0,1,17,31],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac6880044bc1f9934695d4d76f49bf8df":[2,0,1,17,13],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac7adf60d3b33fb6a9f464bb6f15488dc":[2,0,1,17,56],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac7c1adf33ebb33f4526afa621b74ddec":[2,0,1,17,45],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac7dd492a38eeb2b9976ebdf9caf180dd":[2,0,1,17,100],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dac83fc33f6312976e3df2a5dbc783f395":[2,0,1,17,162],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daca5eda3cb7ef69f041e555aa4f0fe876":[2,0,1,17,142],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dacbc55a981874476c41bbc954dfe3ec6e":[2,0,1,17,6],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dacc9e8db3a9396951eb7e4bd4fd1f97a7":[2,0,1,17,107],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dace0807321fce985f7c8fa60fb773516e":[2,0,1,17,117],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad14e755841a017c7e2c527723baf89e4":[2,0,1,17,157],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad159038fd033617d917956ca8fb12106":[2,0,1,17,16],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad1d9fa6e1426863e2ba751727becd4f7":[2,0,1,17,10],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad2608b676b1eec5da9b7096673dbdf93":[2,0,1,17,97],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad37b53647f287184f8dc54fb01a9e209":[2,0,1,17,136],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad5092007c60718ba001b56c06967fa6a":[2,0,1,17,25],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad5759da7ea088431481dd7ef66e37d62":[2,0,1,17,38],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad77f79f22dbff84d60f17735b20d1314":[2,0,1,17,17],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dad9712b15487d63839b9b0fb627374940":[2,0,1,17,3],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dadca2921872d6bd9924236bcdc67bed5d":[2,0,1,17,93],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dadf3153982c2e083bc603f505d69e7956":[2,0,1,17,151],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dae0479465af58d1df9d9a6fd3e498556c":[2,0,1,17,124],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dae313ef83a95bb3bb1bc3a720ff4994d5":[2,0,1,17,2],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dae3b80acf91913b9106d9b7f0b6354e79":[2,0,1,17,116],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dae42244e3374d1b1d0e28bb493b45010d":[2,0,1,17,108],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dae9780b848469996b656d19e311fa74d9":[2,0,1,17,27],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dae9a8bd6bb2335bd6923de36bf63e2ebf":[2,0,1,17,55],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daebced6c075f5700a24c23ecb5eca67a5":[2,0,1,17,110],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daef6da5e49ba5b8d187d5d220ca255cee":[2,0,1,17,73],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf000747ecb851d24632cd00133ff40aa":[2,0,1,17,120],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf046ec3fc1dea1b753603429df53d7ed":[2,0,1,17,166],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf18702c2cfdc53d0f23aef91ff685693":[2,0,1,17,133],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf22f455c52a93c78475964ecfb381c36":[2,0,1,17,139],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf5a7a601b343674d48b0733a9ff83769":[2,0,1,17,14],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf7d6f0966efa449df044f85cc7e895fc":[2,0,1,17,109],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf8f85cf0aee71e1d718a0cee5a0902fe":[2,0,1,17,26],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf901e86c24f8627786390b9e1a158310":[2,0,1,17,63],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf935d4cff8b6287d579c6466d96f624f":[2,0,1,17,48],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daf9c0282c9e9ec14a6936deb101c156a0":[2,0,1,17,57],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0dafd1f9b73f395a59bf2b27644364fa1bf":[2,0,1,17,18],
"bangtal_8h.html#a94b769a2899b14202ace87b550519a0daffb9d8d5d9b1e0c548cb91307952398c":[2,0,1,17,131],
"bangtal_8h.html#a9612cf018b328681a31d38377b2cb3e5":[2,0,1,3],
"bangtal_8h.html#a9ac3c89e07a2d4d3f9164ac6f14ea8cc":[2,0,1,49],
"bangtal_8h.html#a9b828a65e91609a44cd7e2ec8456e3b0":[2,0,1,41],
"bangtal_8h.html#a9d43422939374d7485e494503ab30b8b":[2,0,1,5],
"bangtal_8h.html#aa2279197eb34108bfb774f9e8396fe84":[2,0,1,62],
"bangtal_8h.html#aa26bedd9fbedb7726135d8d870a80793":[2,0,1,42],
"bangtal_8h.html#aa3d14543ea624c7209e4cd2a9d33cb7a":[2,0,1,53],
"bangtal_8h.html#aa4ddd7b05cd1b310ac133e0e7913718a":[2,0,1,52],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74c":[2,0,1,15],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74ca108722944c10b9ec75c18060d79f8a66":[2,0,1,15,8],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74ca37635debd49bc7143d5456af661a1eef":[2,0,1,15,1],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74ca420b9f1a7ef47b8e42fec89602c2fe75":[2,0,1,15,4],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74ca4a54d3e5c083e029f3cfd2eb8eb53623":[2,0,1,15,7],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74ca581af84c394ee4ae28add4c14a370fc2":[2,0,1,15,0],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74ca585eb90a507232026b08781c3a1ada66":[2,0,1,15,3],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74cad54163a9ccb6b7d677f3e1c131b1964a":[2,0,1,15,5],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74cad593a1369528451ba26a3c147871cd60":[2,0,1,15,6],
"bangtal_8h.html#aaba367fb68e6d3c4e49765003d4ef74cafbc24d59203dc2ff41b62f20d59d05ad":[2,0,1,15,2],
"bangtal_8h.html#aae00ada60f57d513d22e752d0a3b78b5":[2,0,1,4]
};
|
aboss123/ParagonEngine
|
GameKit/SCRIPT/Lexer.java
|
<filename>GameKit/SCRIPT/Lexer.java
/*
* Copyright (c) 2019, <NAME>. All rights reserved.
*
* 1. Redistribution in source and in binary forms is NOT permitted
* in any way shape or form unless given permission by the license holder.
*
* 2. Any person(s) who have access to this code by the license holder need this
* license to be present in their code.
*
* 3. The name of the license holder may not 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 GameKit.SCRIPT;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Lexer {
private ArrayList<TokenData> tDatas;
private String tokens;
private Token lastToken;
private boolean toPush;
public Lexer(String tokens) {
this.tDatas = new ArrayList<>();
this.tokens = tokens;
// Basic categories
tDatas.add(new TokenData(Pattern.compile("^([a-zA-Z][a-zA-Z0-9]*)"), Type.IDENTIFIER));
tDatas.add(new TokenData(Pattern.compile("^((-)?[0-9]+)"), Type.INTEGER));
tDatas.add(new TokenData(Pattern.compile("^(\".*\")"), Type.STRING));
tDatas.add(new TokenData(Pattern.compile(";"), Type.NULL));
tDatas.add(new TokenData(Pattern.compile("@start"), Type.KEYWORD));
tDatas.add(new TokenData(Pattern.compile("@end"), Type.KEYWORD));
tDatas.add(new TokenData(Pattern.compile("=>"), Type.KEYWORD));
tDatas.add(new TokenData(Pattern.compile("//"), Type.COMMENT));
for (String t : new String[] { "=", "\\(", "\\)", "\\.", "\\,", "print"}) {
tDatas.add(new TokenData(Pattern.compile("^(" + t + ")"), Type.TOKEN));
}
}
public Token nextToken() throws ForbiddenCharacterException {
tokens = tokens.trim();
if(toPush) {
toPush = false;
return lastToken;
}
if(tokens.isEmpty()) {
return (lastToken = new Token("", Type.BLANK));
}
for (TokenData data : tDatas) {
Matcher matcher = data.getPattern().matcher(tokens);
if (matcher.find()) {
String token = matcher.group().trim();
tokens = matcher.replaceFirst("");
if(data.getType() == Type.STRING) {
return (lastToken = new Token(token.substring(1, token.length() - 1), Type.STRING));
}
else {
return (lastToken = new Token(token, data.getType()));
}
}
}
throw new ForbiddenCharacterException("The characters could not be parsed: " + "'" + tokens + "'");
}
public boolean hasTheNextToken() {
return !tokens.isEmpty();
}
public ArrayList<TokenData> getDatas() {
return tDatas;
}
}
|
ascii33/platform2
|
diagnostics/cros_healthd/system/context.h
|
// Copyright 2020 The Chromium OS 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 DIAGNOSTICS_CROS_HEALTHD_SYSTEM_CONTEXT_H_
#define DIAGNOSTICS_CROS_HEALTHD_SYSTEM_CONTEXT_H_
#include <memory>
#include <base/files/file_path.h>
#include <base/memory/scoped_refptr.h>
#include <base/time/tick_clock.h>
#include <brillo/dbus/dbus_connection.h>
#include <brillo/udev/udev_monitor.h>
#include <chromeos/chromeos-config/libcros_config/cros_config_interface.h>
#include <dbus/bus.h>
#include <dbus/object_proxy.h>
#include <mojo/public/cpp/bindings/remote.h>
#include <mojo/public/cpp/platform/platform_channel_endpoint.h>
#include "diagnostics/common/system/debugd_adapter.h"
#include "diagnostics/common/system/powerd_adapter.h"
#include "diagnostics/cros_healthd/executor/mojom/executor.mojom.h"
#include "diagnostics/cros_healthd/network/network_health_adapter.h"
#include "diagnostics/cros_healthd/network_diagnostics/network_diagnostics_adapter.h"
#include "diagnostics/cros_healthd/system/libdrm_util.h"
#include "diagnostics/cros_healthd/system/pci_util.h"
#include "diagnostics/cros_healthd/system/system_config_interface.h"
#include "diagnostics/cros_healthd/system/system_utilities.h"
#include "diagnostics/cros_healthd/utils/mojo_relay.h"
#include "diagnostics/dbus_bindings/bluetooth/dbus-proxies.h"
#include "diagnostics/mojom/external/cros_healthd_internal.mojom.h"
namespace brillo {
class Udev;
};
namespace org {
namespace chromium {
class AttestationProxyInterface;
class debugdProxyInterface;
class TpmManagerProxyInterface;
namespace cras {
class ControlProxyInterface;
} // namespace cras
} // namespace chromium
namespace freedesktop {
class fwupdProxyInterface;
} // namespace freedesktop
} // namespace org
namespace diagnostics {
namespace mojom = chromeos::cros_healthd::mojom;
// A context class for holding the helper objects used in cros_healthd, which
// simplifies the passing of the helper objects to other objects. For instance,
// instead of passing various helper objects to an object via its constructor,
// the context object is passed.
class Context {
public:
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
virtual ~Context();
static std::unique_ptr<Context> Create(
mojo::PlatformChannelEndpoint executor_endpoint,
std::unique_ptr<brillo::UdevMonitor>&& udev_monitor);
// Creates an object for accessing |LibdrmUtil| interface.
virtual std::unique_ptr<LibdrmUtil> CreateLibdrmUtil();
// Creates an object for accessing |PciUtil| interface.
virtual std::unique_ptr<PciUtil> CreatePciUtil();
// Accessors for the various helper objects:
// Use the object returned by attestation_proxy() to get the attestation
// information from attestation service.
org::chromium::AttestationProxyInterface* attestation_proxy() const;
// Use the object returned by bluetooth_proxy() to subscribe to notifications
// for D-Bus objects representing Bluetooth adapters and devices.
org::bluezProxy* bluetooth_proxy() const;
// Use the object returned by cros_config() to query the device's
// configuration file.
brillo::CrosConfigInterface* cros_config() const;
// Use the object returned by debugd_proxy() to make calls to debugd. Example:
// cros_healthd calls out to debugd when it needs to collect smart battery
// metrics like manufacture_date_smart and temperature_smart.
org::chromium::debugdProxyInterface* debugd_proxy() const;
// Use the object returned by cras_proxy() to communicate with cras daemon
// through dbus.
org::chromium::cras::ControlProxyInterface* cras_proxy() const;
// Use the object returned by fwupd_proxy() to communicate with fwupd through
// dbus.
org::freedesktop::fwupdProxyInterface* fwupd_proxy() const;
// Use the object returned by debugd_adapter() to make calls to debugd.
// Example: cros_healthd calls out to debugd with async callbacks when it
// needs to trigger nvme self-test or collect data like progress info.
DebugdAdapter* debugd_adapter() const;
// Use the object returned by network_health_adapter() to make requests to the
// NetworkHealthService. Example: cros_healthd calls out to the
// NetworkHealthService to get network telemetry data.
NetworkHealthAdapter* network_health_adapter() const;
// Use the object returned by network_diagnostics_adapter() to make calls to
// the NetworkDiagnosticsRoutines interface implemented by the browser.
// Example: cros_healthd calls out to the NetworkDiagnosticsRoutines interface
// with async callbacks when it needs to run network diagnostics.
NetworkDiagnosticsAdapter* network_diagnostics_adapter() const;
// Use the object returned by powerd_adapter() to subscribe to notifications
// from powerd.
PowerdAdapter* powerd_adapter() const;
// Use the object returned by root_dir() to determine the root directory of
// the system.
const base::FilePath& root_dir() const;
// Use the object returned by udev_monitor() to receive udev events.
const std::unique_ptr<brillo::UdevMonitor>& udev_monitor() const;
// Use the object returned by system_config() to determine which conditional
// features a device supports.
SystemConfigInterface* system_config() const;
// Use the interface returned by executor() to make calls to the root-level
// executor.
virtual mojom::Executor* executor();
// Use the object returned by system_utils() to access system utilities.
SystemUtilities* system_utils() const;
// Use the object returned by tick_clock() to track the passage of time.
base::TickClock* tick_clock() const;
// Return current time.
virtual const base::Time time() const;
// Use the object returned by tpm_manager_proxy() to get the tpm information
// from tpm manager.
org::chromium::TpmManagerProxyInterface* tpm_manager_proxy() const;
// Use the object returned by udev() to access udev related interfaces.
brillo::Udev* udev() const;
// Returns internal service factory relay object to access chrome resources.
MojoRelay<chromeos::cros_healthd::internal::mojom::
CrosHealthdInternalServiceFactory>*
internal_service_factory_relay();
private:
Context();
private:
// Allows MockContext to override the default helper objects.
friend class MockContext;
// This should be the only connection to D-Bus. Use |connection_| to get the
// |dbus_bus|.
brillo::DBusConnection connection_;
// Used by this object to initialize the SystemConfig. Used for reading
// cros_config properties to determine device feature support.
std::unique_ptr<brillo::CrosConfigInterface> cros_config_;
// Used to watch udev events.
std::unique_ptr<brillo::UdevMonitor> udev_monitor_;
// Members accessed via the accessor functions defined above.
std::unique_ptr<org::chromium::AttestationProxyInterface> attestation_proxy_;
std::unique_ptr<org::bluezProxy> bluetooth_proxy_;
std::unique_ptr<org::chromium::cras::ControlProxyInterface> cras_proxy_;
std::unique_ptr<org::chromium::debugdProxyInterface> debugd_proxy_;
std::unique_ptr<DebugdAdapter> debugd_adapter_;
std::unique_ptr<org::freedesktop::fwupdProxyInterface> fwupd_proxy_;
std::unique_ptr<MojoRelay<chromeos::cros_healthd::internal::mojom::
CrosHealthdInternalServiceFactory>>
internal_service_factory_relay_;
std::unique_ptr<NetworkHealthAdapter> network_health_adapter_;
std::unique_ptr<NetworkDiagnosticsAdapter> network_diagnostics_adapter_;
std::unique_ptr<PowerdAdapter> powerd_adapter_;
std::unique_ptr<SystemConfigInterface> system_config_;
mojo::Remote<mojom::Executor> executor_;
std::unique_ptr<SystemUtilities> system_utils_;
std::unique_ptr<base::TickClock> tick_clock_;
std::unique_ptr<org::chromium::TpmManagerProxyInterface> tpm_manager_proxy_;
std::unique_ptr<brillo::Udev> udev_;
base::FilePath root_dir_;
};
} // namespace diagnostics
#endif // DIAGNOSTICS_CROS_HEALTHD_SYSTEM_CONTEXT_H_
|
janbodnar/Python-Course
|
stdlib/zipfile/read_zip.py
|
<reponame>janbodnar/Python-Course<filename>stdlib/zipfile/read_zip.py
#!/usr/bin/python
import zipfile
with zipfile.ZipFile('subor.zip', 'r') as zf:
print(zf.namelist())
|
shuqiyige/excellent-course
|
src/main/java/io/shuqi/graduation/domain/bo/SiteInfoCount.java
|
package io.shuqi.graduation.domain.bo;
/**
* 站点信息统计
* @author shuqi
* @date 2015年4月28日
* @version since 1.0
*/
public class SiteInfoCount {
private Long count;
private String name;
private String ico_class = "icon-database";
public static String ico_news = "icon-file-text";
public static String ico_user = "icon-user";
public static String ico_file = "icon-file";
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIco_class() {
return ico_class;
}
public void setIco_class(String ico_class) {
this.ico_class = ico_class;
}
public SiteInfoCount(String name,Long count, String ico_class) {
super();
this.count = count;
this.name = name;
this.ico_class = ico_class;
}
public SiteInfoCount(Long count, String name) {
super();
this.count = count;
this.name = name;
}
public SiteInfoCount() {
super();
}
}
|
mcodegeeks/OpenKODE-Framework
|
01_Develop/libXMCocos2D/Source/kazmath/aabb.cpp
|
/* -----------------------------------------------------------------------------------
*
* File aabb.cpp
* Ported By <NAME>
* Contact <EMAIL>
*
* -----------------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft
* Copyright (c) 2008 <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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ----------------------------------------------------------------------------------- */
#include "Precompiled.h"
#include "kazmath/aabb.h"
/**
* Returns KM_TRUE if point is in the specified AABB, returns
* KM_FALSE otherwise.
*/
const int kmAABBContainsPoint(const kmVec3* pPoint, const kmAABB* pBox)
{
if(pPoint->x >= pBox->min.x && pPoint->x <= pBox->max.x &&
pPoint->y >= pBox->min.y && pPoint->y <= pBox->max.y &&
pPoint->z >= pBox->min.z && pPoint->z <= pBox->max.z) {
return KM_TRUE;
}
return KM_FALSE;
}
/**
* Assigns pIn to pOut, returns pOut.
*/
kmAABB* const kmAABBAssign(kmAABB* pOut, const kmAABB* pIn)
{
kmVec3Assign(&pOut->min, &pIn->min);
kmVec3Assign(&pOut->max, &pIn->max);
return pOut;
}
/**
* Scales pIn by s, stores the resulting AABB in pOut. Returns pOut
*/
kmAABB* const kmAABBScale(kmAABB* pOut, const kmAABB* pIn, kmScalar s)
{
kdAssert(0 && "Not implemented");
return 0;
}
|
rodolfoplondero/py_dss_interface
|
src/py_dss_interface/models/CktElement/CktElementF.py
|
<filename>src/py_dss_interface/models/CktElement/CktElementF.py
# -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
import ctypes
from py_dss_interface.models.Base import Base
class CktElementF(Base):
def cktelement_read_norm_amps(self) -> float:
"""Deliver the normal ampere rating for the active PDElement."""
return float(self.dss_obj.CktElementF(ctypes.c_int32(0), ctypes.c_double(0)))
def cktelement_write_norm_amps(self, argument: float) -> float:
"""Allows to fix the normal ampere rating for the active PDElement."""
return float(self.dss_obj.CktElementF(ctypes.c_int32(1), ctypes.c_double(argument)))
def cktelement_read_emerg_amps(self) -> float:
"""Deliver the Emergency ampere rating for the active PDElement."""
return float(self.dss_obj.CktElementF(ctypes.c_int32(2), ctypes.c_double(0)))
def cktelement_write_emerg_amps(self, argument: float) -> float:
"""Allows to fix the Emergency ampere rating for the active PDElement. The new value must be defined in the
variable ?Argument?."""
return float(self.dss_obj.CktElementF(ctypes.c_int32(3), ctypes.c_double(argument)))
# TODO include in test
def cktelement_variable_i(self, argument: float) -> float:
"""Delivers get the value of a variable by index for the active PCElement."""
return float(self.dss_obj.CktElementF(ctypes.c_int32(4), ctypes.c_double(argument)))
|
mohabg/VoogaSalad
|
src/events/Executable.java
|
package events;
import behaviors.IActions;
import level.ILevelProperties;
import level.LevelProperties;
/**
*
* @author gauravkumar
*
*/
public interface Executable {
public void execute(IActions action, ILevelProperties levProps);
public void stop(IActions actions, ILevelProperties levProps);
}
|
AndrewPetrie1/register-trainee-teachers
|
spec/components/page_title/view_spec.rb
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe PageTitle::View do
before do
allow(I18n).to receive(:t).with("service_name").and_return("Cool Service")
end
it "constructs a page title with empty params" do
component = PageTitle::View.new
page_title = component.build_page_title
expect(page_title).to eq("Cool Service - GOV.UK")
end
context "title as text" do
it "constructs a page title using the provided value" do
component = PageTitle::View.new(text: "Some title")
page_title = component.build_page_title
expect(page_title).to eq("Some title - Cool Service - GOV.UK")
end
context "when has_errors is true" do
it "constructs a page title value with an error" do
component = PageTitle::View.new(text: "Some title", has_errors: true)
page_title = component.build_page_title
expect(page_title).to eq("Error: Some title - Cool Service - GOV.UK")
end
end
end
context "title as i18n key" do
before do
allow(I18n).to receive(:t).with("components.page_titles.trainee.new").and_return("New Trainee")
end
it "constructs a page title value" do
component = PageTitle::View.new(i18n_key: "trainee.new")
page_title = component.build_page_title
expect(page_title).to eq("New Trainee - Cool Service - GOV.UK")
end
context "when has_errors is true" do
it "constructs a page title value with an error" do
component = PageTitle::View.new(i18n_key: "trainee.new", has_errors: true)
page_title = component.build_page_title
expect(page_title).to eq("Error: New Trainee - Cool Service - GOV.UK")
end
end
end
end
|
soracom-labs/openapi-client-go
|
openapi/api/model_generate_user_auth_key_response.go
|
<reponame>soracom-labs/openapi-client-go
/*
SORACOM API
SORACOM API v1
API version: VERSION_PLACEHOLDER
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package api
import (
"encoding/json"
)
// GenerateUserAuthKeyResponse struct for GenerateUserAuthKeyResponse
type GenerateUserAuthKeyResponse struct {
AuthKey *string `json:"authKey,omitempty"`
AuthKeyId *string `json:"authKeyId,omitempty"`
}
// NewGenerateUserAuthKeyResponse instantiates a new GenerateUserAuthKeyResponse object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewGenerateUserAuthKeyResponse() *GenerateUserAuthKeyResponse {
this := GenerateUserAuthKeyResponse{}
return &this
}
// NewGenerateUserAuthKeyResponseWithDefaults instantiates a new GenerateUserAuthKeyResponse object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewGenerateUserAuthKeyResponseWithDefaults() *GenerateUserAuthKeyResponse {
this := GenerateUserAuthKeyResponse{}
return &this
}
// GetAuthKey returns the AuthKey field value if set, zero value otherwise.
func (o *GenerateUserAuthKeyResponse) GetAuthKey() string {
if o == nil || o.AuthKey == nil {
var ret string
return ret
}
return *o.AuthKey
}
// GetAuthKeyOk returns a tuple with the AuthKey field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *GenerateUserAuthKeyResponse) GetAuthKeyOk() (*string, bool) {
if o == nil || o.AuthKey == nil {
return nil, false
}
return o.AuthKey, true
}
// HasAuthKey returns a boolean if a field has been set.
func (o *GenerateUserAuthKeyResponse) HasAuthKey() bool {
if o != nil && o.AuthKey != nil {
return true
}
return false
}
// SetAuthKey gets a reference to the given string and assigns it to the AuthKey field.
func (o *GenerateUserAuthKeyResponse) SetAuthKey(v string) {
o.AuthKey = &v
}
// GetAuthKeyId returns the AuthKeyId field value if set, zero value otherwise.
func (o *GenerateUserAuthKeyResponse) GetAuthKeyId() string {
if o == nil || o.AuthKeyId == nil {
var ret string
return ret
}
return *o.AuthKeyId
}
// GetAuthKeyIdOk returns a tuple with the AuthKeyId field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *GenerateUserAuthKeyResponse) GetAuthKeyIdOk() (*string, bool) {
if o == nil || o.AuthKeyId == nil {
return nil, false
}
return o.AuthKeyId, true
}
// HasAuthKeyId returns a boolean if a field has been set.
func (o *GenerateUserAuthKeyResponse) HasAuthKeyId() bool {
if o != nil && o.AuthKeyId != nil {
return true
}
return false
}
// SetAuthKeyId gets a reference to the given string and assigns it to the AuthKeyId field.
func (o *GenerateUserAuthKeyResponse) SetAuthKeyId(v string) {
o.AuthKeyId = &v
}
func (o GenerateUserAuthKeyResponse) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.AuthKey != nil {
toSerialize["authKey"] = o.AuthKey
}
if o.AuthKeyId != nil {
toSerialize["authKeyId"] = o.AuthKeyId
}
return json.Marshal(toSerialize)
}
type NullableGenerateUserAuthKeyResponse struct {
value *GenerateUserAuthKeyResponse
isSet bool
}
func (v NullableGenerateUserAuthKeyResponse) Get() *GenerateUserAuthKeyResponse {
return v.value
}
func (v *NullableGenerateUserAuthKeyResponse) Set(val *GenerateUserAuthKeyResponse) {
v.value = val
v.isSet = true
}
func (v NullableGenerateUserAuthKeyResponse) IsSet() bool {
return v.isSet
}
func (v *NullableGenerateUserAuthKeyResponse) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableGenerateUserAuthKeyResponse(val *GenerateUserAuthKeyResponse) *NullableGenerateUserAuthKeyResponse {
return &NullableGenerateUserAuthKeyResponse{value: val, isSet: true}
}
func (v NullableGenerateUserAuthKeyResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableGenerateUserAuthKeyResponse) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
|
dme26/intravisor
|
runtime/musl-lkl/lkl/drivers/gpu/drm/vmwgfx/vmwgfx_ioctl.c
|
<reponame>dme26/intravisor
/**************************************************************************
*
* Copyright © 2009-2015 VMware, Inc., Palo Alto, CA., USA
* All Rights Reserved.
*
* 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, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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 "vmwgfx_drv.h"
#include <drm/vmwgfx_drm.h>
#include "vmwgfx_kms.h"
#include "device_include/svga3d_caps.h"
struct svga_3d_compat_cap {
SVGA3dCapsRecordHeader header;
SVGA3dCapPair pairs[SVGA3D_DEVCAP_MAX];
};
int vmw_getparam_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct drm_vmw_getparam_arg *param =
(struct drm_vmw_getparam_arg *)data;
struct vmw_fpriv *vmw_fp = vmw_fpriv(file_priv);
switch (param->param) {
case DRM_VMW_PARAM_NUM_STREAMS:
param->value = vmw_overlay_num_overlays(dev_priv);
break;
case DRM_VMW_PARAM_NUM_FREE_STREAMS:
param->value = vmw_overlay_num_free_overlays(dev_priv);
break;
case DRM_VMW_PARAM_3D:
param->value = vmw_fifo_have_3d(dev_priv) ? 1 : 0;
break;
case DRM_VMW_PARAM_HW_CAPS:
param->value = dev_priv->capabilities;
break;
case DRM_VMW_PARAM_FIFO_CAPS:
param->value = dev_priv->fifo.capabilities;
break;
case DRM_VMW_PARAM_MAX_FB_SIZE:
param->value = dev_priv->prim_bb_mem;
break;
case DRM_VMW_PARAM_FIFO_HW_VERSION:
{
u32 *fifo_mem = dev_priv->mmio_virt;
const struct vmw_fifo_state *fifo = &dev_priv->fifo;
if ((dev_priv->capabilities & SVGA_CAP_GBOBJECTS)) {
param->value = SVGA3D_HWVERSION_WS8_B1;
break;
}
param->value =
vmw_mmio_read(fifo_mem +
((fifo->capabilities &
SVGA_FIFO_CAP_3D_HWVERSION_REVISED) ?
SVGA_FIFO_3D_HWVERSION_REVISED :
SVGA_FIFO_3D_HWVERSION));
break;
}
case DRM_VMW_PARAM_MAX_SURF_MEMORY:
if ((dev_priv->capabilities & SVGA_CAP_GBOBJECTS) &&
!vmw_fp->gb_aware)
param->value = dev_priv->max_mob_pages * PAGE_SIZE / 2;
else
param->value = dev_priv->memory_size;
break;
case DRM_VMW_PARAM_3D_CAPS_SIZE:
if ((dev_priv->capabilities & SVGA_CAP_GBOBJECTS) &&
vmw_fp->gb_aware)
param->value = SVGA3D_DEVCAP_MAX * sizeof(uint32_t);
else if (dev_priv->capabilities & SVGA_CAP_GBOBJECTS)
param->value = sizeof(struct svga_3d_compat_cap) +
sizeof(uint32_t);
else
param->value = (SVGA_FIFO_3D_CAPS_LAST -
SVGA_FIFO_3D_CAPS + 1) *
sizeof(uint32_t);
break;
case DRM_VMW_PARAM_MAX_MOB_MEMORY:
vmw_fp->gb_aware = true;
param->value = dev_priv->max_mob_pages * PAGE_SIZE;
break;
case DRM_VMW_PARAM_MAX_MOB_SIZE:
param->value = dev_priv->max_mob_size;
break;
case DRM_VMW_PARAM_SCREEN_TARGET:
param->value =
(dev_priv->active_display_unit == vmw_du_screen_target);
break;
case DRM_VMW_PARAM_DX:
param->value = dev_priv->has_dx;
break;
default:
return -EINVAL;
}
return 0;
}
static u32 vmw_mask_multisample(unsigned int cap, u32 fmt_value)
{
/* If the header is updated, update the format test as well! */
BUILD_BUG_ON(SVGA3D_DEVCAP_DXFMT_BC5_UNORM + 1 != SVGA3D_DEVCAP_MAX);
if (cap >= SVGA3D_DEVCAP_DXFMT_X8R8G8B8 &&
cap <= SVGA3D_DEVCAP_DXFMT_BC5_UNORM)
fmt_value &= ~(SVGADX_DXFMT_MULTISAMPLE_2 |
SVGADX_DXFMT_MULTISAMPLE_4 |
SVGADX_DXFMT_MULTISAMPLE_8);
else if (cap == SVGA3D_DEVCAP_MULTISAMPLE_MASKABLESAMPLES)
return 0;
return fmt_value;
}
static int vmw_fill_compat_cap(struct vmw_private *dev_priv, void *bounce,
size_t size)
{
struct svga_3d_compat_cap *compat_cap =
(struct svga_3d_compat_cap *) bounce;
unsigned int i;
size_t pair_offset = offsetof(struct svga_3d_compat_cap, pairs);
unsigned int max_size;
if (size < pair_offset)
return -EINVAL;
max_size = (size - pair_offset) / sizeof(SVGA3dCapPair);
if (max_size > SVGA3D_DEVCAP_MAX)
max_size = SVGA3D_DEVCAP_MAX;
compat_cap->header.length =
(pair_offset + max_size * sizeof(SVGA3dCapPair)) / sizeof(u32);
compat_cap->header.type = SVGA3DCAPS_RECORD_DEVCAPS;
spin_lock(&dev_priv->cap_lock);
for (i = 0; i < max_size; ++i) {
vmw_write(dev_priv, SVGA_REG_DEV_CAP, i);
compat_cap->pairs[i][0] = i;
compat_cap->pairs[i][1] = vmw_mask_multisample
(i, vmw_read(dev_priv, SVGA_REG_DEV_CAP));
}
spin_unlock(&dev_priv->cap_lock);
return 0;
}
int vmw_get_cap_3d_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vmw_get_3d_cap_arg *arg =
(struct drm_vmw_get_3d_cap_arg *) data;
struct vmw_private *dev_priv = vmw_priv(dev);
uint32_t size;
u32 *fifo_mem;
void __user *buffer = (void __user *)((unsigned long)(arg->buffer));
void *bounce;
int ret;
bool gb_objects = !!(dev_priv->capabilities & SVGA_CAP_GBOBJECTS);
struct vmw_fpriv *vmw_fp = vmw_fpriv(file_priv);
if (unlikely(arg->pad64 != 0 || arg->max_size == 0)) {
DRM_ERROR("Illegal GET_3D_CAP argument.\n");
return -EINVAL;
}
if (gb_objects && vmw_fp->gb_aware)
size = SVGA3D_DEVCAP_MAX * sizeof(uint32_t);
else if (gb_objects)
size = sizeof(struct svga_3d_compat_cap) + sizeof(uint32_t);
else
size = (SVGA_FIFO_3D_CAPS_LAST - SVGA_FIFO_3D_CAPS + 1) *
sizeof(uint32_t);
if (arg->max_size < size)
size = arg->max_size;
bounce = vzalloc(size);
if (unlikely(bounce == NULL)) {
DRM_ERROR("Failed to allocate bounce buffer for 3D caps.\n");
return -ENOMEM;
}
if (gb_objects && vmw_fp->gb_aware) {
int i, num;
uint32_t *bounce32 = (uint32_t *) bounce;
num = size / sizeof(uint32_t);
if (num > SVGA3D_DEVCAP_MAX)
num = SVGA3D_DEVCAP_MAX;
spin_lock(&dev_priv->cap_lock);
for (i = 0; i < num; ++i) {
vmw_write(dev_priv, SVGA_REG_DEV_CAP, i);
*bounce32++ = vmw_mask_multisample
(i, vmw_read(dev_priv, SVGA_REG_DEV_CAP));
}
spin_unlock(&dev_priv->cap_lock);
} else if (gb_objects) {
ret = vmw_fill_compat_cap(dev_priv, bounce, size);
if (unlikely(ret != 0))
goto out_err;
} else {
fifo_mem = dev_priv->mmio_virt;
memcpy(bounce, &fifo_mem[SVGA_FIFO_3D_CAPS], size);
}
ret = copy_to_user(buffer, bounce, size);
if (ret)
ret = -EFAULT;
out_err:
vfree(bounce);
if (unlikely(ret != 0))
DRM_ERROR("Failed to report 3D caps info.\n");
return ret;
}
int vmw_present_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
struct vmw_private *dev_priv = vmw_priv(dev);
struct drm_vmw_present_arg *arg =
(struct drm_vmw_present_arg *)data;
struct vmw_surface *surface;
struct drm_vmw_rect __user *clips_ptr;
struct drm_vmw_rect *clips = NULL;
struct drm_framebuffer *fb;
struct vmw_framebuffer *vfb;
struct vmw_resource *res;
uint32_t num_clips;
int ret;
num_clips = arg->num_clips;
clips_ptr = (struct drm_vmw_rect __user *)(unsigned long)arg->clips_ptr;
if (unlikely(num_clips == 0))
return 0;
if (clips_ptr == NULL) {
DRM_ERROR("Variable clips_ptr must be specified.\n");
ret = -EINVAL;
goto out_clips;
}
clips = kcalloc(num_clips, sizeof(*clips), GFP_KERNEL);
if (clips == NULL) {
DRM_ERROR("Failed to allocate clip rect list.\n");
ret = -ENOMEM;
goto out_clips;
}
ret = copy_from_user(clips, clips_ptr, num_clips * sizeof(*clips));
if (ret) {
DRM_ERROR("Failed to copy clip rects from userspace.\n");
ret = -EFAULT;
goto out_no_copy;
}
drm_modeset_lock_all(dev);
fb = drm_framebuffer_lookup(dev, file_priv, arg->fb_id);
if (!fb) {
DRM_ERROR("Invalid framebuffer id.\n");
ret = -ENOENT;
goto out_no_fb;
}
vfb = vmw_framebuffer_to_vfb(fb);
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
goto out_no_ttm_lock;
ret = vmw_user_resource_lookup_handle(dev_priv, tfile, arg->sid,
user_surface_converter,
&res);
if (ret)
goto out_no_surface;
surface = vmw_res_to_srf(res);
ret = vmw_kms_present(dev_priv, file_priv,
vfb, surface, arg->sid,
arg->dest_x, arg->dest_y,
clips, num_clips);
/* vmw_user_surface_lookup takes one ref so does new_fb */
vmw_surface_unreference(&surface);
out_no_surface:
ttm_read_unlock(&dev_priv->reservation_sem);
out_no_ttm_lock:
drm_framebuffer_put(fb);
out_no_fb:
drm_modeset_unlock_all(dev);
out_no_copy:
kfree(clips);
out_clips:
return ret;
}
int vmw_present_readback_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct drm_vmw_present_readback_arg *arg =
(struct drm_vmw_present_readback_arg *)data;
struct drm_vmw_fence_rep __user *user_fence_rep =
(struct drm_vmw_fence_rep __user *)
(unsigned long)arg->fence_rep;
struct drm_vmw_rect __user *clips_ptr;
struct drm_vmw_rect *clips = NULL;
struct drm_framebuffer *fb;
struct vmw_framebuffer *vfb;
uint32_t num_clips;
int ret;
num_clips = arg->num_clips;
clips_ptr = (struct drm_vmw_rect __user *)(unsigned long)arg->clips_ptr;
if (unlikely(num_clips == 0))
return 0;
if (clips_ptr == NULL) {
DRM_ERROR("Argument clips_ptr must be specified.\n");
ret = -EINVAL;
goto out_clips;
}
clips = kcalloc(num_clips, sizeof(*clips), GFP_KERNEL);
if (clips == NULL) {
DRM_ERROR("Failed to allocate clip rect list.\n");
ret = -ENOMEM;
goto out_clips;
}
ret = copy_from_user(clips, clips_ptr, num_clips * sizeof(*clips));
if (ret) {
DRM_ERROR("Failed to copy clip rects from userspace.\n");
ret = -EFAULT;
goto out_no_copy;
}
drm_modeset_lock_all(dev);
fb = drm_framebuffer_lookup(dev, file_priv, arg->fb_id);
if (!fb) {
DRM_ERROR("Invalid framebuffer id.\n");
ret = -ENOENT;
goto out_no_fb;
}
vfb = vmw_framebuffer_to_vfb(fb);
if (!vfb->dmabuf) {
DRM_ERROR("Framebuffer not dmabuf backed.\n");
ret = -EINVAL;
goto out_no_ttm_lock;
}
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
goto out_no_ttm_lock;
ret = vmw_kms_readback(dev_priv, file_priv,
vfb, user_fence_rep,
clips, num_clips);
ttm_read_unlock(&dev_priv->reservation_sem);
out_no_ttm_lock:
drm_framebuffer_put(fb);
out_no_fb:
drm_modeset_unlock_all(dev);
out_no_copy:
kfree(clips);
out_clips:
return ret;
}
/**
* vmw_fops_poll - wrapper around the drm_poll function
*
* @filp: See the linux fops poll documentation.
* @wait: See the linux fops poll documentation.
*
* Wrapper around the drm_poll function that makes sure the device is
* processing the fifo if drm_poll decides to wait.
*/
__poll_t vmw_fops_poll(struct file *filp, struct poll_table_struct *wait)
{
struct drm_file *file_priv = filp->private_data;
struct vmw_private *dev_priv =
vmw_priv(file_priv->minor->dev);
vmw_fifo_ping_host(dev_priv, SVGA_SYNC_GENERIC);
return drm_poll(filp, wait);
}
/**
* vmw_fops_read - wrapper around the drm_read function
*
* @filp: See the linux fops read documentation.
* @buffer: See the linux fops read documentation.
* @count: See the linux fops read documentation.
* offset: See the linux fops read documentation.
*
* Wrapper around the drm_read function that makes sure the device is
* processing the fifo if drm_read decides to wait.
*/
ssize_t vmw_fops_read(struct file *filp, char __user *buffer,
size_t count, loff_t *offset)
{
struct drm_file *file_priv = filp->private_data;
struct vmw_private *dev_priv =
vmw_priv(file_priv->minor->dev);
vmw_fifo_ping_host(dev_priv, SVGA_SYNC_GENERIC);
return drm_read(filp, buffer, count, offset);
}
|
Portfoligno/Eyrie
|
nio/src/main/scala/eyrie/nio/instances/FilePathSuffix.scala
|
package eyrie.nio.instances
import eyrie.nio.FilePath
import eyrie.ops.Suffix
private[instances]
trait SuffixInstances[A[_], B[_]] {
implicit def eyrieNioSuffixInstance[C]: Suffix[A[C], B[C]] =
FilePathSuffix.asInstanceOf[Suffix[A[C], B[C]]]
}
private
object FilePathSuffix extends Suffix[FilePath[Any], FilePath[Any]] {
import eyrie.nio.syntax.javaMirror._
override
def endsWith: (FilePath[Any], FilePath[Any]) => Boolean =
(x, y) => x.asJava.endsWith(y.asJava)
}
|
nagineni/chromium-crosswalk
|
chrome/app/policy/cloud_policy_codegen.gyp
|
<gh_stars>1-10
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
'policy_out_dir': '<(SHARED_INTERMEDIATE_DIR)/policy',
'protoc_out_dir': '<(SHARED_INTERMEDIATE_DIR)/protoc_out',
'generate_policy_source_script_path':
'<(DEPTH)/chrome/tools/build/generate_policy_source.py',
'policy_constant_header_path':
'<(policy_out_dir)/policy/policy_constants.h',
'policy_constant_source_path':
'<(policy_out_dir)/policy/policy_constants.cc',
'protobuf_decoder_path':
'<(policy_out_dir)/policy/cloud_policy_generated.cc',
# This is the "full" protobuf, which defines one protobuf message per
# policy. It is also the format currently used by the server.
'chrome_settings_proto_path':
'<(policy_out_dir)/policy/chrome_settings.proto',
# This protobuf is equivalent to chrome_settings.proto but shares messages
# for policies of the same type, so that less classes have to be generated
# and compiled.
'cloud_policy_proto_path': '<(policy_out_dir)/policy/cloud_policy.proto',
},
'targets': [
{
'target_name': 'cloud_policy_code_generate',
'type': 'none',
'actions': [
{
'inputs': [
'policy_templates.json',
'<(generate_policy_source_script_path)',
],
'outputs': [
'<(policy_constant_header_path)',
'<(policy_constant_source_path)',
'<(protobuf_decoder_path)',
'<(chrome_settings_proto_path)',
'<(cloud_policy_proto_path)',
],
'action_name': 'generate_policy_source',
'action': [
'python',
'<@(generate_policy_source_script_path)',
'--policy-constants-header=<(policy_constant_header_path)',
'--policy-constants-source=<(policy_constant_source_path)',
'--chrome-settings-protobuf=<(chrome_settings_proto_path)',
'--cloud-policy-protobuf=<(cloud_policy_proto_path)',
'--cloud-policy-decoder=<(protobuf_decoder_path)',
'<(OS)',
'<(chromeos)',
'policy_templates.json',
],
'message': 'Generating policy source',
},
],
'direct_dependent_settings': {
'include_dirs': [
'<(policy_out_dir)',
'<(protoc_out_dir)',
],
},
},
{
'target_name': 'cloud_policy_proto_generated_compile',
'type': 'static_library',
'sources': [
'<(cloud_policy_proto_path)',
],
'variables': {
'proto_in_dir': '<(policy_out_dir)/policy',
'proto_out_dir': 'policy/proto',
},
'dependencies': [
'cloud_policy_code_generate',
],
'includes': [ '../../../build/protoc.gypi' ],
# TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
'msvs_disabled_warnings': [4267, ],
},
{
# This target builds the "full" protobuf, used for tests only.
'target_name': 'chrome_settings_proto_generated_compile',
'type': 'static_library',
'sources': [
'<(chrome_settings_proto_path)',
],
'variables': {
'proto_in_dir': '<(policy_out_dir)/policy',
'proto_out_dir': 'policy/proto',
},
'dependencies': [
'cloud_policy_code_generate',
'cloud_policy_proto_generated_compile',
],
'includes': [ '../../../build/protoc.gypi' ],
},
{
'target_name': 'policy',
'type': 'static_library',
'hard_dependency': 1,
'direct_dependent_settings': {
'include_dirs': [
'<(policy_out_dir)',
'<(protoc_out_dir)',
],
},
'sources': [
'<(policy_constant_header_path)',
'<(policy_constant_source_path)',
'<(protobuf_decoder_path)',
],
'include_dirs': [
'<(DEPTH)',
],
'dependencies': [
'cloud_policy_code_generate',
'cloud_policy_proto_generated_compile',
'<(DEPTH)/base/base.gyp:base',
'<(DEPTH)/third_party/protobuf/protobuf.gyp:protobuf_lite',
],
},
{
'target_name': 'policy_test_support',
'type': 'none',
'hard_dependency': 1,
'direct_dependent_settings': {
'include_dirs': [
'<(policy_out_dir)',
'<(protoc_out_dir)',
],
},
'dependencies': [
'policy',
'chrome_settings_proto_generated_compile',
],
},
],
'conditions': [
['OS=="win" and target_arch=="ia32"', {
'targets': [
{
'target_name': 'policy_win64',
'type': 'static_library',
'hard_dependency': 1,
'sources': [
'<(policy_constant_header_path)',
'<(policy_constant_source_path)',
],
'include_dirs': [
'<(DEPTH)',
],
'direct_dependent_settings': {
'include_dirs': [
'<(policy_out_dir)'
],
},
'dependencies': [
'cloud_policy_code_generate',
],
'configurations': {
'Common_Base': {
'msvs_target_platform': 'x64',
},
},
},
],
}],
], # 'conditions'
}
|
FarazPatankar/posthog
|
ee/clickhouse/middleware.py
|
<reponame>FarazPatankar/posthog
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.urls.base import resolve
from loginas.utils import is_impersonated_session
from posthog.ee import is_clickhouse_enabled
class CHQueries(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request: HttpRequest):
""" Install monkey-patch on demand.
If monkey-patch has not been run in for this process (assuming multiple preforked processes),
then do it now.
"""
from ee.clickhouse import client
route = resolve(request.path)
client._request_information = {
"save": (
is_clickhouse_enabled()
and request.user.pk
and (request.user.is_staff or is_impersonated_session(request) or settings.DEBUG)
),
"user_id": request.user.pk,
"kind": "request",
"id": f"{route.route} ({route.func.__name__})",
}
response: HttpResponse = self.get_response(request)
client._request_information = None
return response
|
myckwilliam/JS-Exercises
|
exercises/fruitCase.js
|
// 14)Crie uma estrutura condicional switch que receba uma string com o nome de uma fruta e que possua três casos: Caso maçã, retorne no console: “Não vendemos esta fruta aqui”. Caso kiwi, retorne: “Estamos com escassez de kiwis”. Caso melancia, retorne: “Aqui está, são 3 reais o quilo”. Teste com estas três opções .Crie também um default, que retornará uma mensagem de erro no console.
// Let's go!
const fruitCase = fruit => {
switch (fruit.toLowerCase()) {
case 'maçã':
return 'Não vendemos esta fruta aqui.'
case 'kiwi':
return 'Estamos com escassez de kiwi.'
case 'melancia':
return 'Aqui está, são 3 reais o quilo.'
default:
return 'Erro: Termo inválido'
}
}
const fruit = 'Kiwi';
console.log(fruitCase(fruit));
|
balabit-deps/balabit-os-6-fop
|
src/java/org/apache/fop/pdf/PDFFontType3.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.
*/
/* $Id: PDFFontType3.java 679326 2008-07-24 09:35:34Z vhennebert $ */
package org.apache.fop.pdf;
import org.apache.fop.fonts.FontType;
/**
* Class representing a Type3 font.
* <p>
* <b>CAUTION: this is not yet fully implemented!!!!!!!</b>
* the /CharProcs is still missing its <code>toPDF()</code> method.
* <p>
* Type3 fonts are specified on page 206 and onwards of the PDF 1.3 spec.
*/
public class PDFFontType3 extends PDFFontNonBase14 {
/**
* Create the /Font object
*
* @param fontname the internal name for the font
* @param basefont the base font name
* @param encoding the character encoding schema used by the font
*/
public PDFFontType3(String fontname,
String basefont,
Object encoding) {
super(fontname, FontType.TYPE3, basefont, encoding);
}
/**
* Create the /Font object
*
* @param fontname the internal name for the font
* @param basefont the base font name
* @param encoding the character encoding schema used by the font
* @param fontBBox the font's bounding box
* @param fontMatrix the font's transformation matrix
* @param charProcs the glyphs' definitions
*/
public PDFFontType3(String fontname,
String basefont,
Object encoding,
PDFRectangle fontBBox, PDFArray fontMatrix,
PDFCharProcs charProcs) {
/* generic creation of PDF object */
super(fontname, FontType.TYPE3, basefont, encoding /* , mapping */);
setFontBBox(fontBBox);
setFontMatrix(fontMatrix);
setCharProcs(charProcs);
}
/**
* Set the font's bounding box
*
* @param bbox bounding box for the font
*/
public void setFontBBox(PDFRectangle bbox) {
put("FontBBox", bbox);
}
/**
* Set the font's transformation matrix
*
* @param matrix the transformation matrix for the font
*/
public void setFontMatrix(PDFArray matrix) {
put("FontMatrix", matrix);
}
/**
* Set the glyphs' definitions.
* <p>
* The /CharProcs object needs to be registered in the document's resources.
*
* @param chars the glyphs' dictionary
*/
public void setCharProcs(PDFCharProcs chars) {
put("CharProcs", chars);
}
}
|
asm128/gpk_samples
|
test_gpk_db/main.cpp
|
#include "gpk_datatype.h"
#include "gpk_array.h"
#include "gpk_label.h"
struct STable {
::gpk::label Name ;
::gpk::array_obj<::gpk::label> RowNames ;
::gpk::array_pod<::gpk::DATA_TYPE> RowTypes ;
};
#pragma pack(push, 1)
enum GPK_SQL_OP
{ GPK_SQL_OP_NOP = 0
, GPK_SQL_OP_SELECT
, GPK_SQL_OP_DELETE
, GPK_SQL_OP_INSERT
, GPK_SQL_OP_UPDATE
, GPK_SQL_OP_WHERE
, GPK_SQL_OP_JOIN
, GPK_SQL_OP_FROM
, GPK_SQL_OP_VALUES
, GPK_SQL_OP_INNER
, GPK_SQL_OP_OUTER
, GPK_SQL_OP_RIGHT
, GPK_SQL_OP_LEFT
, GPK_SQL_OP_COUNT
};
struct SSQLOperator {
::GPK_SQL_OP OpCode;
::gpk::view_const_string Name;
};
static const ::SSQLOperator table_operators [] =
{ {GPK_SQL_OP_NOP , "NOP" }
, {GPK_SQL_OP_SELECT , "SELECT" }
, {GPK_SQL_OP_DELETE , "DELETE" }
, {GPK_SQL_OP_INSERT , "INSERT" }
, {GPK_SQL_OP_UPDATE , "UPDATE" }
, {GPK_SQL_OP_WHERE , "WHERE" }
, {GPK_SQL_OP_JOIN , "JOIN" }
, {GPK_SQL_OP_FROM , "FROM" }
, {GPK_SQL_OP_VALUES , "VALUES" }
, {GPK_SQL_OP_INNER , "INNER" }
, {GPK_SQL_OP_OUTER , "OUTER" }
, {GPK_SQL_OP_RIGHT , "RIGHT" }
, {GPK_SQL_OP_LEFT , "LEFT" }
, {GPK_SQL_OP_COUNT , "COUNT" }
};
struct SUserAccess {
int32_t User;
::gpk::array_obj<int32_t> Tables;
::GPK_SQL_OP AccessOperation;
};
struct SUser {
::gpk::array_obj<int32_t> Tables;
};
#pragma pack(pop)
struct SDatabase {
::gpk::array_obj<::STable> Tables ;
::gpk::array_obj<::SUser> Users ;
::gpk::array_obj<::SUserAccess> UserAccess ;
};
int main () {
::gpk::view_const_string query = "SELECT * from databases;";
::SDatabase database = {};
return 0;
}
|
sameer79/streamline
|
streams/sdk/src/main/java/com/hortonworks/streamline/streams/notification/NotifierConfig.java
|
<reponame>sameer79/streamline
/**
* Copyright 2017 Hortonworks.
*
* 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.hortonworks.streamline.streams.notification;
import java.util.Map;
import java.util.Properties;
/**
* A set of notifier specific properties and
* field values (defaults plus user configured) for
* the notifier fields.
*/
public interface NotifierConfig {
/**
* The class name of this notifier
*/
String getClassName();
/**
* The path of the jar containing the notifier.
*/
String getJarPath();
/**
* The notifier specific properties.
* E.g. SMTP server, port for email notifier.
*
* @return the notifier properties
*/
Properties getProperties();
/**
* The defaults for some of the notifier fields.
*
* @return a map of defaults for some of the notifier fields.
*/
Map<String, String> getDefaultFieldValues();
}
|
elshize/irkit
|
tests/test_heap.cpp
|
<filename>tests/test_heap.cpp
#include <algorithm>
#include <experimental/filesystem>
#include <iostream>
#include <vector>
#include <unordered_map>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#define private public
#include "heap.hpp"
namespace {
using namespace irk;
class HeapTest : public ::testing::Test {
protected:
Heap<int, char> heap;
};
TEST_F(HeapTest, empty)
{
EXPECT_EQ(heap.size(), 0);
EXPECT_EQ(heap.empty(), true);
}
TEST_F(HeapTest, from_nonempty)
{
EXPECT_EQ(heap.size(), 0);
heap.push(5, 'a');
EXPECT_EQ(heap.size(), 1);
EXPECT_EQ(heap.top(), make_entry(5, 'a'));
heap.push(3, 'b');
EXPECT_EQ(heap.size(), 2);
EXPECT_EQ(heap.top(), make_entry(3, 'b'));
heap.push(1, 'c');
EXPECT_EQ(heap.size(), 3);
EXPECT_EQ(heap.top(), make_entry(1, 'c'));
heap.push(2, 'd');
EXPECT_EQ(heap.size(), 4);
EXPECT_EQ(heap.top(), make_entry(1, 'c'));
auto entry = heap.pop_push(6, 'e');
EXPECT_EQ(heap.size(), 4);
EXPECT_EQ(entry, make_entry(1, 'c'));
EXPECT_EQ(heap.top(), make_entry(2, 'd'));
std::vector<Entry<int, char>> v(heap.begin(), heap.end());
std::sort(v.begin(), v.end());
std::vector<Entry<int, char>> expv = {
{2, 'd'}, {3, 'b'}, {5, 'a'}, {6, 'e'}};
EXPECT_THAT(v, ::testing::ElementsAreArray(expv));
heap.push_with_limit(1, 'f', 4);
EXPECT_EQ(heap.size(), 4);
EXPECT_EQ(heap.top(), make_entry(2, 'd'));
heap.push_with_limit(2, 'g', 4);
EXPECT_EQ(heap.size(), 4);
EXPECT_EQ(heap.top(), make_entry(2, 'g'));
EXPECT_EQ(heap.pop(), make_entry(2, 'g'));
EXPECT_EQ(heap.pop(), make_entry(3, 'b'));
EXPECT_EQ(heap.pop(), make_entry(5, 'a'));
EXPECT_EQ(heap.pop(), make_entry(6, 'e'));
}
TEST(MappingTest, regular_operations)
{
using HeapType = Heap<int, char, std::less<int>, std::unordered_map<int, int>>;
HeapType heap;
EXPECT_EQ(heap.mapping.size(), 0);
heap.push(5, 'a');
heap.push(3, 'b');
heap.push(1, 'c');
heap.push(2, 'd');
heap.pop_push(6, 'e');
std::vector<Entry<int, char>> v(heap.begin(), heap.end());
std::sort(v.begin(), v.end());
std::vector<Entry<int, char>> expv = {
{2, 'd'}, {3, 'b'}, {5, 'a'}, {6, 'e'}};
EXPECT_THAT(v, ::testing::ElementsAreArray(expv));
}
TEST(MappingTest, remove)
{
using HeapType = Heap<int, char, std::less<int>, std::unordered_map<char, int>>;
HeapType heap;
EXPECT_EQ(heap.mapping.size(), 0);
heap.push(1, 'a');
heap.push(4, 'b');
heap.push(2, 'c');
heap.push(5, 'd');
heap.push(6, 'e');
heap.push(7, 'f');
heap.push(3, 'g');
{
std::vector<Entry<int, char>> v(heap.begin(), heap.end());
std::vector<Entry<int, char>> expv = {{1, 'a'},
{4, 'b'},
{2, 'c'},
{5, 'd'},
{6, 'e'},
{7, 'f'},
{3, 'g'}};
EXPECT_THAT(v, ::testing::ElementsAreArray(expv));
}
heap.remove_value('e');
{
std::vector<Entry<int, char>> v(heap.begin(), heap.end());
std::vector<Entry<int, char>> expv = {{1, 'a'},
{3, 'g'},
{2, 'c'},
{5, 'd'},
{4, 'b'},
{7, 'f'}
};
EXPECT_THAT(v, ::testing::ElementsAreArray(expv));
}
ASSERT_THROW(heap.pop_push(2, 'c'), std::invalid_argument);
heap.push(8, 'c');
{
std::vector<Entry<int, char>> v(heap.begin(), heap.end());
std::vector<Entry<int, char>> expv = {{1, 'a'},
{3, 'g'},
{7, 'f'},
{5, 'd'},
{4, 'b'},
{8, 'c'}
};
EXPECT_THAT(v, ::testing::ElementsAreArray(expv));
}
}
} // namespace
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
mikeeq/devilution-nx
|
Source/monstdat.h
|
<filename>Source/monstdat.h
//HEADER_GOES_HERE
#ifndef __MONSTDAT_H__
#define __MONSTDAT_H__
extern MonsterData monsterdata[112];
extern char MonstConvTbl[128];
extern unsigned char MonstAvailTbl[112];
extern UniqMonstStruct UniqMonst[98];
#endif /* __MONSTDAT_H__ */
|
Marquez607/Wireless-Perf-Sim
|
ns-3-dev/build/ns3/network-module.h
|
<reponame>Marquez607/Wireless-Perf-Sim
#ifdef NS3_MODULE_COMPILATION
# error "Do not include ns3 module aggregator headers from other modules; these are meant only for end user scripts."
#endif
#ifndef NS3_MODULE_NETWORK
// Module headers:
#include "address-utils.h"
#include "address.h"
#include "application-container.h"
#include "application.h"
#include "bit-deserializer.h"
#include "bit-serializer.h"
#include "buffer.h"
#include "byte-tag-list.h"
#include "channel-list.h"
#include "channel.h"
#include "chunk.h"
#include "crc32.h"
#include "data-rate.h"
#include "delay-jitter-estimation.h"
#include "drop-tail-queue.h"
#include "dynamic-queue-limits.h"
#include "error-channel.h"
#include "error-model.h"
#include "ethernet-header.h"
#include "ethernet-trailer.h"
#include "flow-id-tag.h"
#include "generic-phy.h"
#include "header.h"
#include "inet-socket-address.h"
#include "inet6-socket-address.h"
#include "ipv4-address.h"
#include "ipv6-address.h"
#include "llc-snap-header.h"
#include "lollipop-counter.h"
#include "mac16-address.h"
#include "mac48-address.h"
#include "mac64-address.h"
#include "mac8-address.h"
#include "net-device-container.h"
#include "net-device-queue-interface.h"
#include "net-device.h"
#include "nix-vector.h"
#include "node-container.h"
#include "node-list.h"
#include "node.h"
#include "output-stream-wrapper.h"
#include "packet-burst.h"
#include "packet-data-calculators.h"
#include "packet-metadata.h"
#include "packet-probe.h"
#include "packet-socket-address.h"
#include "packet-socket-client.h"
#include "packet-socket-factory.h"
#include "packet-socket-helper.h"
#include "packet-socket-server.h"
#include "packet-socket.h"
#include "packet-tag-list.h"
#include "packet.h"
#include "packetbb.h"
#include "pcap-file-wrapper.h"
#include "pcap-file.h"
#include "pcap-test.h"
#include "queue-item.h"
#include "queue-limits.h"
#include "queue-size.h"
#include "queue.h"
#include "radiotap-header.h"
#include "sequence-number.h"
#include "simple-channel.h"
#include "simple-net-device-helper.h"
#include "simple-net-device.h"
#include "sll-header.h"
#include "socket-factory.h"
#include "socket.h"
#include "tag-buffer.h"
#include "tag.h"
#include "trace-helper.h"
#include "trailer.h"
#endif
|
PacificBiosciences/pbbam
|
tools/pbindexdump/src/PbIndexDumpWorkflow.cpp
|
#include "PbIndexDumpWorkflow.h"
#include <cassert>
#include <cstdlib>
#include "CppFormatter.h"
#include "JsonFormatter.h"
#include "PbIndexDumpSettings.h"
namespace PacBio {
namespace PbIndexDump {
int Workflow::Runner(const CLI_v2::Results& args)
{
const Settings settings{args};
if (settings.Format == "json") {
JsonFormatter::Run(settings);
} else {
assert(settings.Format == "cpp");
CppFormatter::Run(settings);
}
return EXIT_SUCCESS;
}
} // namespace PbIndexDump
} // namespace PacBio
|
Sachindadhalli/Frontend_code
|
src/containers/EmployerInbox/component/SharedAppiledUserProfile/SharedAppiledUserProfile.js
|
//library dependency
import React, {Component} from 'react';
import Button from '@material-ui/core/Button';
import {withStyles} from '@material-ui/core/styles';
//custom components
import PersonalDetails from '../AppliedUserProfile/Components/PersonalDetails';
import DesiredCareerProfile from '../AppliedUserProfile/Components/DesiredCareerProfile';
import MyAchievements from '../AppliedUserProfile/Components/MyAchievements';
import Projects from '../AppliedUserProfile/Components/Projects';
import AppliedUserProfileSideCard from '../AppliedUserProfile/Components/AppliedUserProfileSideCard';
import BasicDetails from '../AppliedUserProfile/Components/BasicDetails/BasicDetails';
import ResumeHeadline from '../AppliedUserProfile/Components/ResumeHeadline/ResumeHeadline';
import Technologies from '../AppliedUserProfile/Components/Technologies/Technologies';
import Employment from '../AppliedUserProfile/Components/Employment/Employment';
import TechnologiesWorkedOn from '../AppliedUserProfile/Components/TechnologiesWorkedOn';
import ProfileSummary from '../AppliedUserProfile/Components/ProfileSummary';
import Education from '../AppliedUserProfile/Components/Education';
import PageNotFound from '../../../../components/PageNotFound';
import LoadingIcon from "../../../../components/LoadingIcon/LoadingIcon";
//styles
import './styles.scss';
//utilities
import {apiCall, handleLocalStorage} from "../../../../Utilities";
import {EMPLOYER_SHARED_USER_PROFILE} from "../../../../../config/constants";
/**
* this function used to check object is empty or not
* @param obj
* @returns {boolean}
*/
function isEmpty(obj) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) return false;
}
return true;
}
/**
* this function used to check array of object is empty or not
* @param obj
* @returns {boolean}
*/
function isEmptyObjOfArray(obj) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) if (obj[prop].length > 0) return false;
}
return true;
}
/**
* this function used to get query parameters from url
* @param variable
* @returns {*}
*/
function getQueryVariable(variable) {
let query = window.location.search.substring(1);
let vars = query.split("&");
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split("=");
if (pair[0] === variable) {
return pair[1];
}
}
return (false);
}
// used to overrides material ui components styles
const styles = () => ({
button: {
color: " #e73a9e",
border: "1px solid #e73a9e",
marginRight: "12px",
"&:hover": {background: "#e73a9e17 !important"}
},
input: {display: 'none'},
});
class SharedAppliedUserProfile extends Component {
constructor(props) {
super(props);
this.state = {
loading: false, sorry: false, result: {
is_fresher: false, application_status: "", training_internship:
{internship: [], training: []}, achievements: {
online_profile: [], work_sample: [], publication: [],
presentation: [], patent: [], certification: [], reward: []
}, desired_profile: {}, personal_details: {},
projects: [], basic_profile: {}, resume_headline: "", profile_summary: "", skills: [], employment_details: [],
education: [], technologies: [], resumes: {}, snippet: {},
}
};
}
componentWillMount() {
/**
* here we are calling user profile details api function to get details
*/
this.callEmployerUserProfileApi();
}
/**
* this function call user profile api and stores in state variable
* @returns {Promise<void>}
*/
callEmployerUserProfileApi = async () => {
this.setState({loading: true});
let headers = {'authorization': handleLocalStorage('get', 'employerLogin'), 'Content-Type': 'application/json',};
const requestData = {token: getQueryVariable('token')};
try {
const USerProfileData = await apiCall('get', requestData, EMPLOYER_SHARED_USER_PROFILE, headers);
if (USerProfileData.status) {
USerProfileData.data["is_fresher"] = !USerProfileData.is_experienced;
this.setState({result: USerProfileData.data, loading: false, sorry: false})
} else this.setState({result1: USerProfileData.data, loading: false, sorry: true})
} catch (e) {
}
};
render() {
const {classes} = this.props;
const {sorry, loading, result} = this.state;
return (
<div className="shared-inbox-user-profile-page">
{
!loading ? !sorry ?
<div style={{width: "100%"}}>
<div className="shared-inbox-user-profile-auto-overflow">
<div className="shared-inbox-user-profile-border-padding">
<div className="shared-inbox-user-profile-name-login">
<div
className="head-text-padding shared-inbox-user-profile-text">{result.snippet ? result.snippet.full_name : ""}</div>
<div>
<Button variant="outlined" className={classes.button}>
Login
</Button>
</div>
</div>
<div className="shared-inbox-user-profile-right-container">
<div className="shared-inbox-user-profile-left-wraper">
{!isEmpty(result.basic_profile) &&
<div className="component-div-padding">
<BasicDetails
fresher_experienced={result.is_fresher}
basic_profile={result.basic_profile}
/>
</div>
}
{result.resume_headline !== '' && result.resume_headline !== null &&
<div className="component-div-padding">
<ResumeHeadline resume_headline={result.resume_headline}/>
</div>
}
{result.profile_summary !== '' && result.profile_summary !== null &&
<div className="component-div-padding">
<ProfileSummary profile_summary={result.profile_summary}/>
</div>
}
{result.skills.length !== 0 &&
<div className="component-div-padding">
<Technologies skills={result.skills}/>
</div>
}
{result.employment_details.length > 0 || !isEmptyObjOfArray(result.training_internship) ?
<div className="component-div-padding">
<Employment
employment_details={result.employment_details}
fresher_experienced={result.is_fresher}
training_internship={result.training_internship}
/>
</div> : ''
}
{result.education.length > 0 &&
<div className="component-div-padding">
<Education education={result.education}/>
</div>
}
{result.technologies.length !== 0 &&
<div className="component-div-padding">
<TechnologiesWorkedOn technologies={result.technologies}/>
</div>
}
{result.projects.length !== 0 &&
<div className="component-div-padding">
<Projects projects={result.projects}/>
</div>
}
{!result.is_fresher && (!isEmptyObjOfArray(result.training_internship) || !isEmptyObjOfArray(result.achievements)) ?
<div className="component-div-padding">
<MyAchievements
training_internship={result.training_internship}
achievements={result.achievements}
/>
</div>
: ''
}
{!isEmpty(result.desired_profile) &&
<div className="component-div-padding">
<DesiredCareerProfile desired_profile={result.desired_profile}/>
</div>
}
{!isEmpty(result.personal_details) &&
<div className="component-div-padding">
<PersonalDetails personal_details={result.personal_details}/>
</div>
}
</div>
<div className="shared-inbox-user-profile-right-wraper">
<AppliedUserProfileSideCard {...this.props} snippet={result.snippet}
application_status={result.application_status}
resumes={result.resumes} viewOnly={true}/>
</div>
</div>
</div>
</div>
</div> : <PageNotFound/> : <div><LoadingIcon/>
</div>}
</div>
);
}
}
export default withStyles(styles)(SharedAppliedUserProfile);
|
DEDZTBH/ejml
|
main/ejml-core/src/org/ejml/data/DMatrixD1.java
|
/*
* Copyright (c) 2020, <NAME>. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ejml.data;
import org.ejml.UtilEjml;
import org.ejml.ops.MatrixIO;
/**
* A generic abstract class for matrices whose data is stored in a single 1D array of doubles. The
* format of the elements in this array is not specified. For example row major, column major,
* and block row major are all common formats.
*
* @author <NAME>
*/
public abstract class DMatrixD1 implements ReshapeMatrix, DMatrix {
/**
* Where the raw data for the matrix is stored. The format is type dependent.
*/
public double[] data = UtilEjml.ZERO_LENGTH_F64;
/**
* Number of rows in the matrix.
*/
public int numRows;
/**
* Number of columns in the matrix.
*/
public int numCols;
/**
* Used to get a reference to the internal data.
*
* @return Reference to the matrix's data.
*/
public double[] getData() {
return data;
}
/**
* Changes the internal array reference.
*/
public void setData( double[] data ) {
this.data = data;
}
/**
* Returns the internal array index for the specified row and column.
*
* @param row Row index.
* @param col Column index.
* @return Internal array index.
*/
public abstract int getIndex( int row, int col );
/**
* Sets the value of this matrix to be the same as the value of the provided matrix. Both
* matrices must have the same shape:<br>
* <br>
* a<sub>ij</sub> = b<sub>ij</sub><br>
* <br>
*
* @param b The matrix that this matrix is to be set equal to.
*/
public void setTo( DMatrixD1 b )
{
this.reshape(b.numRows,b.numCols);
int dataLength = b.getNumElements();
System.arraycopy(b.data, 0, this.data, 0, dataLength);
}
/**
* Returns the value of the matrix at the specified internal array index. The element at which row and column
* returned by this function depends upon the matrix's internal structure, e.g. row-major, column-major, or block.
*
* @param index Internal array index.
* @return Value at the specified index.
*/
public double get( int index ) {
return data[index];
}
/**
* Sets the element's value at the specified index. The element at which row and column
* modified by this function depends upon the matrix's internal structure, e.g. row-major, column-major, or block.
*
* @param index Index of element that is to be set.
* @param val The new value of the index.
*/
public double set( int index , double val ) {
// See benchmarkFunctionReturn. Pointless return does not degrade performance. Tested on JDK 1.6.0_21
return data[index] = val;
}
/**
* <p>
* Adds the specified value to the internal data array at the specified index.<br>
* <br>
* Equivalent to: this.data[index] += val;
* </p>
*
* <p>
* Intended for use in highly optimized code. The row/column coordinate of the modified element is
* dependent upon the matrix's internal structure.
* </p>
*
* @param index The index which is being modified.
* @param val The value that is being added.
*/
public double plus( int index , double val ) {
// See benchmarkFunctionReturn. Pointless return does not degrade performance. Tested on JDK 1.6.0_21
return data[index] += val;
}
/**
* <p>
* Subtracts the specified value to the internal data array at the specified index.<br>
* <br>
* Equivalent to: this.data[index] -= val;
* </p>
*
* <p>
* Intended for use in highly optimized code. The row/column coordinate of the modified element is
* dependent upon the matrix's internal structure.
* </p>
*
* @param index The index which is being modified.
* @param val The value that is being subtracted.
*/
public double minus( int index , double val ) {
// See benchmarkFunctionReturn. Pointless return does not degrade performance. Tested on JDK 1.6.0_21
return data[index] -= val;
}
/**
* <p>
* Multiplies the specified value to the internal data array at the specified index.<br>
* <br>
* Equivalent to: this.data[index] *= val;
* </p>
*
* <p>
* Intended for use in highly optimized code. The row/column coordinate of the modified element is
* dependent upon the matrix's internal structure.
* </p>
*
* @param index The index which is being modified.
* @param val The value that is being multiplied.
*/
public double times( int index , double val ) {
// See benchmarkFunctionReturn. Pointless return does not degrade performance. Tested on JDK 1.6.0_21
return data[index] *= val;
}
/**
* <p>
* Divides the specified value to the internal data array at the specified index.<br>
* <br>
* Equivalent to: this.data[index] /= val;
* </p>
*
* <p>
* Intended for use in highly optimized code. The row/column coordinate of the modified element is
* dependent upon the matrix's internal structure.
* </p>
*
* @param index The index which is being modified.
* @param val The value that is being divided.
*/
public double div( int index , double val ) {
// See benchmarkFunctionReturn. Pointless return does not degrade performance. Tested on JDK 1.6.0_21
return data[index] /= val;
}
/**
* <p>
* Changes the number of rows and columns in the matrix, allowing its size to grow or shrink.
* If the saveValues flag is set to true, then the previous values will be maintained, but
* reassigned to new elements in a row-major ordering. If saveValues is false values will only
* be maintained when the requested size is less than or equal to the internal array size.
* The primary use for this function is to encourage data reuse and avoid unnecessarily declaring
* and initialization of new memory.
* </p>
*
* <p>
* Examples:<br>
* [ 1 2 ; 3 4 ] → reshape( 2 , 3 , true ) = [ 1 2 3 ; 4 0 0 ]<br>
* [ 1 2 ; 3 4 ] → reshape( 1 , 2 , true ) = [ 1 2 ]<br>
* [ 1 2 ; 3 4 ] → reshape( 1 , 2 , false ) = [ 1 2 ]<br>
* [ 1 2 ; 3 4 ] → reshape( 2 , 3 , false ) = [ 0 0 0 ; 0 0 0 ]
* </p>
*
* @param numRows The new number of rows in the matrix.
* @param numCols The new number of columns in the matrix.
* @param saveValues If true then the value of each element will be save using a row-major reordering. Typically this should be false.
*/
public abstract void reshape(int numRows, int numCols, boolean saveValues);
/**
* Equivalent to invoking reshape(numRows,numCols,false);
*
* @param numRows The new number of rows in the matrix.
* @param numCols The new number of columns in the matrix.
*/
@Override
public void reshape( int numRows , int numCols ) {
reshape(numRows,numCols,false);
}
/**
* Creates a new iterator for traversing through a submatrix inside this matrix. It can be traversed
* by row or by column. Range of elements is inclusive, e.g. minRow = 0 and maxRow = 1 will include rows
* 0 and 1. The iteration starts at (minRow,minCol) and ends at (maxRow,maxCol)
*
* @param rowMajor true means it will traverse through the submatrix by row first, false by columns.
* @param minRow first row it will start at.
* @param minCol first column it will start at.
* @param maxRow last row it will stop at.
* @param maxCol last column it will stop at.
* @return A new MatrixIterator
*/
public DMatrixIterator iterator(boolean rowMajor, int minRow, int minCol, int maxRow, int maxCol)
{
return new DMatrixIterator(this,rowMajor, minRow, minCol, maxRow, maxCol);
}
@Override
public void print() {
MatrixIO.printFancy(System.out,this,MatrixIO.DEFAULT_LENGTH);
}
@Override
public void print( String format ) {
MatrixIO.print(System.out,this, format );
}
/**
* {@inheritDoc}
*/
@Override
public int getNumRows() {
return numRows;
}
/**
* {@inheritDoc}
*/
@Override
public int getNumCols() {
return numCols;
}
/**
* Sets the number of rows.
*
* @param numRows Number of rows
*/
public void setNumRows(int numRows) {
this.numRows = numRows;
}
/**
* Sets the number of columns.
*
* @param numCols Number of columns
*/
public void setNumCols(int numCols) {
this.numCols = numCols;
}
}
|
Draciel/Slackify
|
src/main/java/pl/draciel/slackify/resources/MessageImpl.java
|
package pl.draciel.slackify.resources;
import lombok.AllArgsConstructor;
import javax.annotation.Nonnull;
@AllArgsConstructor
public final class MessageImpl implements Message {
@Nonnull
public final String message;
@Nonnull
@Override
public String message() {
return message;
}
}
|
GabrielSantos25/Python
|
Exercicios em python/ex13.py
|
<filename>Exercicios em python/ex13.py
salario = int(input("Informe seu sálario: "))
aumento = (salario * 15) /100
total = salario + aumento
print("O seu sálario aumentou 15% e será R${}".format(total))
|
beichenhpy/notes
|
Netty/netty-demo/src/main/java/me/young1lin/netty/demo/wrap/serializer/ProtobufInitializer.java
|
package me.young1lin.netty.demo.wrap.serializer;
import com.google.protobuf.MessageLite;
import io.netty.channel.*;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
/**
* Google Protocol Buffer
*
* @author young1lin
* @version 1.0
* @date 2020/11/2 9:58 下午
*/
public class ProtobufInitializer extends ChannelInitializer<Channel> {
private final MessageLite lite;
public ProtobufInitializer(MessageLite lite) {
this.lite = lite;
}
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ProtobufVarint32FrameDecoder());
pipeline.addLast(new ProtobufEncoder());
pipeline.addLast(new ProtobufDecoder(lite));
pipeline.addLast(new ObjectHandler());
}
public static final class ObjectHandler extends SimpleChannelInboundHandler<Object> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
// Do something with object
}
}
}
|
fbarthez/aribaweb
|
src/metaui/ariba/ui/meta/editor/MetaSideInspector.java
|
<filename>src/metaui/ariba/ui/meta/editor/MetaSideInspector.java
/*
Copyright 1996-2008 Ariba, 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.
$Id: //ariba/platform/ui/metaui/ariba/ui/meta/editor/MetaSideInspector.java#2 $
*/
package ariba.ui.meta.editor;
import ariba.ui.aribaweb.core.AWComponent;
import ariba.ui.widgets.FooterIncludes;
import ariba.ui.meta.core.UIMeta;
public class MetaSideInspector extends AWComponent
{
static {
FooterIncludes.registerInclude(MetaSideInspector.class.getName());
}
public static void initialize ()
{
}
public boolean enabled ()
{
if (requestContext().frameName() != null) return false;
EditManager editManager = EditManager.activeEditManager(UIMeta.getInstance(), session());
return (editManager != null) && (editManager.getSelectedRecord() != null);
}
public void closeAction ()
{
EditManager editManager = EditManager.currentEditManager(UIMeta.getInstance(), session(), true);
editManager.setSelectedRecord(null);
}
}
|
Jia-shuaitao/esa-restlight
|
restlight-test/restlight-test-mock/src/main/java/esa/restlight/test/mock/MockHttpOutputStream.java
|
/*
* Copyright 2020 OPPO ESA Stack Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package esa.restlight.test.mock;
import esa.httpserver.core.HttpOutputStream;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.MathUtil;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;
class MockHttpOutputStream extends HttpOutputStream {
private final MockAsyncResponse response;
private final ByteBuf buffer;
private final AtomicBoolean closed;
MockHttpOutputStream(MockAsyncResponse response) {
this.response = response;
this.buffer = Unpooled.buffer();
this.closed = new AtomicBoolean(response.isCommitted());
}
@Override
public void write(int b) {
checkCloseState();
ensureSpace(1);
buffer.writeByte(b);
}
@Override
public void write(byte[] b, int off, int len) {
if (b == null) {
throw new NullPointerException("b");
}
if (MathUtil.isOutOfBounds(off, len, b.length)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return;
}
checkCloseState();
write0(b, off, len);
}
@Override
public void writeBoolean(boolean v) {
checkCloseState();
ensureSpace(1);
buffer.writeBoolean(v);
}
@Override
public void writeByte(int v) {
checkCloseState();
ensureSpace(1);
buffer.writeByte(v);
}
@Override
public void writeShort(int v) {
checkCloseState();
ensureSpace(2);
buffer.writeShort(v);
}
@Override
public void writeChar(int v) {
checkCloseState();
ensureSpace(2);
buffer.writeChar(v);
}
@Override
public void writeInt(int v) {
checkCloseState();
ensureSpace(4);
buffer.writeInt(v);
}
@Override
public void writeLong(long v) {
checkCloseState();
ensureSpace(8);
buffer.writeLong(v);
}
@Override
public void writeFloat(float v) {
checkCloseState();
ensureSpace(4);
buffer.writeFloat(v);
}
@Override
public void writeDouble(double v) {
checkCloseState();
ensureSpace(8);
buffer.writeDouble(v);
}
@Override
public void writeBytes(String s) {
checkNullAndCloseState(s);
int len = s.length();
int writable;
int off = 0;
while ((writable = buffer.maxWritableBytes()) < len) {
writeAscii0(s, off, writable);
len -= writable;
off += writable;
flush(false);
}
if (len > 0) {
writeAscii0(s, off, len);
}
}
@Override
public void writeChars(String s) {
checkNullAndCloseState(s);
int len = s.length();
int writable;
int off = 0;
//Sets the specified 2-byte UTF-16 character
//The 16 high-order bits of the specified value are ignored.
while ((writable = buffer.maxWritableBytes() / 2) < len) {
writeChars0(s, off, writable);
len -= writable;
off += writable;
flush(false);
}
if (len > 0) {
writeChars0(s, off, len);
}
}
@Override
public void writeUTF(String s) {
checkNullAndCloseState(s);
int len = ByteBufUtil.utf8MaxBytes(s);
if (len > buffer.maxCapacity()) {
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
write0(bytes, 0, bytes.length);
} else {
ensureSpace(len);
buffer.writeCharSequence(s, CharsetUtil.UTF_8);
}
}
@Override
public void flush() {
if (isClosed()) {
return;
}
flush(false);
}
private void flush(boolean isLast) {
if (buffer.readableBytes() == 0) {
if (isLast) {
buffer.release();
}
return;
}
response.casSetCommitted();
response.result.writeBytes(buffer);
if (isLast) {
buffer.release();
} else {
buffer.clear();
}
}
@Override
public void close() {
if (!closed.compareAndSet(false, true)) {
return;
}
flush(true);
response.callEndListener();
}
@Override
public boolean isClosed() {
return closed.get();
}
private void checkNullAndCloseState(String s) {
if (s == null) {
throw new NullPointerException("s");
}
checkCloseState();
}
private void checkCloseState() {
if (isClosed()) {
throw new IllegalStateException("Output stream already closed");
}
}
private void write0(byte[] b, int off, int len) {
// if current buf's writable space is less than len
// write in the left space of the current buf and flush it
int writable;
while ((writable = buffer.maxWritableBytes()) < len) {
buffer.writeBytes(b, off, writable);
len -= writable;
off += writable;
flush(false);
}
if (len > 0) {
buffer.writeBytes(b, off, len);
}
}
private void ensureSpace(int space) {
if (buffer.maxWritableBytes() < space && buffer.capacity() > 0) {
flush(false);
}
}
private void writeAscii0(CharSequence seq, int off, int len) {
int max = off + len;
for (int i = off; i < max; i++) {
buffer.writeByte(AsciiString.c2b(seq.charAt(i)));
}
}
private void writeChars0(CharSequence seq, int off, int len) {
int max = off + len;
for (int i = off; i < max; i++) {
buffer.writeChar(seq.charAt(i));
}
}
}
|
sean5470/panda3d
|
panda/src/ode/odeUtil_ext.cxx
|
<reponame>sean5470/panda3d
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file odeUtil_ext.cxx
* @author rdb
* @date 2013-12-10
*/
#include "odeUtil_ext.h"
#include "config_ode.h"
#include "odeGeom.h"
#include "odeGeom_ext.h"
#ifdef HAVE_PYTHON
PyObject *Extension<OdeUtil>::_python_callback = NULL;
/**
* Calls the callback for all potentially intersecting pairs that contain one
* geom from geom1 and one geom from geom2.
*/
int Extension<OdeUtil>::
collide2(const OdeGeom &geom1, const OdeGeom &geom2, PyObject* arg, PyObject* callback) {
nassertr(callback != NULL, -1);
if (!PyCallable_Check(callback)) {
PyErr_Format(PyExc_TypeError, "'%s' object is not callable", callback->ob_type->tp_name);
return -1;
} else {
_python_callback = (PyObject*) callback;
Py_XINCREF(_python_callback);
dSpaceCollide2(geom1.get_id(), geom2.get_id(), (void*) arg, &near_callback);
Py_XDECREF(_python_callback);
return 0;
}
}
void Extension<OdeUtil>::
near_callback(void *data, dGeomID o1, dGeomID o2) {
if (ode_cat.is_spam()) {
ode_cat.spam()
<< "near_callback called, data: " << data << ", dGeomID1: " << o1 << ", dGeomID2: " << o2 << "\n";
}
OdeGeom g1 (o1);
OdeGeom g2 (o2);
PyObject* p1 = invoke_extension(&g1).convert();
PyObject* p2 = invoke_extension(&g2).convert();
PyObject* result = PyObject_CallFunctionObjArgs(_python_callback, (PyObject*) data, p1, p2, NULL);
if (!result) {
ode_cat.error() << "An error occurred while calling python function!\n";
PyErr_Print();
}
Py_XDECREF(p1);
Py_XDECREF(p2);
}
#endif // HAVE_PYTHON
|
KnowSciEng/TransmogrifAI
|
helloworld/src/main/scala/com/salesforce/hw/boston/BostonFeatures.scala
|
<reponame>KnowSciEng/TransmogrifAI
/*
* Copyright (c) 2017, Salesforce.com, 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 the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.hw.boston
import com.salesforce.hw.boston.BostonFeatures._
import com.salesforce.op.features.FeatureBuilder
import com.salesforce.op.features.types._
trait BostonFeatures extends Serializable {
val rowId = FeatureBuilder.Integral[BostonHouse].extract(new RowId).asPredictor
val crim = FeatureBuilder.RealNN[BostonHouse].extract(new Crim).asPredictor
val zn = FeatureBuilder.RealNN[BostonHouse].extract(new Zn).asPredictor
val indus = FeatureBuilder.RealNN[BostonHouse].extract(new Indus).asPredictor
val chas = FeatureBuilder.PickList[BostonHouse].extract(new Chas).asPredictor
val nox = FeatureBuilder.RealNN[BostonHouse].extract(new Nox).asPredictor
val rm = FeatureBuilder.RealNN[BostonHouse].extract(new RM).asPredictor
val age = FeatureBuilder.RealNN[BostonHouse].extract(new Age).asPredictor
val dis = FeatureBuilder.RealNN[BostonHouse].extract(new Dis).asPredictor
val rad = FeatureBuilder.Integral[BostonHouse].extract(new Rad).asPredictor
val tax = FeatureBuilder.RealNN[BostonHouse].extract(new Tax).asPredictor
val ptratio = FeatureBuilder.RealNN[BostonHouse].extract(new PTRatio).asPredictor
val b = FeatureBuilder.RealNN[BostonHouse].extract(new B).asPredictor
val lstat = FeatureBuilder.RealNN[BostonHouse].extract(new Lstat).asPredictor
val medv = FeatureBuilder.RealNN[BostonHouse].extract(new Medv).asResponse
}
object BostonFeatures {
abstract class BostonFeatureFunc[T] extends Function[BostonHouse, T] with Serializable
class RealNNExtract(f: BostonHouse => Double) extends BostonFeatureFunc[RealNN] {
override def apply(v1: BostonHouse): RealNN = f(v1).toRealNN
}
class IntegralExtract(f: BostonHouse => Int) extends BostonFeatureFunc[Integral] {
override def apply(v1: BostonHouse): Integral = f(v1).toIntegral
}
class RowId extends IntegralExtract(_.rowId)
class Rad extends IntegralExtract(_.rad)
class Crim extends RealNNExtract(_.crim)
class Zn extends RealNNExtract(_.zn)
class Indus extends RealNNExtract(_.indus)
class Nox extends RealNNExtract(_.nox)
class RM extends RealNNExtract(_.rm)
class Age extends RealNNExtract(_.age)
class Dis extends RealNNExtract(_.dis)
class Tax extends RealNNExtract(_.tax)
class PTRatio extends RealNNExtract(_.ptratio)
class B extends RealNNExtract(_.b)
class Lstat extends RealNNExtract(_.lstat)
class Medv extends RealNNExtract(_.medv)
class Chas extends BostonFeatureFunc[PickList] {
override def apply(v1: BostonHouse): PickList = Option(v1.chas).toPickList
}
}
|
srikanthprathi/Segs
|
Common/Runtime/RuntimeData.h
|
#pragma once
#include "Common/Runtime/HandleBasedStorage.h"
#include <QHash>
struct SceneModifiers;
struct FSWrapper;
namespace SEGS
{
struct RuntimeData;
}
extern SEGS::RuntimeData& getRuntimeData();
namespace SEGS
{
using HTexture = SingularStoreHandleT<20,12,struct TextureWrapper>;
struct PrefabStore;
struct RuntimeData
{
//! Here we store handles to loaded texture headers
QHash<QByteArray, HTexture> m_loaded_textures;
//! map from texture name to full file path
QHash<QByteArray, QByteArray> m_texture_paths;
PrefabStore * m_prefab_mapping = nullptr; //!< maps directories and model names to geosets
SceneModifiers * m_modifiers = nullptr;
FSWrapper * m_wrapper = nullptr;
bool m_ready = false; //!< set to true if runtime data was read.
bool prepare(FSWrapper *fs,const QByteArray &directory_path);
bool read_prefab_definitions(const QByteArray &directory_path);
bool read_model_modifiers(const QByteArray &directory_path);
// This is a non-copyable type
RuntimeData(const RuntimeData &) = delete;
RuntimeData &operator=(const RuntimeData&) = delete;
private:
friend RuntimeData& ::getRuntimeData();
RuntimeData() = default;
};
} //end of SEGS namespace
|
im6705/csgo_full
|
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/Code/vtabledumphelper.cpp
|
#include "Interfaces/InterfacesProxy.h"
#include "Misc/Helpers.h"
#ifdef WIN32
# define DbgBreak() __debugbreak()
#else
# include <signal.h>
# define DbgBreak() raise(SIGTRAP)
#endif
/*
(gdb) set print demangle on
(gdb) set $i = 0
(gdb) while $i < 100
>print $i
>p /a (*pcur)[$i]
>set $i = $i + 1
>end
*/
void HelpMeeee()
{
using namespace SourceSdk::InterfacesProxy;
using namespace Helpers;
// engine callbacks first
void *** pcur;
printf("------------------------------\nDumping virtual classes pointers for game ID %d\n", m_game);
printf("pcur -> m_servergamedll %d\n", m_servergamedll_version);
pcur = (void ***)m_servergamedll;
DbgBreak();
printf("pcur -> m_playerinfomanager %d\n", m_playerinfomanager_version);
pcur = (void ***)m_playerinfomanager;
DbgBreak();
printf("pcur -> m_servergameents %d\n", m_servergameents_version);
pcur = (void ***)m_servergameents;
DbgBreak();
printf("pcur -> m_servergameclients %d\n", m_servergameclients_version);
pcur = (void ***)m_servergameclients;
DbgBreak();
printf("pcur -> m_engineserver %d\n", m_engineserver_version);
pcur = (void ***)m_engineserver;
DbgBreak();
printf("pcur -> m_gameeventmanager %d\n", m_gameeventmanager_version);
pcur = (void ***)m_gameeventmanager;
DbgBreak();
printf("pcur -> m_serverpluginhelpers %d\n", m_serverpluginhelpers_version);
pcur = (void ***)m_serverpluginhelpers;
DbgBreak();
printf("pcur -> m_enginetrace %d\n", m_enginetrace_version);
pcur = (void ***)m_enginetrace;
DbgBreak();
printf("pcur -> m_cvar %d\n", m_enginecvar_version);
pcur = (void ***)m_cvar;
DbgBreak();
if (SourceSdk::InterfacesProxy::m_game == SourceSdk::CounterStrikeGlobalOffensive)
{
SourceSdk::edict_t_csgo * cur(PEntityOfEntIndex(0));
SourceSdk::edict_t_csgo * const max_cur(cur + MAX_EDICTS);
do
{
#undef GetClassName
if (cur->GetClassName() != nullptr && cur->GetClassName()[0] != 0)
{
printf("pcur -> Entity %s m_pUnk\n", cur->GetClassName());
pcur = (void ***)cur->m_pUnk;
DbgBreak();
}
} while (++cur <= max_cur);
}
else
{
SourceSdk::edict_t * cur(PEntityOfEntIndex(0));
SourceSdk::edict_t * const max_cur(cur + MAX_EDICTS);
do
{
#undef GetClassName
if (cur->GetClassName() != nullptr && cur->GetClassName()[0] != 0)
{
printf("pcur -> Entity %s m_pUnk\n", cur->GetClassName());
pcur = (void ***)cur->m_pUnk;
DbgBreak();
}
} while (++cur <= max_cur);
}
printf("%X\n", (size_t)pcur);
}
|
anatolyyyyyy/kubernetes-ingress-controller
|
internal/ingress/controller/store/cert.go
|
package store
import (
"bytes"
"fmt"
"strings"
"github.com/kong/kubernetes-ingress-controller/internal/ingress"
"github.com/kong/kubernetes-ingress-controller/internal/ssl"
apiv1 "k8s.io/api/core/v1"
)
func (s k8sStore) GetCertFromSecret(secretName string) (*ingress.SSLCert, error) {
secret, err := s.listers.Secret.ByKey(secretName)
if err != nil {
return nil, fmt.Errorf("error retrieving secret %v: %v", secretName, err)
}
cert, okcert := secret.Data[apiv1.TLSCertKey]
key, okkey := secret.Data[apiv1.TLSPrivateKeyKey]
if !okcert || !okkey {
return nil, fmt.Errorf("no keypair could be found in %v", secretName)
}
cert = []byte(strings.TrimSpace(bytes.NewBuffer(cert).String()))
key = []byte(strings.TrimSpace(bytes.NewBuffer(key).String()))
sslCert := &ingress.SSLCert{
Raw: ingress.RawSSLCert{
Cert: cert,
Key: key,
},
ID: fmt.Sprintf("%v", secret.GetUID()),
}
sslCert.Namespace = secret.Namespace
certificate, err := ssl.ParseX509Certificate(cert, key)
if err != nil {
return nil, err
}
sslCert.Certificate = certificate
cn := ssl.ParseCommonNamesFromCert(certificate)
sslCert.CN = cn
sslCert.ExpireTime = certificate.NotAfter
return sslCert, nil
}
|
lczx/fdi2-exams
|
exams/eqsolve/src/main/java/eqsolve/equation/QuadraticEquation.java
|
package eqsolve.equation;
public class QuadraticEquation extends EquationBase {
/*@Override
public String getFriendlyName() {
return "Quadratic Equation";
}*/
@Override
public String getCurrentFormula() {
return String.format("%.1f x² + %.1f x + %.1f = 0", getParam(0), getParam(1), getParam(2));
}
@Override
public int getParamListSize() {
return 3;
}
}
|
sunxuia/MyBatisAutoMapper
|
BaseProcessor/src/main/java/net/sunxu/mybatis/automapper/processor/util/AutoMapperException.java
|
package net.sunxu.mybatis.automapper.processor.util;
public class AutoMapperException extends RuntimeException {
private AutoMapperException(String message) {
super(message);
}
private AutoMapperException(Throwable cause) {
super(cause);
}
public static AutoMapperException newException(String message, Object... paras) {
if (paras.length > 0)
message = String.format(message, paras);
return new AutoMapperException(message);
}
public static AutoMapperException newException(Throwable cause) {
return new AutoMapperException(cause);
}
@FunctionalInterface
public interface RunnableWithException {
void run() throws Exception;
}
public static void wrapException(RunnableWithException runnable) {
try {
runnable.run();
} catch (Exception err) {
throw new AutoMapperException(err);
}
}
@FunctionalInterface
public interface SupplierWithException<T> {
T get() throws Exception;
}
public static <T> T wrapException(SupplierWithException<T> function) {
try {
return function.get();
} catch (Exception err) {
throw new AutoMapperException(err);
}
}
public static <T> T wrapException(SupplierWithException<T> function, String failMessage, Object... paras) {
try {
return function.get();
} catch (Exception err) {
throw newException(failMessage, paras);
}
}
}
|
blimyj/RPKit
|
bukkit/rpk-stores-bukkit/src/main/java/com/rpkit/store/bukkit/database/jooq/tables/records/RpkitConsumablePurchaseRecord.java
|
<filename>bukkit/rpk-stores-bukkit/src/main/java/com/rpkit/store/bukkit/database/jooq/tables/records/RpkitConsumablePurchaseRecord.java
/*
* This file is generated by jOOQ.
*/
package com.rpkit.store.bukkit.database.jooq.tables.records;
import com.rpkit.store.bukkit.database.jooq.tables.RpkitConsumablePurchase;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class RpkitConsumablePurchaseRecord extends UpdatableRecordImpl<RpkitConsumablePurchaseRecord> implements Record3<Integer, Integer, Integer> {
private static final long serialVersionUID = 1L;
/**
* Setter for <code>rpkit_stores.rpkit_consumable_purchase.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>rpkit_stores.rpkit_consumable_purchase.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>rpkit_stores.rpkit_consumable_purchase.purchase_id</code>.
*/
public void setPurchaseId(Integer value) {
set(1, value);
}
/**
* Getter for <code>rpkit_stores.rpkit_consumable_purchase.purchase_id</code>.
*/
public Integer getPurchaseId() {
return (Integer) get(1);
}
/**
* Setter for <code>rpkit_stores.rpkit_consumable_purchase.remaining_uses</code>.
*/
public void setRemainingUses(Integer value) {
set(2, value);
}
/**
* Getter for <code>rpkit_stores.rpkit_consumable_purchase.remaining_uses</code>.
*/
public Integer getRemainingUses() {
return (Integer) get(2);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
@Override
public Row3<Integer, Integer, Integer> fieldsRow() {
return (Row3) super.fieldsRow();
}
@Override
public Row3<Integer, Integer, Integer> valuesRow() {
return (Row3) super.valuesRow();
}
@Override
public Field<Integer> field1() {
return RpkitConsumablePurchase.RPKIT_CONSUMABLE_PURCHASE.ID;
}
@Override
public Field<Integer> field2() {
return RpkitConsumablePurchase.RPKIT_CONSUMABLE_PURCHASE.PURCHASE_ID;
}
@Override
public Field<Integer> field3() {
return RpkitConsumablePurchase.RPKIT_CONSUMABLE_PURCHASE.REMAINING_USES;
}
@Override
public Integer component1() {
return getId();
}
@Override
public Integer component2() {
return getPurchaseId();
}
@Override
public Integer component3() {
return getRemainingUses();
}
@Override
public Integer value1() {
return getId();
}
@Override
public Integer value2() {
return getPurchaseId();
}
@Override
public Integer value3() {
return getRemainingUses();
}
@Override
public RpkitConsumablePurchaseRecord value1(Integer value) {
setId(value);
return this;
}
@Override
public RpkitConsumablePurchaseRecord value2(Integer value) {
setPurchaseId(value);
return this;
}
@Override
public RpkitConsumablePurchaseRecord value3(Integer value) {
setRemainingUses(value);
return this;
}
@Override
public RpkitConsumablePurchaseRecord values(Integer value1, Integer value2, Integer value3) {
value1(value1);
value2(value2);
value3(value3);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached RpkitConsumablePurchaseRecord
*/
public RpkitConsumablePurchaseRecord() {
super(RpkitConsumablePurchase.RPKIT_CONSUMABLE_PURCHASE);
}
/**
* Create a detached, initialised RpkitConsumablePurchaseRecord
*/
public RpkitConsumablePurchaseRecord(Integer id, Integer purchaseId, Integer remainingUses) {
super(RpkitConsumablePurchase.RPKIT_CONSUMABLE_PURCHASE);
setId(id);
setPurchaseId(purchaseId);
setRemainingUses(remainingUses);
}
}
|
kashifiqb/Aspose.PDF-for-C
|
Examples/include/asposecpplib/system/details/call_once.h
|
<reponame>kashifiqb/Aspose.PDF-for-C<filename>Examples/include/asposecpplib/system/details/call_once.h
/// @file system/details/call_once.h
#pragma once
#include <atomic>
#include <mutex>
namespace System { namespace Details {
/// Specifies how a CallOnce instance synchronizes access among multiple threads.
enum class CallOnceThreadSafetyMode
{
/// The CallOnce instance is thread safe.
ThreadSafe,
/// The CallOnce instance is not thread safe.
NotThreadSafe,
/// Thread-safety mode is specified at runtime.
Customizable
};
/// Executes the callable object exactly once.
template <CallOnceThreadSafetyMode thread_safety_mode>
class CallOnce;
/// Thread safe CallOnce specialization.
template <>
class CallOnce<CallOnceThreadSafetyMode::ThreadSafe>
{
public:
constexpr CallOnce() noexcept
: m_called(false)
{}
CallOnce(const CallOnce&) = delete;
CallOnce& operator=(const CallOnce&) = delete;
/// Executes the Callable object exactly once.
template <typename Callable>
bool operator()(Callable&& callable)
{
bool result = false;
if (!called())
{
std::call_once(m_once_flag, [&]()
{
result = true;
callable();
m_called.store(true, std::memory_order_release);
});
}
return result;
}
/// Get the flag indicating that CallOnce was already called.
bool called(std::memory_order order = std::memory_order_acquire) const
{
return m_called.load(order);
}
private:
std::once_flag m_once_flag;
std::atomic_bool m_called;
};
/// Not thread safe CallOnce specialization.
template <>
class CallOnce<CallOnceThreadSafetyMode::NotThreadSafe>
{
public:
constexpr CallOnce() noexcept
: m_called(false)
{}
CallOnce(const CallOnce&) = delete;
CallOnce& operator=(const CallOnce&) = delete;
/// Executes the Callable object exactly once.
template <typename Callable>
bool operator()(Callable&& callable)
{
if (!called())
{
callable();
m_called.store(true, std::memory_order_release);
return true;
}
return false;
}
/// Get the flag indicating that CallOnce was already called.
bool called(std::memory_order order = std::memory_order_acquire) const
{
return m_called.load(order);
}
private:
std::atomic_bool m_called;
};
/// Customizable CallOnce specialization.
template <>
class CallOnce<CallOnceThreadSafetyMode::Customizable>
{
public:
constexpr CallOnce(bool thread_safe = true) noexcept
: m_called(false)
, m_thread_safe(thread_safe)
{}
CallOnce(const CallOnce&) = delete;
CallOnce& operator=(const CallOnce&) = delete;
/// Executes the Callable object exactly once.
template <typename Callable>
bool operator()(Callable&& callable)
{
bool result = false;
if (!called())
{
if (m_thread_safe)
{
std::call_once(m_once_flag, [&]()
{
result = true;
callable();
m_called.store(true, std::memory_order_release);
});
}
else
{
result = true;
callable();
m_called.store(true, std::memory_order_release);
}
}
return result;
}
/// Get the flag indicating that CallOnce was already called.
bool called(std::memory_order order = std::memory_order_acquire) const
{
return m_called.load(order);
}
bool is_thread_safe() const
{
return m_thread_safe;
}
private:
std::once_flag m_once_flag;
std::atomic_bool m_called;
const bool m_thread_safe;
};
using ThreadSafeCallOnce = CallOnce<CallOnceThreadSafetyMode::ThreadSafe>;
using NotThreadSafeCallOnce = CallOnce<CallOnceThreadSafetyMode::NotThreadSafe>;
using CustomizableCallOnce = CallOnce<CallOnceThreadSafetyMode::Customizable>;
}} // namespace System::Details
|
SalihTuncer/DungeonCrawler
|
src/main/java/Text/SettingsText.java
|
package Text;
import Character.Player;
import Handler.SettingsHandler;
public class SettingsText extends Text {
public SettingsText() {
this.handler = new SettingsHandler();
}
@Override
public void printText(Player player) {
clear();
playerInterface(player);
System.out.println("You are now in the settings:");
decision(player);
}
@Override
public void decision(Player player) {
System.out.println("You have the following options:");
System.out.println("1.Stats of the player\n2.Stats of the current enemy\n3.Save game\n4.Load game");
System.out.println("5.Quit game\n6.Return");
System.out.print("Which option do you choose?: ");
this.handler.handleInput(getInput().nextLine().toLowerCase(), player);
}
}
|
qq476743842/weex-saoa
|
platforms/android/farwolf.weex/src/main/java/com/farwolf/weex/core/Page.java
|
package com.farwolf.weex.core;
import android.view.View;
import com.farwolf.weex.util.Weex;
import com.taobao.weex.WXSDKInstance;
import java.util.HashMap;
/**
* Created by zhengjiangrong on 2017/5/9.
*/
public class Page {
public String id;
public View v;
public WXSDKInstance instance;
public String url;
public boolean trigger=false;
HashMap param;
public boolean hasLoad()
{
return Weex.hasLoad(this.v);
}
}
|
i10416/dotty
|
compiler/src/dotty/tools/dotc/config/ScalaRelease.scala
|
<filename>compiler/src/dotty/tools/dotc/config/ScalaRelease.scala
package dotty.tools.dotc.config
enum ScalaRelease(val majorVersion: Int, val minorVersion: Int) extends Ordered[ScalaRelease]:
case Release3_0 extends ScalaRelease(3, 0)
case Release3_1 extends ScalaRelease(3, 1)
case Release3_2 extends ScalaRelease(3, 2)
def show = s"$majorVersion.$minorVersion"
def compare(that: ScalaRelease) =
val ord = summon[Ordering[(Int, Int)]]
ord.compare((majorVersion, minorVersion), (that.majorVersion, that.minorVersion))
object ScalaRelease:
def latest = Release3_1
def parse(name: String) = name match
case "3.0" => Some(Release3_0)
case "3.1" => Some(Release3_1)
case "3.2" => Some(Release3_2)
case _ => None
|
Alecto3-D/testable-greeter
|
bb-master/sandbox/lib/python3.5/site-packages/buildbot/www/avatar.py
|
<reponame>Alecto3-D/testable-greeter<filename>bb-master/sandbox/lib/python3.5/site-packages/buildbot/www/avatar.py
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
from future.moves.urllib.parse import urlencode
from future.moves.urllib.parse import urljoin
import hashlib
from twisted.internet import defer
from buildbot.util import config
from buildbot.util import unicode2bytes
from buildbot.www import resource
class AvatarBase(config.ConfiguredMixin):
name = "noavatar"
def getUserAvatar(self, email, size, defaultAvatarUrl):
raise NotImplementedError()
class AvatarGravatar(AvatarBase):
name = "gravatar"
# gravatar does not want intranet URL, which is most of where the bots are
# just use same default as github (retro)
default = "retro"
def getUserAvatar(self, email, size, defaultAvatarUrl):
# construct the url
emailBytes = unicode2bytes(email.lower())
emailHash = hashlib.md5(emailBytes)
gravatar_url = "//www.gravatar.com/avatar/"
gravatar_url += emailHash.hexdigest() + "?"
if self.default != "url":
defaultAvatarUrl = self.default
url = {'d': defaultAvatarUrl, 's': str(size)}
sorted_url = sorted(url.items(), key=lambda x: x[0])
gravatar_url += urlencode(sorted_url)
raise resource.Redirect(gravatar_url)
class AvatarResource(resource.Resource):
# enable reconfigResource calls
needsReconfig = True
defaultAvatarUrl = b"img/nobody.png"
def reconfigResource(self, new_config):
self.avatarMethods = new_config.www.get('avatar_methods', [])
self.defaultAvatarFullUrl = urljoin(
unicode2bytes(new_config.buildbotURL), unicode2bytes(self.defaultAvatarUrl))
self.cache = {}
# ensure the avatarMethods is a iterable
if isinstance(self.avatarMethods, AvatarBase):
self.avatarMethods = (self.avatarMethods, )
def render_GET(self, request):
return self.asyncRenderHelper(request, self.renderAvatar)
@defer.inlineCallbacks
def renderAvatar(self, request):
email = request.args.get(b"email", [b""])[0]
size = request.args.get(b"size", 32)
if self.cache.get(email):
r = self.cache[email]
for method in self.avatarMethods:
try:
res = yield method.getUserAvatar(email, size, self.defaultAvatarFullUrl)
except resource.Redirect as r:
self.cache[email] = r
raise
if res is not None:
request.setHeader(b'content-type', res[0])
request.setHeader(b'content-length', len(res[1]))
request.write(res[1])
return
raise resource.Redirect(self.defaultAvatarUrl)
|
bstansberry/undertow
|
core/src/main/java/io/undertow/server/handlers/AllowedMethodsHandler.java
|
<filename>core/src/main/java/io/undertow/server/handlers/AllowedMethodsHandler.java
package io.undertow.server.handlers;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import io.undertow.util.StatusCodes;
/**
* Handler that whitelists certain HTTP methods. Only requests with a method in
* the allowed methods set will be allowed to continue.
*
* @author <NAME>
*/
public class AllowedMethodsHandler implements HttpHandler {
private final Set<HttpString> allowedMethods;
private final HttpHandler next;
public AllowedMethodsHandler(final HttpHandler next, final Set<HttpString> allowedMethods) {
this.allowedMethods = new HashSet<HttpString>(allowedMethods);
this.next = next;
}
public AllowedMethodsHandler(final HttpHandler next, final HttpString... allowedMethods) {
this.allowedMethods = new HashSet<HttpString>(Arrays.asList(allowedMethods));
this.next = next;
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if (allowedMethods.contains(exchange.getRequestMethod())) {
next.handleRequest(exchange);
} else {
exchange.setResponseCode(StatusCodes.METHOD_NOT_ALLOWED);
exchange.endExchange();
}
}
}
|
BethWIntera/Beths_PySandbox
|
Learning Unittests/matplotlib-tutorial-master/scripts/plot3d_ex.py
|
# -----------------------------------------------------------------------------
# Copyright (c) 2015, <NAME>. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2,2)
# savefig('../figures/plot3d_ex.png',dpi=48)
plt.show()
|
wangsongiam/leetcode
|
solutions/572.subtree-of-another-tree/subtree-of-another-tree.js
|
<reponame>wangsongiam/leetcode
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} s
* @param {TreeNode} t
* @return {boolean}
*/
const isSubtree = (s, t) => {
if (!s) return false
if (isSame(s, t)) return true
return isSubtree(s.left, t) || isSubtree(s.right, t)
}
const isSame = (s, t) => {
if (!s && t) return false
if (s && !t) return false
if (!s && !t) return true
if (s.val === t.val) return isSame(s.left, t.left) && isSame(s.right, t.right)
else return false
}
|
SethTisue/http4s
|
server/src/main/scala/org/http4s/server/staticcontent/ResourceService.scala
|
<filename>server/src/main/scala/org/http4s/server/staticcontent/ResourceService.scala
package org.http4s
package server
package staticcontent
import java.util.concurrent.ExecutorService
import org.http4s.server._
import org.http4s.{Response, Request, StaticFile}
import scalaz.concurrent.{Strategy, Task}
object ResourceService {
/** [[org.http4s.server.staticcontent.ResourceService]] configuration
*
* @param basePath prefix of the path files will be served from
* @param pathPrefix prefix of the Uri that content will be served from
* @param bufferSize size hint of internal buffers to use when serving resources
* @param executor `ExecutorService` to use when collecting content
* @param cacheStrategy strategy to use for caching purposes. Default to no caching.
*/
final case class Config(basePath: String,
pathPrefix: String = "",
bufferSize: Int = 50*1024,
executor: ExecutorService = Strategy.DefaultExecutorService,
cacheStrategy: CacheStrategy = NoopCacheStrategy)
/** Make a new [[org.http4s.HttpService]] that serves static files. */
private[staticcontent] def apply(config: Config): Service[Request, Response] = Service.lift { req =>
val uriPath = req.pathInfo
if (!uriPath.startsWith(config.pathPrefix))
Response.fallthrough
else
StaticFile.fromResource(sanitize(config.basePath + '/' + getSubPath(uriPath, config.pathPrefix)))
.fold(Response.fallthrough)(config.cacheStrategy.cache(uriPath, _))
}
}
|
cdsnyder/esp-idf
|
components/bootloader_support/src/bootloader_init.c
|
// Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string.h>
#include <stdint.h>
#include "sdkconfig.h"
#include "esp_log.h"
#include "bootloader_init.h"
#include "bootloader_flash.h"
#include "bootloader_flash_config.h"
#include "bootloader_random.h"
#include "bootloader_clock.h"
#include "bootloader_common.h"
#include "esp_flash_encrypt.h"
#include "hal/timer_ll.h"
#include "soc/cpu.h"
#include "soc/rtc.h"
#include "soc/rtc_wdt.h"
static const char *TAG = "boot";
esp_image_header_t bootloader_image_hdr;
void bootloader_clear_bss_section(void)
{
memset(&_bss_start, 0, (&_bss_end - &_bss_start) * sizeof(_bss_start));
}
esp_err_t bootloader_read_bootloader_header(void)
{
/* load bootloader image header */
if (bootloader_flash_read(ESP_BOOTLOADER_OFFSET, &bootloader_image_hdr, sizeof(esp_image_header_t), true) != ESP_OK) {
ESP_LOGE(TAG, "failed to load bootloader image header!");
return ESP_FAIL;
}
return ESP_OK;
}
esp_err_t bootloader_check_bootloader_validity(void)
{
/* read chip revision from efuse */
uint8_t revision = bootloader_common_get_chip_revision();
ESP_LOGI(TAG, "chip revision: %d", revision);
/* compare with the one set in bootloader image header */
if (bootloader_common_check_chip_validity(&bootloader_image_hdr, ESP_IMAGE_BOOTLOADER) != ESP_OK) {
return ESP_FAIL;
}
return ESP_OK;
}
void bootloader_config_wdt(void)
{
#ifdef CONFIG_BOOTLOADER_WDT_ENABLE
ESP_LOGD(TAG, "Enabling RTCWDT(%d ms)", CONFIG_BOOTLOADER_WDT_TIME_MS);
rtc_wdt_protect_off();
rtc_wdt_disable();
rtc_wdt_set_length_of_reset_signal(RTC_WDT_SYS_RESET_SIG, RTC_WDT_LENGTH_3_2us);
rtc_wdt_set_length_of_reset_signal(RTC_WDT_CPU_RESET_SIG, RTC_WDT_LENGTH_3_2us);
rtc_wdt_set_stage(RTC_WDT_STAGE0, RTC_WDT_STAGE_ACTION_RESET_RTC);
rtc_wdt_set_time(RTC_WDT_STAGE0, CONFIG_BOOTLOADER_WDT_TIME_MS);
rtc_wdt_enable();
rtc_wdt_protect_on();
#else /* disable watch dog */
rtc_wdt_disable();
#endif
timer_ll_wdt_set_protect(&TIMERG0, false);
timer_ll_wdt_flashboot_en(&TIMERG0, false);
}
void bootloader_enable_random(void)
{
ESP_LOGI(TAG, "Enabling RNG early entropy source...");
bootloader_random_enable();
}
void bootloader_print_banner(void)
{
ESP_LOGI(TAG, "ESP-IDF %s 2nd stage bootloader", IDF_VER);
ESP_LOGI(TAG, "compile time " __TIME__);
}
void __assert_func(const char *file, int line, const char *func, const char *expr)
{
ESP_LOGE(TAG, "Assert failed in %s, %s:%d (%s)", func, file, line, expr);
while (1) {
}
}
|
angelopassaro/Hacktoberfest-1
|
misc/java/game.java
|
<filename>misc/java/game.java
package com.quizapplication;
public class Game {
Question[] questions=new Question[3];
Player player=new Player();
String[] questionsdata={"JAVA was created by _____?","What technology is used to record cryptocurrency transactions?","What tool would you use to reduce the digital image size?"};
String[] options1={"<NAME>","Digital wallet","Filter"};
String[] options2={"<NAME>","Mining","Brush"};
String[] options3={"<NAME>","Blockchain","Rotate"};
String[] options4={"<NAME>","Token","Crop"};
int[] answers={2,3,4};
public void initGame() {
for(int i=0;i<3;i++) {
questions[i]=new Question();
}
for(int i=0;i<3;i++) {
questions[i].question=questionsdata[i];
questions[i].option1=options1[i];
questions[i].option2=options2[i];
questions[i].option3=options3[i];
questions[i].option4=options4[i];
questions[i].correctAnswer=answers[i];
}
}
public void play() {
player.getDetails();
for(int i=0;i<3;i++) {
boolean status=questions[i].askQuestion();
if(status==true) {
System.out.println("WOW! It's Correct Answer...!");
player.score=player.score+5;
}
else {
System.out.println("OOPS! It's Wrong Answer...!");
player.score=player.score-5;
}
}
System.out.println(player.name+" Your Score is : "+player.score);
}
}
|
hmhao/avalonx
|
examples/shopping-cart/app.js
|
<gh_stars>1-10
import avalon from '../avalon.extend.js'
import App from './components/App.js'
import store from './store'
import { currency } from './currency'
avalon.filters['currency'] = currency
avalon.bootstrap({
el: '#app',
component: App
})
|
gfogle/boring-framework
|
test/helpers/NounHelper.test.js
|
<gh_stars>1-10
const NounHelper = require("../../src/core/helpers/NounHelper");
test("pluralizes BlogPost to BlogPosts", () => {
expect(NounHelper.getPluralForm("BlogPost")).toBe("BlogPosts");
});
test("singularizes BlogPosts to BlogPost", () => {
expect(NounHelper.getSingularForm("BlogPosts")).toBe("BlogPost");
});
test("converts BlogPost to blog_post", () => {
expect(NounHelper.toSingularResource("BlogPost")).toBe("blog_post");
});
test("converts BlogPosts to blog_post", () => {
expect(NounHelper.toSingularResource("BlogPosts")).toBe("blog_post");
});
test("converts BlogPost to blog_posts", () => {
expect(NounHelper.toPluralResource("BlogPost")).toBe("blog_posts");
});
test("converts BlogPosts to blog_posts", () => {
expect(NounHelper.toPluralResource("BlogPost")).toBe("blog_posts");
});
test("converts BlogPost to blogPost", () => {
expect(NounHelper.getCamelCaseSingularForm("BlogPost")).toBe("blogPost");
});
|
magicbrush/InteractiveMediaP5
|
Fractals/Demo6_TRS/sketch.js
|
var Shapes;// 一组图元
// 函数setup() :准备阶段
function setup()
{
createCanvas(300,300);
Shapes = new Array();// 一个序列容器
Shapes[0] = new sprite(
primitive1,width/2,height/2,PI/3,2,2);
for(var i=0;i<5;i++)
{
Shapes = evolveShapes(Shapes);
}
}
function evolveShapes(S)
{
var S2 = new Array();
for(var i=0;i<S.length;i++)
{
var cnt= round(random(3,6));
for(k=0;k<cnt;k++)
{
S2.push(S[i].regen());
}
}
for(var j=0;j<S2.length;j++)
{
S.push(S2[j]);
}
return S;
}
// 函数draw():作画阶段
function draw() {
//fill(255,255,255,1);
//rect(-10,-10,2*width,2*height);
for(var i=0;i<Shapes.length;i++)
{
Shapes[i].draw();
}
}
function sprite(primitive,x,y,rot,sx,sy)
{
this.primitive = primitive;
this.x= x;
this.y = y;
this.rot = rot;
this.sx = sx;
this.sy = sy;
this.draw = function()
{
push();
translate(this.x,this.y);
rotate(this.rot);
scale(this.sx,this.sy);
this.primitive();
pop();
}
this.regen = function()
{
var x = this.x+random(-50,50)*this.sx;
var y = this.y+random(-50,50)*this.sy;
var rot = this.rot+random(-0.3,0.3);
var sx = this.sx*random(0.3,0.8);
var sy = this.sy *random(0.3,0.8);
var r = random(0,1);
var p = primitive0;
if(r>0.7)
{
p = primitive1;
}
var childSprite =
new sprite(p,x,y,rot,sx,sy);
return childSprite;
}
}
function primitive0()
{
ellipse(0,0,100,100);
}
function primitive1()
{
rect(-40,-40,80,80);
}
function randColor()
{
var cr = color(
random(0,255),random(0,255),random(0,255));
return cr;
}
|
ministryofjustice/laa-court-data-adaptor
|
app/serializers/api/internal/v1/court_application_type_serializer.rb
|
<filename>app/serializers/api/internal/v1/court_application_type_serializer.rb
module Api
module Internal
module V1
class CourtApplicationTypeSerializer
include JSONAPI::Serializer
attributes :id, :description, :code, :category_code, :legislation, :applicant_appellant_flag
end
end
end
end
|
cndavy/docker-office
|
custom_apps/richdocuments/l10n/cs.js
|
OC.L10N.register(
"richdocuments",
{
"Collabora Online" : "Collabora Online",
"Can't create document" : "Dokument se nedaří vytvořit",
"New Document.odt" : "Dokument.odt",
"New Spreadsheet.ods" : "Tabulka.ods",
"New Presentation.odp" : "Prezentace.odp",
"New Document.docx" : "novy_dokument.docx",
"New Spreadsheet.xlsx" : "Tabulka.xlsx",
"New Presentation.pptx" : "nova_prezentace.pptx",
"Document already exists" : "Dokument už existuje",
"Not allowed to create document" : "Nemáte oprávnění k vytvoření dokumentu",
"Saved" : "Uloženo",
"Saved with error: Collabora Online should use the same protocol as the server installation." : "Uloženo s chybou: Collabora Online by mělo používat stejný protokol jako instalovaný server.",
"Invalid config key" : "Neplatný klíč nastavení",
"Error when saving" : "Chyba při ukládání",
"File is too big" : "Soubor je příliš velký",
"Only template files can be uploaded" : "Je možné nahrávat pouze soubory se šablonami",
"Invalid file provided" : "Poskytnut neplatný soubor",
"Template not found" : "Šablona nenalezena",
"Empty" : "Prázdná",
"%s (Guest)" : "%s (host)",
"Anonymous guest" : "Anonymní host",
"Edit office documents directly in your browser." : "Upravujte dokumenty přímo ve webovém prohlížeči.",
"This application can connect to a Collabora Online (or other) server (WOPI-like Client). Nextcloud is the WOPI Host. Please read the documentation to learn more about that.\n\nYou can also edit your documents off-line with the Collabora Office app from the **[Android](https://play.google.com/store/apps/details?id=com.collabora.libreoffice)** and **[iOS](https://apps.apple.com/us/app/collabora-office/id1440482071)** store." : "Tato aplikace se může připojit ke Collabora Online (nebo jinému) serveru (klient WOPI). Nextcloud je WOPI hostitel. Další informace naleznete v dokumentaci.\n\nSvé dokumenty můžete upravovat i bez připojení k Intenetu v aplikaci Collabora Office z **[Android](https://play.google.com/store/apps/details?id=com.collabora.libreoffice)** a **[iOS](https://apps.apple.com/us/app/collabora-office/id1440482071)** katalogu aplikací.",
"Collabora Online is a powerful LibreOffice-based online office suite with collaborative editing, which supports all major documents, spreadsheet and presentation file formats and works together with all modern browsers." : "Collabora Online je všestranný online kancelářský balík pro spolupráci více uživatelů, založený na Libre Office. Podporuje všechny hlavní souborové formáty dokumentů, tabulek a prezentací a funguje ve všech moderních webových prohlížečích.",
"Could not establish connection to the Collabora Online server." : "Nedaří se navázat spojení s Collabora Online serverem.",
"Setting up a new server" : "Nastavit nový server",
"Collabora Online server is reachable." : "Server s Collabora Online je dosažitelný.",
"Please configure a Collabora Online server to start editing documents" : "Aby bylo možné upravovat dokumenty, nastavte Collabora Online server",
"Use your own server" : "Použít váš vlastní server",
"Collabora Online requires a seperate server acting as a WOPI-like Client to provide editing capabilities." : "Collabora Online potřebuje zvlášť server sloužící jako WOPI klient, poskytující možnosti upravování.",
"URL (and Port) of Collabora Online-server" : "URL adresa (včetně portu) serveru Collabora Online",
"Disable certificate verification (insecure)" : "Neověřovat certifikát (nezabezpečené)",
"Use a demo server" : "Použít demo server",
"You can use a demo server provided by Collabora and other service providers for giving Collabora Online a try." : "Můžete využít demo server provozovaný Collabora a dalšími poskytovateli služeb a vyzkoušet si tak Collabora Online.",
"Loading available demo servers …" : "Načítání dostupných demo serverů…",
"No available demo servers found." : "Nejsou k dispozici žádné demo servery.",
"Documents opened with the demo server configured will be sent to a 3rd party server. Only use this for evaluating Collabora Online." : "Dokumenty otevřené pomocí nastaveného demo serveru budou odeslány třetí straně. Toto použijte pouze pro vyzkoušení Collabora Online.",
"Advanced settings" : "Pokročilá nastavení",
"Use Office Open XML (OOXML) instead of OpenDocument Format (ODF) by default for new files" : "Použít pro nové soubory jako výchozí Office Open XML (OOXML) namísto OpenDocument Format (ODF)",
"Restrict usage to specific groups" : "Omezit použití na konkrétní skupiny",
"Collabora Online is enabled for all users by default. When this setting is active, only members of the specified groups can use it." : "Ve výchozím stavu je Collabora Online zapnuté pro všechny uživatele. Pokud je toto nastavení aktivní, mohou Collabora Online používat jen členové zadaných skupin.",
"Select groups" : "Vyberte skupiny",
"Restrict edit to specific groups" : "Omezit úpravy pro konkrétní skupiny",
"Use Canonical webroot" : "Použít úplný popis umístění kořene webu",
"Canonical webroot, in case there are multiple, for Collabora to use. Provide the one with least restrictions. Eg: Use non-shibbolized webroot if this instance is accessed by both shibbolized and non-shibbolized webroots. You can ignore this setting if only one webroot is used to access this instance." : "Úplný popis umístění kořene webu, kterou má Collabora použít v případě, že je jich více. Použijte tu s nejméně omezeními. Např. použijte popis umístění kořene bez podpory Shibboleth pokud tato instance podporuje oba přístupy. Tuto volbu můžete ignorovat v případě, že existuje pouze jedna kořenová složka pro přístup.",
"Enable access for external apps" : "Povolit přístup pro externí aplikace",
"Secure view settings" : "Nastavení zabezpečeného zobrazení",
"Secure view enables you to secure documents by embedding a watermark" : "Zabezpečené zobrazení umožňuje zabezpečit dokumenty vložením vodoznaku",
"Enable watermarking" : "Zapnout opatřování vodoznaky",
"Supported placeholders: {userId}, {date}" : "Podporované výplně: {userId}, {date}",
"Show watermark on tagged files" : "Zobrazovat vodoznaky na souborech, označených štítky",
"Select tags to enforce watermarking" : "Vyberte štítky, pro které vynucovat vodoznaky",
"Show watermark for users of groups" : "Zobrazovat vodoznak pro uživatele skupin",
"Show watermark for all shares" : "Zobrazovat vodoznak pro všechna sdílení",
"Show watermark for read only shares" : "Zobrazovat vodoznak pro sdílení, která jsou pouze pro čtení",
"Show watermark for all link shares" : "Zobrazovat vodoznak pro všechna sdílení odkazem",
"Show watermark for download hidden shares" : "Zobrazovat vodoznak pro stahování ze skrytých sdílení",
"Show watermark for read only link shares" : "Zobrazovat vodoznak pro sdílení odkazem, která jsou pouze pro čtení",
"Show watermark on link shares with specific system tags" : "Zobrazovat vodoznak na sdíleních odkazem, která jsou opatřena konkrétními systémovými štítky",
"Contact {0} to get an own installation." : "Pro získání vlastní instalace se obraťte na {0}.",
"Failed to save settings" : "Nastavení se nepodařilo uložit",
"Description" : "Popis",
"Add new token" : "Přidat nový token",
"No results" : "Žádné výsledky",
"Error" : "Chyba",
"An error occurred" : "Došlo k chybě",
"Please choose your nickname to continue as guest user." : "Zvolte si svou přezdívku a pokračujte jako host.",
"Nickname" : "Přezdívka",
"Set" : "Nastavit",
"Close version preview" : "Zavřít náhled verze",
"Please enter the filename to store the document as." : "Zadejte název souboru ve kterém dokument uchovávat.",
"Save As" : "Uložit jako",
"New filename" : "Název souboru",
"Cancel" : "Storno",
"Save" : "Uložit",
"Select a personal template folder" : "Vyberte složku s osobní šablonou",
"Saving…" : "Ukládání…",
"Insert from {name}" : "Vložit z {name}",
"Remove from favorites" : "Odebrat z oblíbených",
"Add to favorites" : "Přidat do oblíbených",
"Details" : "Podrobnosti",
"Download" : "Stáhnout",
"(read only)" : "(pouze pro čtení)",
"Guest" : "Host",
"Follow current editor" : "Následovat stávající editor",
"Last saved version" : "Poslední uložená verze",
"Current version" : "Stávající verze",
"Failed to revert the document to older version" : "Nepodařilo se vrátit dokument do podoby starší verze",
"Please enter the filename for the new document" : "Zadejte název souboru pro nový dokument",
"Create a new document" : "Vytvořit nový dokument",
"Edit with {productName}" : "Upravit pomocí {productName}",
"Failed to load {productName} - please try again later" : "Nepodařilo se načíst {productName} – zkuste to prosím znovu později.",
"New Document" : "Nový dokument",
"New Spreadsheet" : "Nová tabulka",
"New Presentation" : "Nová prezentace",
"Could not create file" : "Nepodařilo se vytvořit soubor",
"Create" : "Vytvořit",
"Select template" : "Vybrat šablonu",
"Failed to connect to {productName}. Please try again later or contact your server administrator." : "Nepodařilo se připojit k {productName}. Zkuste to prosím znovu později nebo se obraťte na správce serveru.",
"Global templates" : "Globální šablony",
"Add a new template" : "Přidat novou šablonu",
"No templates defined." : "Nebyla určena žádná šablona.",
"Add a new one?" : "Přidat novou?",
"template preview" : "náhled šablony",
"Select a template directory" : "Vyberte adresář se šablonou",
"Remove personal template folder" : "Odebrat složku s osobní šablonou",
"Templates inside of this directory will be added to the template selector of Collabora Online." : "Šablony nacházející se v tomto adresáři budou přidány do výběru šablon v Collabora Online.",
"Wrong password. Please retry." : "Nesprávné heslo. Zkuste to znovu.",
"Password" : "<PASSWORD>",
"OK" : "OK",
"Guest %s" : "Host %s",
"This link has been expired or is never existed. Please contact the person who shared it with you for details." : "Platnost tohoto odkazu skončila nebo nikdy neexistoval. Pro podrobnosti se obraťte na osobu, která vám ho nasdílela."
},
"nplurals=4; plural=(n == 1 && n % 1 == 0) ? 0 : (n >= 2 && n <= 4 && n % 1 == 0) ? 1: (n % 1 != 0 ) ? 2 : 3;");
|
medmedCH/Quizard
|
backend/routes/Quizzs.js
|
const express = require('express')
const router = express.Router()
let Quizze = require('../models/Quizz');
const { check, validationResult } = require('express-validator');
// get all quiz questions
router.get('/quizz', (req, res) => {
Quizze.find()
.then(quizzs => res.json(quizzs))
.catch(err=> res.status(400).json('error:'+err));
})
// get one quiz question
router.get('/quizz/:id', (req, res) => {
Quizze.findById(req.params.id)
.then(quizzs => res.json(quizzs ))
.catch(err => res.status(400).json('Error: ' + err));
})
router.get('/quizzcode/:code', (req, res) => {
Quizze.findOne({code:req.params.code})
.then(quizzs => {
if(quizzs===null)
{
return res.status(400).json('error')
}
res.json(quizzs)
})
.catch(err => res.status(400).json('Error: ' + err));
})
// create one quiz question
router.post('/quizz', (req, res) => {
let r = Math.random().toString(36).substring(7);
const code = r;
const name = req.body.name;
const classe = req.body.classe;
const Question = req.body.Question;
const Timer = Number(req.body.Timer);
const Quizz = new Quizze ({
name,
code,
classe,
Question,
Timer
})
Quizz.save()
.then(() => res.json(Quizz))
.catch(err => res.status(400).json('Error:' + err));
})
// update one quiz question
router.put('/Quizz/:id', (req, res) => {
Quizze.findById(req.params.id)
.then(quizz => {
quizz.name = req.body.name;
quizz.classe = req.body.classe;
quizz.Question = req.body.question;
quizz.Timer = Number(req.body.Timer);
quizz.save()
.then(() => res.json('quizz updated!'))
.catch(err => res.status(400).json('Error: ' + err));
})
.catch(err => res.status(400).json('Error: ' + err));
})
// delete one quiz question
router.delete('/quizz/:id', (req, res) => {
Quizze.findByIdAndDelete(req.params.id)
.then(() => res.json('quizz deleted.'))
.catch(err => res.status(400).json('Error: ' + err));
})
// this one is just a test
router.get('/', (req, res) => {
res.send('H3ll0 W0RlD')
})
module.exports = router
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.