max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
575 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/network/public/cpp/optional_trust_token_params.h"
namespace network {
OptionalTrustTokenParams::OptionalTrustTokenParams() = default;
OptionalTrustTokenParams::OptionalTrustTokenParams(base::nullopt_t) {}
OptionalTrustTokenParams::OptionalTrustTokenParams(
mojom::TrustTokenParamsPtr ptr)
: ptr_(std::move(ptr)) {}
OptionalTrustTokenParams::OptionalTrustTokenParams(
const mojom::TrustTokenParams& params)
: ptr_(params.Clone()) {}
OptionalTrustTokenParams::OptionalTrustTokenParams(
const OptionalTrustTokenParams& other) {
ptr_ = other.as_ptr().Clone();
}
OptionalTrustTokenParams& OptionalTrustTokenParams::operator=(
const OptionalTrustTokenParams& other) {
ptr_ = other.as_ptr().Clone();
return *this;
}
OptionalTrustTokenParams::OptionalTrustTokenParams(
OptionalTrustTokenParams&& other) = default;
OptionalTrustTokenParams& OptionalTrustTokenParams::operator=(
OptionalTrustTokenParams&& other) = default;
OptionalTrustTokenParams::~OptionalTrustTokenParams() = default;
bool OptionalTrustTokenParams::operator==(
const OptionalTrustTokenParams& other) const {
return mojo::Equals(ptr_, other.ptr_);
}
} // namespace network
| 413 |
381 | package org.apache.helix.model.builder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.helix.model.Transition;
public class StateTransitionTableBuilder {
// for convenient get path value, in which non-exist means MAX
static int getPathVal(Map<String, Map<String, Integer>> path, String fromState, String toState) {
if (!path.containsKey(fromState)) {
return Integer.MAX_VALUE;
}
if (!(path.get(fromState).containsKey(toState))) {
return Integer.MAX_VALUE;
}
return path.get(fromState).get(toState);
}
static void setPathVal(Map<String, Map<String, Integer>> path, String fromState, String toState,
int val) {
if (!path.containsKey(fromState)) {
path.put(fromState, new HashMap<String, Integer>());
}
path.get(fromState).put(toState, val);
}
static void setNext(Map<String, Map<String, String>> next, String fromState, String toState,
String nextState) {
if (!next.containsKey(fromState)) {
next.put(fromState, new HashMap<String, String>());
}
next.get(fromState).put(toState, nextState);
}
/**
* auxiliary method to get next state based on next map
* @param next
* @param fromState
* @param toState
* @return nextState or null if doesn't exist a path
*/
public static String getNext(Map<String, Map<String, String>> next, String fromState,
String toState) {
if (!next.containsKey(fromState)) {
// no path
return null;
}
return next.get(fromState).get(toState);
}
// debug
static void printPath(List<String> states, Map<String, Map<String, String>> next) {
for (String fromState : states) {
for (String toState : states) {
if (toState.equals(fromState)) {
// not print self-loop
continue;
}
System.out.print(fromState);
String nextState = getNext(next, fromState, toState);
while (nextState != null && !nextState.equals(toState)) {
System.out.print("->" + nextState);
nextState = getNext(next, nextState, toState);
}
if (nextState == null) {
// no path between fromState -> toState
System.out.println("->null" + toState + " (no path avaliable)");
} else {
System.out.println("->" + toState);
}
}
}
}
/**
* Uses floyd-warshall algorithm, shortest distance for all pair of nodes
* Allows one to lookup nextState given fromState,toState <br/>
* map.get(fromState).get(toState) --> nextState
* @param states
* @param transitions
* @return next map
*/
public Map<String, Map<String, String>> buildTransitionTable(List<String> states,
List<Transition> transitions) {
// path distance value
Map<String, Map<String, Integer>> path = new HashMap<String, Map<String, Integer>>();
// next state
Map<String, Map<String, String>> next = new HashMap<String, Map<String, String>>();
// init path and next
for (String state : states) {
setPathVal(path, state, state, 0);
setNext(next, state, state, state);
}
for (Transition transition : transitions) {
String fromState = transition.getFromState();
String toState = transition.getToState();
setPathVal(path, fromState, toState, 1);
setNext(next, fromState, toState, toState);
}
// iterate
for (String intermediateState : states) {
for (String fromState : states) {
for (String toState : states) {
int pathVal1 = getPathVal(path, fromState, intermediateState);
int pathVal2 = getPathVal(path, intermediateState, toState);
int pathValCur = getPathVal(path, fromState, toState);
// should not overflow
if (pathVal1 < Integer.MAX_VALUE && pathVal2 < Integer.MAX_VALUE
&& (pathVal1 + pathVal2) < pathValCur) {
setPathVal(path, fromState, toState, pathVal1 + pathVal2);
setNext(next, fromState, toState, getNext(next, fromState, intermediateState));
}
}
}
}
return next;
}
// TODO move this to test
public static void main(String[] args) {
List<String> states = new ArrayList<String>();
// [MASTER, SLAVE, DROPPED, OFFLINE]
// [SLAVE-OFFLINE, OFFLINE-SLAVE, SLAVE-MASTER, OFFLINE-DROPPED, MASTER-SLAVE]
states.add("MASTER");
states.add("SLAVE");
states.add("DROPPED");
states.add("OFFLINE");
List<Transition> transitions = new ArrayList<Transition>();
transitions.add(new Transition("SLAVE", "OFFLINE"));
transitions.add(new Transition("OFFLINE", "SLAVE"));
transitions.add(new Transition("SLAVE", "MASTER"));
transitions.add(new Transition("OFFLINE", "DROPPED"));
transitions.add(new Transition("MASTER", "SLAVE"));
StateTransitionTableBuilder builder = new StateTransitionTableBuilder();
Map<String, Map<String, String>> next = builder.buildTransitionTable(states, transitions);
System.out.println(next);
printPath(states, next);
}
}
| 2,143 |
422 | <filename>src/com/ansorgit/plugins/bash/lang/psi/impl/vars/BashVarDefImpl.java
/*
* Copyright (c) <NAME>, <EMAIL>
*
* 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.ansorgit.plugins.bash.lang.psi.impl.vars;
import com.ansorgit.plugins.bash.lang.LanguageBuiltins;
import com.ansorgit.plugins.bash.lang.lexer.BashTokenTypes;
import com.ansorgit.plugins.bash.lang.psi.BashVisitor;
import com.ansorgit.plugins.bash.lang.psi.api.BashCharSequence;
import com.ansorgit.plugins.bash.lang.psi.api.BashPsiElement;
import com.ansorgit.plugins.bash.lang.psi.api.BashReference;
import com.ansorgit.plugins.bash.lang.psi.api.BashString;
import com.ansorgit.plugins.bash.lang.psi.api.command.BashCommand;
import com.ansorgit.plugins.bash.lang.psi.api.function.BashFunctionDef;
import com.ansorgit.plugins.bash.lang.psi.api.vars.BashAssignmentList;
import com.ansorgit.plugins.bash.lang.psi.api.vars.BashVar;
import com.ansorgit.plugins.bash.lang.psi.api.vars.BashVarDef;
import com.ansorgit.plugins.bash.lang.psi.impl.BashBaseStubElementImpl;
import com.ansorgit.plugins.bash.lang.psi.impl.BashElementSharedImpl;
import com.ansorgit.plugins.bash.lang.psi.stubs.api.BashVarDefStub;
import com.ansorgit.plugins.bash.lang.psi.util.BashCommandUtil;
import com.ansorgit.plugins.bash.lang.psi.util.BashIdentifierUtil;
import com.ansorgit.plugins.bash.lang.psi.util.BashPsiElementFactory;
import com.ansorgit.plugins.bash.lang.psi.util.BashPsiUtils;
import com.ansorgit.plugins.bash.settings.BashProjectSettings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static com.ansorgit.plugins.bash.lang.LanguageBuiltins.*;
/**
* @author jansorg
*/
public class BashVarDefImpl extends BashBaseStubElementImpl<BashVarDefStub> implements BashVarDef, BashVar, StubBasedPsiElement<BashVarDefStub> {
private static final TokenSet accepted = TokenSet.create(BashTokenTypes.WORD, BashTokenTypes.ASSIGNMENT_WORD);
private static final Set<String> commandsWithReadonlyOption = Sets.newHashSet("declare", "typeset", "local");
private static final Set<String> commandsWithArrayOption = Sets.newHashSet("declare", "typeset", "read", "local");
private static final Set<String> localVarDefCommands = commandsWithArrayOption; // Sets.newHashSet("declare", "typeset");
private static final Set<String> typeArrayDeclarationParams = Collections.singleton("-a");
private static final Set<String> typeReadOnlyParams = Collections.singleton("-r");
private final BashReference reference = new SmartVarDefReference(this);
private final BashReference dumbReference = new DumbVarDefReference(this);
private final Object stateLock = new Object();
private volatile Boolean cachedFunctionScopeLocal;
private volatile String name;
private volatile PsiElement assignmentWord;
private volatile TextRange nameTextRange;
public BashVarDefImpl(ASTNode astNode) {
super(astNode, "Bash var def");
}
public BashVarDefImpl(@NotNull BashVarDefStub stub, @NotNull IStubElementType nodeType) {
super(stub, nodeType, "Bash var def");
}
@Override
public void subtreeChanged() {
super.subtreeChanged();
synchronized (stateLock) {
this.cachedFunctionScopeLocal = null;
this.name = null;
this.assignmentWord = null;
this.nameTextRange = null;
}
}
public String getName() {
BashVarDefStub stub = getStub();
if (stub != null) {
return stub.getName();
}
if (name == null) {
//no other lock is used in the callees, it's safe to synchronize around the whole calculation
synchronized (stateLock) {
if (name == null) {
PsiElement element = findAssignmentWord();
String newName;
if (element instanceof BashCharSequence) {
newName = ((BashCharSequence) element).getUnwrappedCharSequence();
} else {
newName = element.getText();
}
name = newName;
}
}
}
return name;
}
public PsiElement setName(@NotNull @NonNls String newName) throws IncorrectOperationException {
if (!BashIdentifierUtil.isValidNewVariableName(newName)) {
throw new IncorrectOperationException("Invalid variable name");
}
PsiElement original = findAssignmentWord();
PsiElement replacement = BashPsiElementFactory.createAssignmentWord(getProject(), newName);
return BashPsiUtils.replaceElement(original, replacement);
}
public boolean isArray() {
//a variable can be declared as array variable in different ways:
// - using an array assignment a=(one two)
// - using declare -a
// - using typeset -a
// - using mapfile/readarray
// - using read -a
// - using local -a
PsiElement assignmentValue = findAssignmentValue();
//check if we have an array assignment part
if (assignmentValue instanceof BashAssignmentList) {
return true;
}
//check for declare -a or typeset -a
PsiElement parentElement = getParent();
if (parentElement instanceof BashCommand) {
BashCommand command = (BashCommand) parentElement;
return "mapfile".equals(command.getReferencedCommandName())
|| "readarray".equals(command.getReferencedCommandName())
|| isCommandWithParameter(command, commandsWithArrayOption, typeArrayDeclarationParams);
}
return false;
}
/**
* Returns either a assignment word element or a array assignment word.
*
* @return The element which represents the left part of the assignment.
*/
@NotNull
public PsiElement findAssignmentWord() {
if (assignmentWord == null) {
//no other lock is used in the callees, it's safe to synchronize around the whole calculation
synchronized (stateLock) {
if (assignmentWord == null) {
PsiElement element = findChildByType(accepted);
PsiElement newAssignmentWord;
if (element != null) {
newAssignmentWord = element;
} else {
//if null we probably represent a single var without assignment, i.e. the var node is nested inside of
//a parsed var
PsiElement firstChild = getFirstChild();
ASTNode childNode = firstChild != null ? firstChild.getNode() : null;
ASTNode node = childNode != null ? childNode.findChildByType(accepted) : null;
newAssignmentWord = (node != null) ? node.getPsi() : firstChild;
}
assignmentWord = newAssignmentWord;
}
}
}
return assignmentWord;
}
@Nullable
public PsiElement findAssignmentValue() {
PsiElement last = getLastChild();
return last != this ? last : null;
}
public boolean isFunctionScopeLocal() {
if (cachedFunctionScopeLocal == null) {
boolean newCachedFunctionScopeLocal = doIsFunctionScopeLocal();
synchronized (stateLock) {
cachedFunctionScopeLocal = newCachedFunctionScopeLocal;
}
}
return cachedFunctionScopeLocal;
}
private boolean doIsFunctionScopeLocal() {
if (isLocalVarDef()) {
return true;
}
//Although this variable has no direct local command,
//it's still possible that an earlier usage of the local command declared this
//variable as function local
//
//Solve this by using stubs and index and without a processor to prevent SOE in other processors using this function
//filter all variable definitions which are included in the broadest function scope, all others are out of scope
//then iterate and break if there is one def which is local and which occurs before this element
//fixme handle injected code in functions
BashFunctionDef scope = BashPsiUtils.findNextVarDefFunctionDefScope(this);
while (scope != null) {
if (scope.findLocalScopeVariables().contains(getReferenceName())) {
return true;
}
scope = BashPsiUtils.findNextVarDefFunctionDefScope(PsiTreeUtil.getStubOrPsiParent(scope));
}
return false;
}
public boolean isLocalVarDef() {
//check if the command is a local-var defining command, e.g. local
final PsiElement context = getContext();
if (context instanceof BashCommand) {
final BashCommand parentCmd = (BashCommand) context;
String commandName = parentCmd.getReferencedCommandName();
//declared by "local"
if (parentCmd.isVarDefCommand() && LanguageBuiltins.localVarDefCommands.contains(commandName)) {
return true;
}
//declared by either delcare or typeset in a function block
if (localVarDefCommands.contains(commandName) && BashPsiUtils.findNextVarDefFunctionDefScope(context) != null) {
return true;
}
}
return false;
}
public boolean hasAssignmentValue() {
return findAssignmentValue() != null;
}
public boolean isCommandLocal() {
final PsiElement context = getContext();
if (context instanceof BashCommand) {
final BashCommand parentCmd = (BashCommand) context;
return !parentCmd.isPureAssignment() && !parentCmd.isVarDefCommand();
}
return false;
}
@Override
public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
@NotNull ResolveState resolveState,
PsiElement lastParent,
@NotNull PsiElement place) {
if (!processor.execute(this, resolveState)) {
return false;
}
return BashElementSharedImpl.walkDefinitionScope(this, processor, resolveState, lastParent, place);
}
public PsiElement getNameIdentifier() {
return findAssignmentWord();
}
public final String getReferenceName() {
return getName();
}
public PsiElement getElement() {
return this;
}
@NotNull
@Override
public BashReference getReference() {
return DumbService.isDumb(getProject()) ? dumbReference : reference;
}
@Nullable
@Override
public BashReference getNeighborhoodReference() {
return null;
}
@Override
public final boolean isVarDefinition() {
return true;
}
@Override
public int getPrefixLength() {
return 0;
}
@Override
public boolean isStaticAssignmentWord() {
PsiElement word = findAssignmentWord();
if (word instanceof BashCharSequence) {
return ((BashCharSequence) word).isStatic();
}
return true;
}
public BashFunctionDef findFunctionScope() {
return PsiTreeUtil.getStubOrPsiParentOfType(this, BashFunctionDef.class);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof BashVisitor) {
((BashVisitor) visitor).visitVarDef(this);
} else {
visitor.visitElement(this);
}
}
public boolean isBuiltinVar() {
boolean isBash_v4 = BashProjectSettings.storedSettings(getProject()).isSupportBash4();
String varName = getReferenceName();
boolean v3_var = bashShellVars.contains(varName) || bourneShellVars.contains(varName);
return isBash_v4 ? (v3_var || bashShellVars_v4.contains(varName)) : v3_var;
}
public boolean isParameterExpansion() {
return false;
}
public boolean isParameterReference() {
return false;
}
public boolean isArrayUse() {
return false;
}
public TextRange getAssignmentNameTextRange() {
if (nameTextRange == null) {
synchronized (stateLock) {
if (nameTextRange == null) {
PsiElement wordElement = findAssignmentWord();
TextRange newNameTextRange;
if (wordElement instanceof BashCharSequence) {
newNameTextRange = ((BashCharSequence) wordElement).getTextContentRange();
} else {
newNameTextRange = TextRange.from(0, wordElement.getTextLength());
}
nameTextRange = newNameTextRange;
}
}
}
return nameTextRange;
}
public boolean isReadonly() {
PsiElement context = getParent();
if (context instanceof BashCommand) {
BashCommand command = (BashCommand) context;
if (command.isInternalCommand() && LanguageBuiltins.readonlyVarDefCommands.contains(command.getReferencedCommandName())) {
return true;
}
//check for declare -r or typeset -r
if (isCommandWithParameter(command, commandsWithReadonlyOption, typeReadOnlyParams)) {
return true;
}
}
return false;
}
private boolean isCommandWithParameter(BashCommand command, Set<String> validCommands, Set<String> validParams) {
String commandName = command.getReferencedCommandName();
if (commandName != null && validCommands.contains(commandName)) {
List<BashPsiElement> parameters = Lists.newArrayList(command.parameters());
for (BashPsiElement argValue : parameters) {
for (String paramName : validParams) {
if (BashCommandUtil.isParameterDefined(paramName, argValue.getText())) {
return true;
}
}
}
}
return false;
}
@Nullable
public List<PsiComment> findAttachedComment() {
return BashPsiUtils.findDocumentationElementComments(this);
}
}
| 6,344 |
400 | <gh_stars>100-1000
/*
* gl_copy_handler.cpp - gl copy handler implementation
*
* Copyright (c) 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: <NAME> <<EMAIL>>
*/
#include "gl_copy_handler.h"
#include "gl_utils.h"
#include "gl_sync.h"
#define INVALID_INDEX (uint32_t)(-1)
namespace XCam {
const GLShaderInfo shader_info = {
GL_COMPUTE_SHADER,
"shader_copy",
#include "shader_copy.comp.slx"
, 0
};
GLCopyHandler::GLCopyHandler (const char *name)
: GLImageHandler (name)
, _index (INVALID_INDEX)
{
}
XCamReturn
GLCopyHandler::copy (const SmartPtr<VideoBuffer> &in_buf, SmartPtr<VideoBuffer> &out_buf)
{
SmartPtr<ImageHandler::Parameters> param = new ImageHandler::Parameters (in_buf, out_buf);
XCAM_ASSERT (param.ptr ());
XCamReturn ret = execute_buffer (param, false);
XCAM_FAIL_RETURN (ERROR, xcam_ret_is_ok (ret), ret, "gl-copy execute copy failed");
GLSync::flush ();
if (!out_buf.ptr ()) {
out_buf = param->out_buf;
}
return ret;
}
bool
GLCopyHandler::set_copy_area (uint32_t idx, const Rect &in_area, const Rect &out_area)
{
XCAM_FAIL_RETURN (
ERROR,
idx != INVALID_INDEX &&
in_area.width == out_area.width && in_area.height == out_area.height,
false,
"gl-copy set copy area failed, idx: %d, input size: %dx%d, output size: %dx%d",
idx, in_area.width, in_area.height, out_area.width, out_area.height);
_index = idx;
_in_area = in_area;
_out_area = out_area;
XCAM_LOG_DEBUG (
"gl-copy set copy area, idx: %d, input area: %d, %d, %d, %d, output area: %d, %d, %d, %d",
idx,
in_area.pos_x, in_area.pos_y, in_area.width, in_area.height,
out_area.pos_x, out_area.pos_y, out_area.width, out_area.height);
return true;
}
XCamReturn
GLCopyHandler::fix_parameters (const SmartPtr<Parameters> ¶m)
{
const VideoBufferInfo &in_info = param->in_buf->get_video_info ();
const VideoBufferInfo &out_info =
param->out_buf.ptr () ? param->out_buf->get_video_info () : get_out_video_info ();
XCAM_FAIL_RETURN (
ERROR, out_info.width > 0, XCAM_RETURN_ERROR_PARAM,
"gl-copy invalid output width: %d", out_info.width);
const size_t unit_bytes = sizeof (uint32_t) * 4;
uint32_t in_img_width = in_info.aligned_width / unit_bytes;
uint32_t in_x_offset = _in_area.pos_x / unit_bytes;
uint32_t out_img_width = out_info.aligned_width / unit_bytes;
uint32_t out_x_offset = _out_area.pos_x / unit_bytes;
uint32_t copy_w = _in_area.width / unit_bytes;
uint32_t copy_h = _in_area.height / 2 * 3;
GLCmdList cmds;
cmds.push_back (new GLCmdUniformT<uint32_t> ("in_img_width", in_img_width));
cmds.push_back (new GLCmdUniformT<uint32_t> ("in_x_offset", in_x_offset));
cmds.push_back (new GLCmdUniformT<uint32_t> ("out_img_width", out_img_width));
cmds.push_back (new GLCmdUniformT<uint32_t> ("out_x_offset", out_x_offset));
cmds.push_back (new GLCmdUniformT<uint32_t> ("copy_width", copy_w));
_copy_shader->set_commands (cmds);
GLGroupsSize groups_size;
groups_size.x = XCAM_ALIGN_UP (copy_w, 8) / 8;
groups_size.y = XCAM_ALIGN_UP (copy_h, 8) / 8;
groups_size.z = 1;
_copy_shader->set_groups_size (groups_size);
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
GLCopyHandler::configure_resource (const SmartPtr<Parameters> ¶m)
{
XCAM_ASSERT (param.ptr () && param->in_buf.ptr ());
XCAM_FAIL_RETURN (
ERROR,
_index != INVALID_INDEX &&
_in_area.width && _in_area.height && _out_area.width && _out_area.height,
XCAM_RETURN_ERROR_PARAM,
"gl-copy invalid copy area, index: %d, in size: %dx%d, out size: %dx%d",
_index, _in_area.width, _in_area.height, _out_area.width, _out_area.height);
SmartPtr<GLImageShader> shader = new GLImageShader (shader_info.name);
XCAM_ASSERT (shader.ptr ());
_copy_shader = shader;
XCamReturn ret = _copy_shader->create_compute_program (shader_info);
XCAM_FAIL_RETURN (
ERROR, ret == XCAM_RETURN_NO_ERROR, ret,
"gl-copy create %s program failed", shader_info.name);
fix_parameters (param);
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
GLCopyHandler::start_work (const SmartPtr<ImageHandler::Parameters> ¶m)
{
SmartPtr<GLBuffer> in_buf = get_glbuffer (param->in_buf);
SmartPtr<GLBuffer> out_buf = get_glbuffer (param->out_buf);
GLCmdList cmds;
cmds.push_back (new GLCmdBindBufRange (in_buf, 0));
cmds.push_back (new GLCmdBindBufRange (out_buf, 1));
_copy_shader->set_commands (cmds);
return _copy_shader->work (NULL);
};
XCamReturn
GLCopyHandler::terminate ()
{
if (_copy_shader.ptr ()) {
_copy_shader.release ();
}
return GLImageHandler::terminate ();
}
}
| 2,255 |
3,066 | /*
* Licensed to Crate.io GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.planner.operators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public final class PrintContext {
private final StringBuilder sb;
private final ArrayList<String> prefixes = new ArrayList<>();
public PrintContext() {
sb = new StringBuilder();
}
public PrintContext text(String s) {
sb.append(s);
return this;
}
@SafeVarargs
public final PrintContext nest(Consumer<PrintContext>... children) {
return nest(Arrays.asList(children));
}
public final PrintContext nest(List<Consumer<PrintContext>> children) {
for (int i = 0; i < children.size(); i++) {
sb.append("\n");
for (String prefix : prefixes) {
sb.append(prefix);
}
if (i + 1 == children.size()) {
sb.append(" └ ");
prefixes.add(" ");
} else {
sb.append(" ├ ");
prefixes.add(" │");
}
Consumer<PrintContext> child = children.get(i);
child.accept(this);
prefixes.remove(prefixes.size() - 1);
}
return this;
}
@Override
public String toString() {
return sb.toString();
}
}
| 852 |
2,151 | /*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* <NAME>
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef _STLP_C_LOCALE_H
#define _STLP_C_LOCALE_H
/*
* Implementation dependent definitions.
* Beware: This header is not a purely internal header, it is also included
* from the outside world when building the STLport library. So this header
* should not reference internal headers (stlport/stl/_*.h) directly.
*/
#if defined (__sgi)
# if defined (ROOT_65) /* IRIX 6.5.x */
# include <sgidefs.h>
# include <standards.h>
# include <wchar.h>
# include <ctype.h>
# else /* IRIX pre-6.5 */
# include <sgidefs.h>
# include <standards.h>
# if !defined(_SIZE_T) && !defined(_SIZE_T_)
# define _SIZE_T
# if (_MIPS_SZLONG == 32)
typedef unsigned int size_t;
# endif
# if (_MIPS_SZLONG == 64)
typedef unsigned long size_t;
# endif
# endif
# if !defined (_WCHAR_T)
# define _WCHAR_T
# if (_MIPS_SZLONG == 32)
typedef long wchar_t;
# endif
# if (_MIPS_SZLONG == 64)
typedef __int32_t wchar_t;
# endif
# endif /* _WCHAR_T */
# if !defined (_WINT_T)
# define _WINT_T
# if (_MIPS_SZLONG == 32)
typedef long wint_t;
# endif
# if (_MIPS_SZLONG == 64)
typedef __int32_t wint_t;
# endif
# endif /* _WINT_T */
# if !defined (_MBSTATE_T)
# define _MBSTATE_T
/* _MSC_VER check is here for historical reason and seems wrong as it is the macro defined
* by Microsoft compilers to give their version. But we are in a SGI platform section so it
* is weird. However _MSC_VER might also be a SGI compiler macro so we keep it this way.*/
# if defined (_MSC_VER)
typedef int mbstate_t;
# else
typedef char mbstate_t;
# endif
# endif /* _MBSTATE_T */
# endif /* ROOT65 */
#elif defined (_STLP_USE_GLIBC)
# include <ctype.h>
#endif
/*
* GENERAL FRAMEWORK
*/
/*
* Opaque types, implementation (if there is one) depends
* on platform localisation API.
*/
struct _Locale_ctype;
struct _Locale_codecvt;
struct _Locale_numeric;
struct _Locale_time;
struct _Locale_collate;
struct _Locale_monetary;
struct _Locale_messages;
/*
Bitmask macros.
*/
/*
* For narrow characters, we expose the lookup table interface.
*/
#if defined (_STLP_USE_GLIBC)
/* This section uses macros defined in the gnu libc ctype.h header */
# define _Locale_CNTRL _IScntrl
# define _Locale_UPPER _ISupper
# define _Locale_LOWER _ISlower
# define _Locale_DIGIT _ISdigit
# define _Locale_XDIGIT _ISxdigit
# define _Locale_PUNCT _ISpunct
# define _Locale_SPACE _ISspace
# define _Locale_PRINT _ISprint
# define _Locale_ALPHA _ISalpha
#else
/* Default values based on C++ Standard 22.2.1.
* Under Windows the localisation implementation take care of mapping its
* mask values to those internal values. For other platforms without real
* localization support we are free to use the most suitable values.*/
# define _Locale_SPACE 0x0001
# define _Locale_PRINT 0x0002
# define _Locale_CNTRL 0x0004
# define _Locale_UPPER 0x0008
# define _Locale_LOWER 0x0010
# define _Locale_ALPHA 0x0020
# define _Locale_DIGIT 0x0040
# define _Locale_PUNCT 0x0080
# define _Locale_XDIGIT 0x0100
#endif
#endif /* _STLP_C_LOCALE_H */
| 1,419 |
409 | package org.webrtc.kite;
import static io.cosmosoftware.kite.util.TestUtils.printJsonTofile;
import static io.cosmosoftware.kite.util.TestUtils.readJsonFile;
import static io.cosmosoftware.kite.util.TestUtils.verifyPathFormat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;
import org.apache.commons.io.FileUtils;
public class ReportMerger {
public static void main(String[] args) {
String pathToOldReport = verifyPathFormat(args[0]);
String pathToNewReport = verifyPathFormat(args[1]);
List<String> failedCasesInOldReport = extractFailedCases(pathToOldReport);
try {
fixWrongStatus(pathToOldReport);
}catch (Exception e) {
System.out.println("Could not fix wrong status");
}
for (int index = 0; index < failedCasesInOldReport.size(); index++) {
String failedCase = failedCasesInOldReport.get(index);
System.out.println("Processing [" + (index+1) + "/" + failedCasesInOldReport.size() + "]" + failedCase);
String otherCase = findOtherCaseInNewReports(failedCase, pathToNewReport);
if (!otherCase.isEmpty()) {
try {
System.out.println("Updating " + failedCase + " with " + otherCase);
updateResultFile(failedCase, otherCase);
List<String> attachments = getAttachments(otherCase);
for (String attachment : attachments) {
try {
FileUtils.copyFile(new File(pathToNewReport + "/" + attachment),
new File(pathToOldReport+ "/" + attachment));
} catch (Exception e) {
System.out.println("Could not copy " + attachment + ": " + e.getLocalizedMessage());
}
}
List<String> attachmentsToDelete = getAttachments(failedCase);
for (String attachment : attachmentsToDelete) {
try {
FileUtils.forceDelete(new File(pathToOldReport+ "/" + attachment));
} catch (Exception e) {
System.out.println("Could not delete " + attachment + ": " + e.getLocalizedMessage());
}
}
} catch (Exception e) {
System.out.println("Could not update " + failedCase + ": " + e.getLocalizedMessage());
}
} else {
System.out.println("No possible update for " + failedCase);
}
}
}
private static void copyAttachments(String fileName) {
}
private static void updateResultFile(String pathToResultFile, String pathToOtherResultFile)
throws IOException {
JsonObject result = readJsonFile(pathToResultFile);
JsonObject otherResult = readJsonFile(pathToOtherResultFile);
JsonObjectBuilder builder = Json.createObjectBuilder();
for (String key: result.keySet()) {
switch (key) {
case "steps":
case "statusDetails":
case "attachments":
case "name":
case "status":
case "stage": {
builder.add(key, otherResult.get(key));
break;
}
default: {
builder.add(key, result.get(key));
break;
}
}
}
FileUtils.forceDelete(new File(pathToResultFile));
printJsonTofile(builder.build().toString(), pathToResultFile);
}
private static String findOtherCaseInNewReports(String pathToFailedCase, String pathToNewReports) {
JsonObject result = readJsonFile(pathToFailedCase);
boolean webdriverIssue = result.getJsonObject("statusDetails").getString("message").contains("populating web drivers");
String testCaseName = result.getString("name").split(Pattern.quote("("))[0];
String testFullName = result.getString("fullName");
String fullName = result.getString("fullName");
List<String> testCasesInNewReports = findTestCasesInReports(pathToNewReports, testCaseName, testFullName);
for (String testCasePath : testCasesInNewReports) {
JsonObject testCase = readJsonFile(testCasePath);
if (testCase.getString("fullName").equals(fullName)) {
if (webdriverIssue) {
return testCasePath;
} else {
if (result.getString("status").equals("BROKEN")) {
if (testCase.getString("status").equals("PASSED")
|| testCase.getString("status").equals("FAILED")) {
return testCasePath;
}
} else { // FAILED
if (testCase.getString("status").equals("PASSED")) {
return testCasePath;
}
}
}
}
}
return "";
}
private static List<String> findTestCasesInReports(String pathToReportFolder, String testCaseName, String testFullName) {
List<String> res = new ArrayList<>();
try {
File reportFolder = new File(pathToReportFolder);
File[] subFiles = reportFolder.listFiles();
for (int index = 0; index < subFiles.length; index++) {
if (subFiles[index].getName().contains("result.json")) {
JsonObject result = readJsonFile(subFiles[index].getAbsolutePath());
if (result.getString("name").contains(testCaseName)
&& result.getString("fullName").equals(testFullName)) {
res.add(subFiles[index].getAbsolutePath());
}
}
}
} catch (Exception e) {
System.out.println("Error getting failed cases from " + pathToReportFolder + ":\n" + e.getLocalizedMessage());
}
return res;
}
private static List<String> getAttachments(String pathToTestCase) {
JsonObject result = readJsonFile(pathToTestCase);
return getAttachments(result);
}
private static List<String> getAttachments(JsonObject step) {
List<String> res = new ArrayList<>();
JsonArray steps = step.getJsonArray("steps");
for (JsonValue subStep : steps) {
res.addAll(getAttachments((JsonObject) subStep));
}
JsonArray attachments = step.getJsonArray("attachments");
for (JsonValue attachment : attachments) {
res.add(((JsonObject) attachment).getString("source"));
}
return res;
}
private static List<String> extractFailedCases(String pathToReportFolder) {
List<String> res = new ArrayList<>();
try {
File reportFolder = new File(pathToReportFolder);
File[] subFiles = reportFolder.listFiles();
for (int index = 0; index < subFiles.length; index++) {
if (subFiles[index].getName().contains("result.json")) {
JsonObject result = readJsonFile(subFiles[index].getAbsolutePath());
if (!result.getString("status").equals("PASSED")) {
res.add(subFiles[index].getAbsolutePath());
}
}
}
} catch (Exception e) {
System.out.println("Error getting failed cases from " + pathToReportFolder + ":\n" + e.getLocalizedMessage());
}
return res;
}
private static void fixWrongStatus(String pathToReportFolder) throws IOException {
File reportFolder = new File(pathToReportFolder);
File[] subFiles = reportFolder.listFiles();
for (int index = 0; index < subFiles.length; index++) {
if (subFiles[index].getName().contains("result.json")) {
JsonObject result = readJsonFile(subFiles[index].getAbsolutePath());
JsonObject statusDetail = result.getJsonObject("statusDetails");
String message = statusDetail.getString("message");
boolean issue = message.equalsIgnoreCase("The test has passed successfully!")
&& !result.getString("status").equals("PASSED");
if (issue) {
JsonArray steps = result.getJsonArray("steps");
for (int i = 0; i < steps.size(); i++) {
JsonObject step = (JsonObject)steps.get(i);
if (!step.getString("status").equals("PASSED")){
statusDetail = step.getJsonObject("statusDetails");
break;
}
}
JsonObjectBuilder builder = Json.createObjectBuilder();
for (String key: result.keySet()) {
if (!key.equals("statusDetails")) {
builder.add(key, result.get(key));
} else {
builder.add(key, statusDetail);
}
}
FileUtils.forceDelete(new File(subFiles[index].getAbsolutePath()));
printJsonTofile(builder.build().toString(), subFiles[index].getAbsolutePath());
}
}
}
}
}
| 3,403 |
852 | //#include "CondFormats/DataRecord/interface/RecoIdealGeometryRcd.h"
#include "Geometry/Records/interface/CSCRecoGeometryRcd.h"
#include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h"
EVENTSETUP_RECORD_REG(CSCRecoGeometryRcd);
| 94 |
486 | <gh_stars>100-1000
package com.tutsplus.jobscheduler;
import android.app.Activity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private JobScheduler mJobScheduler;
private Button mScheduleJobButton;
private Button mCancelAllJobsButton;
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
mJobScheduler = (JobScheduler) getSystemService( Context.JOB_SCHEDULER_SERVICE );
mScheduleJobButton = (Button) findViewById( R.id.schedule_job );
mCancelAllJobsButton = (Button) findViewById( R.id.cancel_all );
mScheduleJobButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
JobInfo.Builder builder = new JobInfo.Builder( 1,
new ComponentName( getPackageName(), JobSchedulerService.class.getName() ) );
builder.setPeriodic( 3000 );
if( mJobScheduler.schedule( builder.build() ) <= 0 ) {
//If something goes wrong
}
}
});
mCancelAllJobsButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick( View v ) {
mJobScheduler.cancelAll();
}
});
}
}
| 704 |
3,459 | typedef struct {
uint8 r,g,b;
} pal;
extern pal *palo;
void FCEU_ResetPalette(void);
void FCEU_ResetPalette(void);
void FCEU_ResetMessages();
void FCEU_LoadGamePalette(void);
void FCEU_DrawNTSCControlBars(uint8 *XBuf);
| 113 |
605 | package com.sohu.tv.mq.cloud.web.view.chart;
import java.util.List;
import java.util.Map;
/**
* 曲线图对象
*
* @Description:
* @author yongfeigao
* @date 2018年6月29日
*/
public class LineChart {
// 曲线类型
private String type = "spline";
// 曲线图id,同一个页面的多张图不可相同
private String chartId;
// 曲线图的名称,用于显示
private String title;
// 曲线图的副名称
private String subTitle;
// 高度
private int height = 400;
// 曲线提示对象
private Tip tip;
// 曲线图的x轴对象
private XAxis xAxis;
// 曲线图的一组y轴数据,如果只有一条曲线,该组中的list为1
private List<YAxisGroup> yAxisGroupList;
// 点击曲线图的点跳到的url,点击后会给该url附加上x=&y=&name=的数据
private String url;
// 鼠标移到该点时,提示该点跳转的名字
private String urlTitle;
// 曲线边框宽度,默认带边框
private int borderWidth = 1;
// 是否单独占一行显示
private boolean oneline;
// 设置x轴步长
private int tickInterval;
private Map<?, ?> dataMap;
public String getChartId() {
return chartId;
}
public void setChartId(String chartId) {
this.chartId = chartId;
}
public String getUrlTitle() {
return urlTitle;
}
public void setUrlTitle(String urlTitle) {
this.urlTitle = urlTitle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTickInterval() {
return tickInterval;
}
public void setTickInterval(int tickInterval) {
this.tickInterval = tickInterval;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public int getBorderWidth() {
return borderWidth;
}
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
}
public Tip getTip() {
return tip;
}
public void setTip(Tip tip) {
this.tip = tip;
}
public XAxis getxAxis() {
return xAxis;
}
public void setxAxis(XAxis xAxis) {
this.xAxis = xAxis;
}
public List<YAxisGroup> getyAxisGroupList() {
return yAxisGroupList;
}
public void setyAxisGroupList(List<YAxisGroup> yAxisGroupList) {
this.yAxisGroupList = yAxisGroupList;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isOneline() {
return oneline;
}
public void setOneline(boolean oneline) {
this.oneline = oneline;
}
public Map<?, ?> getDataMap() {
return dataMap;
}
public void setDataMap(Map<?, ?> dataMap) {
this.dataMap = dataMap;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
/**
* X轴对象
*/
public static class XAxis {
// x轴的刻度列表
private List<String> xList;
public List<String> getxList() {
return xList;
}
public void setxList(List<String> xList) {
this.xList = xList;
}
}
/**
* 一组Y轴数据
*/
public static class YAxisGroup {
// 整个y轴组的名字
private String groupName;
// 各个y轴数据
private List<YAxis> yAxisList;
// 可选的(如果为true y轴在右边显示)
private boolean opposite;
// 是否启用流量单位格式化
private boolean traffic;
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public List<YAxis> getyAxisList() {
return yAxisList;
}
public void setyAxisList(List<YAxis> yAxisList) {
this.yAxisList = yAxisList;
}
public boolean isOpposite() {
return opposite;
}
public void setOpposite(boolean opposite) {
this.opposite = opposite;
}
public boolean isTraffic() {
return traffic;
}
public void setTraffic(boolean traffic) {
this.traffic = traffic;
}
}
/**
* Y轴对象,注意,x轴的xList与y轴yList顺序需要一一对应
*/
public static class YAxis {
// y轴的的类型名
private String name;
// y轴数据
private List<Object> data;
// 颜色
private String color;
// 对应的y轴
private int yAxis;
// 默认是否可见
private boolean visible = true;
private Tip tooltip;
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Object> getData() {
return data;
}
public int getyAxis() {
return yAxis;
}
public void setyAxis(int yAxis) {
this.yAxis = yAxis;
}
@SuppressWarnings("unchecked")
public void setData(List<?> data) {
this.data = (List<Object>) data;
}
public Tip getTooltip() {
return tooltip;
}
public void setTooltip(Tip tooltip) {
this.tooltip = tooltip;
}
}
/**
* 曲线数据提示对象
*/
public static class Tip {
// 是否多条曲线的数据一起提示
private boolean shared = true;
// 默认为xAxis+YAxis.name+YAxis数据
private String headerFormat;
private String pointFormat;
private String footerFormat;
// message是否使用html格式
private boolean useHTML;
private String valueSuffix;
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
public String getPointFormat() {
return pointFormat;
}
public String getHeaderFormat() {
return headerFormat;
}
public void setHeaderFormat(String headerFormat) {
this.headerFormat = headerFormat;
}
public String getFooterFormat() {
return footerFormat;
}
public void setFooterFormat(String footerFormat) {
this.footerFormat = footerFormat;
}
public void setPointFormat(String pointFormat) {
this.pointFormat = pointFormat;
}
public boolean isUseHTML() {
return useHTML;
}
public void setUseHTML(boolean useHTML) {
this.useHTML = useHTML;
}
public String getValueSuffix() {
return valueSuffix;
}
public void setValueSuffix(String valueSuffix) {
this.valueSuffix = valueSuffix;
}
}
}
| 3,963 |
764 | {"symbol": "DKA","address": "0x5dc60C4D5e75D22588FA17fFEB90A63E535efCE0","overview":{"en": ""},"email": "<EMAIL>","website": "https://dkargo.io/","state": "NORMAL","links": {"blog": "https://medium.com/dkargo","twitter": "","telegram": "https://t.me/dKargo_Official_KR","github": ""}} | 112 |
764 | <reponame>641589523/token-profile<filename>erc20/0xD6e1401a079922469e9b965Cb090ea6fF64C6839.json<gh_stars>100-1000
{"symbol": "HOLD","address": "0xD6e1401a079922469e9b965Cb090ea6fF64C6839","overview":{"en": ""},"email": "<EMAIL>","website": "https://hold.co/","state": "NORMAL","links": {"blog": "https://medium.com/@HoldHQ","twitter": "https://twitter.com/HoldHQ","telegram": "https://t.me/HoldHQ","github": ""}} | 174 |
22,688 | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include <vector>
#include "modules/localization/msf/local_map/base_map/base_map_node.h"
#include "modules/localization/msf/local_map/lossless_map/lossless_map_matrix.h"
namespace apollo {
namespace localization {
namespace msf {
class LosslessMapNode : public BaseMapNode {
public:
LosslessMapNode();
~LosslessMapNode();
/**@brief Set the value of a pixel in the map node.
* @param <coordinate> The 3D global coordinate.
* @param <intensity> The reflectance intensity.
*/
void SetValue(const Eigen::Vector3d& coordinate, unsigned char intensity);
/**@brief Set the value of a pixel in the map node if the pixel in the node.
* @param <coordinate> The 3D global coordinate.
* @param <intensity> The reflectance intensity.
* @param <return> True, if pixel in the bound of the node, else False.
* */
bool SetValueIfInBound(const Eigen::Vector3d& coordinate,
unsigned char intensity);
/**@brief Set the value of a pixel in a layer in the map node.
* @param <coordinate> The 3D global coordinate. The z is used as the altitude
* for the layer match.
* @param <intensity> The reflectance intensity.
*/
void SetValueLayer(const Eigen::Vector3d& coordinate,
unsigned char intensity);
/**@brief Given the 3D global coordinate, get the map cell average intensity
* of each layer. */
void GetValue(const Eigen::Vector3d& coordinate,
std::vector<unsigned char>* values) const;
/**@brief Given the 3D global coordinate, get the map cell variance of the
* intensity of each layer. */
void GetVar(const Eigen::Vector3d& coordinate,
std::vector<float>* vars) const;
/**@brief Given the 3D global coordinate, get the map cell's average altitude
* of each layer. */
void GetAlt(const Eigen::Vector3d& coordinate,
std::vector<float>* alts) const;
/**@brief Given the 3D global coordinate, get the map cell's variance of the
* altitude of each layer. */
void GetAltVar(const Eigen::Vector3d& coordinate,
std::vector<float>* alt_vars) const;
/**@brief Given the 3D global coordinate, get the map cell's count of the
* samples of each layer. */
void GetCount(const Eigen::Vector3d& coordinate,
std::vector<unsigned int>* counts) const;
/**@brief Given the 3D global coordinate, get the map cell average intensity.
*/
unsigned char GetValue(const Eigen::Vector3d& coordinate) const;
/**@brief Given the 3D global coordinate, get the map cell variance of the
* intensity. */
float GetVar(const Eigen::Vector3d& coordinate) const;
/**@brief Given the 3D global coordinate, get the map cell's average altitude.
*/
float GetAlt(const Eigen::Vector3d& coordinate) const;
/**@brief Given the 3D global coordinate, get the map cell's variance of the
* altitude */
float GetAltVar(const Eigen::Vector3d& coordinate) const;
/**@brief Given the 3D global coordinate, get the map cell's count of the
* samples. */
unsigned int GetCount(const Eigen::Vector3d& coordinate) const;
/**@brief Get the map cell average intensity. */
unsigned char GetValue(unsigned int row, unsigned int col) const {
return static_cast<LosslessMapMatrix*>(map_matrix_)
->GetMapCell(row, col)
.GetValue();
}
/**@brief Get the map cell variance of the intensity. */
float GetVar(unsigned int row, unsigned int col) const {
return static_cast<LosslessMapMatrix*>(map_matrix_)
->GetMapCell(row, col)
.GetVar();
}
/**@brief Get the map cell's average altitude. */
float GetAlt(unsigned int row, unsigned int col) const {
return static_cast<LosslessMapMatrix*>(map_matrix_)
->GetMapCell(row, col)
.GetAlt();
}
/**@brief Get the map cell's variance of the altitude */
float GetAltVar(unsigned int row, unsigned int col) const {
return static_cast<LosslessMapMatrix*>(map_matrix_)
->GetMapCell(row, col)
.GetAltVar();
}
/**@brief Get the map cell's count of the samples. */
unsigned int GetCount(unsigned int row, unsigned int col) const {
return static_cast<LosslessMapMatrix*>(map_matrix_)
->GetMapCell(row, col)
.GetCount();
}
/**@brief Get the constant map cell given the coordinate. */
inline const LosslessMapSingleCell& GetFirstMapCell(unsigned int row,
unsigned int col) const {
return static_cast<LosslessMapMatrix*>(map_matrix_)
->GetMapCell(row, col)
.map_cells[0];
}
inline LosslessMapSingleCell& GetFirstMapCell(unsigned int row,
unsigned int col) {
return static_cast<LosslessMapMatrix*>(map_matrix_)
->GetMapCell(row, col)
.map_cells[0];
}
/**@brief Get the min altitude of point cloud in the node. */
inline float GetMinAltitude() const { return min_altitude_; }
/**@brief Set the min altitude of point cloud in the node. */
inline void SetMinAltitude(float altitude) { min_altitude_ = altitude; }
protected:
/**@brief The min altitude of point cloud in the node. */
float min_altitude_;
};
} // namespace msf
} // namespace localization
} // namespace apollo
| 2,031 |
310 | <filename>gear/software/l/lsp-mode.json
{
"name": "lsp-mode",
"description": "A Language Server Protocol mode for Emacs.",
"url": "https://github.com/emacs-lsp/lsp-mode"
}
| 68 |
2,204 | from gordon.utils_tests import BaseIntegrationTest, BaseBuildTest
from gordon.utils import valid_cloudformation_name
from gordon import utils
class IntegrationTest(BaseIntegrationTest):
def test_0001_project(self):
self._test_project_step('0001_project')
self.assert_stack_succeed('p')
self.assert_stack_succeed('r')
lambda_ = self.get_lambda(utils.valid_cloudformation_name('pyexample:pyexample'))
self.assertEqual(lambda_['Runtime'], 'python2.7')
self.assertEqual(lambda_['Description'], 'My description')
self.assertEqual(lambda_['MemorySize'], 192)
self.assertEqual(lambda_['Timeout'], 123)
aliases = self.get_lambda_aliases(function_name=lambda_['FunctionName'])
self.assertEqual(list(aliases.keys()), ['current'])
response = self.invoke_lambda(
function_name=lambda_['FunctionName'],
payload={'key1': 'hello'}
)
self.assert_lambda_response(response, 'hello')
def test_0002_project(self):
self._test_project_step('0002_project')
self.assert_stack_succeed('p')
self.assert_stack_succeed('r')
lambda_ = self.get_lambda(utils.valid_cloudformation_name('pyexample:pyexample'))
self.assertEqual(lambda_['Runtime'], 'python2.7')
self.assertEqual(lambda_['Description'], 'My second description')
self.assertEqual(lambda_['MemorySize'], 256)
self.assertEqual(lambda_['Timeout'], 199)
aliases = self.get_lambda_aliases(function_name=lambda_['FunctionName'])
self.assertEqual(list(aliases.keys()), ['current'])
response = self.invoke_lambda(
function_name=lambda_['FunctionName'],
payload={'key1': 'hello', 'key2': 'bye'}
)
self.assert_lambda_response(response, 'bye')
class BuildTest(BaseBuildTest):
def test_0001_project(self):
self._test_project_step('0001_project')
self.assertBuild('0001_project', '0001_p.json')
self.assertBuild('0001_project', '0002_pr_r.json')
self.assertBuild('0001_project', '0003_r.json')
def test_0002_project(self):
self._test_project_step('0002_project')
self.assertBuild('0002_project', '0001_p.json')
self.assertBuild('0002_project', '0002_pr_r.json')
self.assertBuild('0002_project', '0003_r.json')
| 978 |
432 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import phyre.creator as creator_lib
@creator_lib.define_task
def build_task(C):
scene_width = C.scene.width
scene_height = C.scene.height
# Add two bars that are supposed to touch each other.
bar1 = C.add('dynamic bar', scale=0.25) \
.set_angle(90.) \
.set_bottom(0.) \
.set_left(.3 * scene_width)
bar2 = C.add('dynamic bar', scale=0.25) \
.set_angle(90.) \
.set_bottom(0.) \
.set_left(.7 * scene_width)
# Add obstacle.
C.add('static bar', scale=0.6) \
.set_center_x(0.5 * scene_width) \
.set_bottom(0.5 * scene_height)
# Create task.
C.update_task(body1=bar1,
body2=bar2,
relationships=[C.SpatialRelationship.TOUCHING])
| 526 |
2,199 | /*******************************************************************************
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
******************************************************************************/
package the8472.bencode;
import static the8472.bencode.Utils.str2buf;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.stream.Stream;
public class BEncoder {
private ByteBuffer buf;
public static class RawData {
ByteBuffer rawBuf;
public RawData(ByteBuffer b) {
rawBuf = b;
}
}
public static interface StringWriter {
int length();
void writeTo(ByteBuffer buf);
}
public ByteBuffer encode(Map<String, Object> toEnc, int maxSize) {
buf = ByteBuffer.allocate(maxSize);
encodeMap(toEnc);
buf.flip();
return buf;
}
public void encodeInto(Map<String, Object> toEnc, ByteBuffer target) {
buf = target;
encodeMap(toEnc);
buf.flip();
}
public ByteBuffer encode(Object toEnc, int maxSize) {
buf = ByteBuffer.allocate(maxSize);
encodeInternal(toEnc);
buf.flip();
return buf;
}
private void encodeInternal(Object o) {
if(o instanceof Map) {
encodeMap((Map<String, Object>) o);
return;
}
if(o instanceof List) {
encodeList((List<Object>) o);
return;
}
if(o instanceof String) {
encodeString((String) o);
return;
}
if(o instanceof byte[]) {
byte[] b = (byte[]) o;
encodeInt(b.length, (byte) ':');
buf.put(b);
return;
}
if(o instanceof ByteBuffer) {
ByteBuffer clone = ((ByteBuffer) o).slice();
encodeInt(clone.remaining(), (byte) ':');
buf.put(clone);
return;
}
if(o instanceof Integer) {
buf.put((byte) 'i');
encodeInt(((Integer) o).intValue(),(byte) 'e');
return;
}
if(o instanceof Long) {
buf.put((byte) 'i');
encodeLong(((Long) o).longValue(), 'e');
return;
}
if(o instanceof RawData) {
ByteBuffer raw = ((RawData) o).rawBuf;
buf.put(raw.duplicate());
return;
}
if(o instanceof StringWriter) {
StringWriter w = (StringWriter) o;
encodeInt(w.length(), (byte)':');
w.writeTo(buf);
return;
}
if(o instanceof Stream) {
encodeStream((Stream<Object>) o);
return;
}
throw new RuntimeException("unknown object to encode " + o);
}
private void encodeStream(Stream<Object> l) {
buf.put((byte) 'l');
l.forEach(this::encodeInternal);
buf.put((byte) 'e');
}
private void encodeList(List<Object> l) {
buf.put((byte) 'l');
l.forEach(this::encodeInternal);
buf.put((byte) 'e');
}
private void encodeString(String str) {
encodeInt(str.length(), (byte) ':');
str2buf(str, buf);
}
private void encodeMap(Map<String, Object> map) {
buf.put((byte) 'd');
Stream<Entry<String,Object>> str;
if(map instanceof SortedMap<?, ?> && ((SortedMap<?, ?>) map).comparator() == null)
str = map.entrySet().stream();
else
str = map.entrySet().stream().sorted(Map.Entry.comparingByKey());
str.forEachOrdered(e -> {
encodeString(e.getKey());
encodeInternal(e.getValue());
});
buf.put((byte) 'e');
}
private final static byte[] MIN_INT = str2buf(Integer.toString(Integer.MIN_VALUE)).array();
private void encodeInt(int val, byte terminator) {
if(val == Integer.MIN_VALUE)
buf.put(MIN_INT);
else {
if(val < 0) {
buf.put((byte) '-');
val = -val;
}
int numChars = 10;
int probe = 10;
for (int i=1; i<10; i++) {
if (val < probe) {
numChars = i;
break;
}
probe = 10*probe;
}
int pos = buf.position() + numChars;
buf.position(pos);
for(int i=1; i <= numChars; i++) {
int reduced = val / 10;
int remainder = val - (reduced * 10);
buf.put(pos - i, (byte) ('0' + remainder));
val = reduced;
}
}
buf.put(terminator);
}
private void encodeLong(long val, char terminator) {
str2buf(Long.toString(val), buf);
buf.put((byte) terminator);
}
}
| 1,848 |
338 | <gh_stars>100-1000
package com.camnter.hook.binder;
import android.annotation.SuppressLint;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.util.Log;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* ServiceManager # HashMap<String, IBinder> sCache
* IBinder 的类型基本上都是 BinderProxy
* 因为 ServiceManager 会将这些 BinderProxy 通过 asInterface 转为接口
*
* asInterface 会判断 BinderProxy 是否在本进程有 Binder 对象
*
* public static IBinder getService(String name) {
* - try {
* - IBinder service = sCache.get(name);
* - if (service != null) {
* - return service;
* - } else {
* - return getIServiceManager().getService(name);
* - }
* - } catch (RemoteException e) {
* - Log.e(TAG, "error in getService", e);
* - }
* - return null;
* }
*
* public interface IClipboard extends android.os.IInterface {
*
* - ...
*
* - public static abstract class Stub extends android.os.Binder
* - implements android.app.IApplicationThread {
*
* - public static android.content.IClipboard asInterface(android.os.IBinder obj) {
* - if ((obj == null)) {
* - return null;
* - }
* - android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
* - if (((iin != null) && (iin instanceof android.content.IClipboard))) {
* - return ((android.content.IClipboard) iin);
* - }
* - return new android.content.IClipboard.Stub.Proxy(obj);
* - }
*
* - }
*
* - ...
*
* }
*
* BinderProxyHookHandler 的作用就是 hook queryLocalInterface
* 将 public static android.content.IClipboard asInterface(android.os.IBinder obj) 方法
* 的返回值变为 BinderHookHandler
*
* @author CaMnter
*/
@SuppressWarnings("DanglingJavadoc")
public class BinderProxyHookHandler implements InvocationHandler {
private static final String TAG = "BinderProxyHookHandler";
private IBinder base;
private Class<?> stub;
private Class<?> iinterface;
@SuppressLint("PrivateApi")
public BinderProxyHookHandler(@NonNull final IBinder base) {
this.base = base;
try {
this.stub = Class.forName("android.content.IClipboard$Stub");
this.iinterface = Class.forName("android.content.IClipboard");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("queryLocalInterface".equals(method.getName())) {
/**
* android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
* 将 iin 变为 BinderHookHandler
*
* BinderHookHandler 代理对象指定了接口类型 (android.content.IClipboard)
*
* 所以可以 return ((android.content.IClipboard) iin);
*
* 然后再一次动态代理
*/
Log.d(TAG, "[BinderProxyHookHandler] hook queryLocalInterface");
return Proxy.newProxyInstance(proxy.getClass().getClassLoader(),
new Class[] { this.iinterface },
new BinderHookHandler(this.base, this.stub));
}
return method.invoke(base, args);
}
}
| 1,535 |
634 | <reponame>halotroop2288/consulo
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots.ui;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ContentFolder;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.roots.libraries.Library;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import consulo.annotation.DeprecationInfo;
public abstract class OrderEntryAppearanceService {
public static OrderEntryAppearanceService getInstance() {
return ServiceManager.getService(OrderEntryAppearanceService.class);
}
@Nonnull
@Deprecated
@DeprecationInfo("Use #forOrderEntry(@ OrderEntry)")
public CellAppearanceEx forOrderEntry(@Deprecated Project project, @Nonnull OrderEntry orderEntry, @Deprecated boolean selected) {
return forOrderEntry(orderEntry);
}
@Nonnull
public abstract CellAppearanceEx forOrderEntry(@Nonnull OrderEntry orderEntry);
@Nonnull
public abstract CellAppearanceEx forLibrary(Project project, @Nonnull Library library, boolean hasInvalidRoots);
@Nonnull
public abstract CellAppearanceEx forSdk(@Nullable Sdk jdk, boolean isInComboBox, boolean selected, boolean showVersion);
@Nonnull
public abstract CellAppearanceEx forContentFolder(@Nonnull ContentFolder folder);
@Nonnull
public abstract CellAppearanceEx forModule(@Nonnull Module module);
}
| 596 |
561 | #!/usr/bin/env python
""" Owl module: Python binding for Minerva library
The module encapsulates or directly maps some functions of Minerva's API to python.
Only system APIs are defined here. For convolution APIs, please refer to conv.py.
For element-wise operations, please refer to elewise.py. For other APIs such as member
functions of :py:class:`owl.NArray`, please refer to the API document.
Note that Minerva is an dataflow system with lazy evaluation to construct dataflow graph
to extract parallelism within codes. All the operations like ``+-*/`` of ``owl.NArray`` are
all *lazy* such that they are NOT evaluated immediatedly. Only when you try to pull the
content of an NArray outside Minerva's control (e.g. call ``to_numpy()``) will those operations
be executed concretely.
We implement two interfaces for swapping values back and forth between numpy and Minerva.
They are ``from_numpy`` and ``to_numpy``. So you could still use any existing codes
on numpy such as IO and visualization.
"""
import numpy as np
import libowl as _owl
NArray = _owl.NArray
_owl.initialize()
# def initialize():
# """ Initialize Minerva System with `sys.argv`
#
# .. note::
# Must be called before calling any owl's API
# """
# _owl.initialize()
def has_cuda():
""" Check if CUDA is enabled
:return: CUDA status
:rtype: int
"""
return _owl.has_cuda()
def wait_for_all():
""" Wait for all evaluation to complete
.. note::
The user thread (python) will be blocked until all previous operations are finished.
:return: None
"""
_owl.wait_for_all()
def create_cpu_device():
""" Create device for running on CPU cores
.. note::
At least one of :py:func:`create_cpu_device` or :py:func:`create_gpu_device` should be called
before using any ``owl`` APIs.
:return: A unique id for cpu device
:rtype: int
"""
return _owl.create_cpu_device()
def create_gpu_device(which):
""" Create device for running on GPU card
.. note::
At least one of :py:func:`create_cpu_device` or :py:func:`create_gpu_device` should be called
before using any ``owl`` APIs.
:param int which: which GPU card the code would be run on
:return: A unique id for the device on that GPU card
:rtype: int
"""
return _owl.create_gpu_device(which)
def get_gpu_device_count():
""" Get the number of compute-capable GPU devices
:return: Number of compute-capable GPU devices
:rtype: int
"""
return _owl.get_gpu_device_count()
def set_device(dev):
""" Switch to the given device for running computations
When ``set_device(dev)`` is called, all the subsequent codes will be run on ``dev``
till another ``set_device`` is called.
:param int dev: the id of the device (usually returned by create_xxx_device)
"""
_owl.set_device(dev)
def zeros(shape):
""" Create ndarray of zero values
:param shape: shape of the ndarray to create
:type shape: list int
:return: result ndarray
:rtype: owl.NArray
"""
return NArray.zeros(shape)
def ones(shape):
""" Create ndarray of one values
:param shape: shape of the ndarray to create
:type shape: list int
:return: result ndarray
:rtype: owl.NArray
"""
return NArray.ones(shape)
def randn(shape, mu, var):
""" Create a random ndarray using normal distribution
:param shape: shape of the ndarray to create
:type shape: list int
:param float mu: mu
:param float var: variance
:return: result ndarray
:rtype: owl.NArray
"""
return NArray.randn(shape, mu, var)
def randb(shape, prob):
""" Create a random ndarray using bernoulli distribution
:param shape: shape of the ndarray to create
:type shape: list int
:param float prob: probability for the value to be one
:return: result ndarray
:rtype: owl.NArray
"""
return NArray.randb(shape, prob)
def from_numpy(nparr):
""" Create an owl.NArray from numpy.ndarray
.. note::
The content will be directly copied to Minerva's memory system. However, due to
the different priority when treating dimensions between numpy and Minerva. The
result ``owl.NArray``'s dimension will be *reversed*.
>>> a = numpy.zeros([200, 300, 50])
>>> b = owl.from_numpy(a)
>>> print b.shape
[50, 300, 200]
.. seealso::
:py:func:`owl.NArray.to_numpy`
:param numpy.ndarray nparr: numpy ndarray
:return: Minerva's ndarray
:rtype: owl.NArray
"""
return NArray.from_numpy(np.require(nparr, dtype=np.float32, requirements=['C']))
def concat(narrays, concat_dim):
""" Concatenate NArrays according to concat_dim
:param narrays: inputs for concatenation
:type narrays: owl.NArray
:param concat_dim: the dimension to concate
:type concat_dim: int
:return: result of concatenation
:rtype: owl.NArray
"""
return NArray.concat(narrays, concat_dim)
def slice(src, slice_dim, st_off, slice_count):
""" Slice NArrays according to slice_dim
:param src: inputs for slice
:type src: owl.NArray
:param slice_dim: the dimension to slice
:type slice_dim: int
:param st_off: where to start slice
:type st_off: int
:param slice_count: how many data_chunk on slice_dim
:slice_count: int
:return: result of slicer
:rtype: owl.NArray
"""
return NArray.slice(src, slice_dim, st_off, slice_count)
# def print_profiler_result():
# """ Print result from execution profiler
#
# :return: None
# """
# _owl.print_profiler_result()
#
# def reset_profiler_result():
# """ Reset execution profiler
#
# :return: None
# """
# _owl.reset_profiler_result()
#
# def print_dag_to_file(fname):
# """ Print the current generated dag into the give filename
#
# :param fname: filename for printing the dag
# :type fname: str
# :return: None
# """
# _owl.print_dag_to_file(fname)
#
# def print_dot_dag_to_file(fname):
# """ Print the current generated dag into the give filename in dot format
#
# :param fname: filename for printing the dag
# :type fname: str
# :return: None
# """
# _owl.print_dot_dag_to_file(fname)
| 2,291 |
1,085 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.datastore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.List;
import com.dremio.datastore.RemoteDataStoreProtobuf.ContainsRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.ContainsResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.DeleteRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.DeleteResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.DocumentResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.FindRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.FindResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.GetCountsRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.GetCountsResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.GetRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.GetResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.GetStoreRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.GetStoreResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.PutRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.PutResponse;
import com.dremio.datastore.RemoteDataStoreProtobuf.SearchRequest;
import com.dremio.datastore.RemoteDataStoreProtobuf.SearchResponse;
import com.dremio.datastore.SearchTypes.SearchQuery;
import com.dremio.datastore.api.Document;
import com.dremio.datastore.api.FindByCondition;
import com.dremio.datastore.api.ImmutableDocument;
import com.dremio.datastore.api.KVStore;
import com.dremio.datastore.indexed.PutRequestDocumentWriter;
import com.dremio.exec.rpc.RpcException;
import com.dremio.services.fabric.simple.ReceivedResponseMessage;
import com.google.common.base.Strings;
import com.google.protobuf.ByteString;
/**
* Raw interfaces over wire, does not use any types.
* Upper levels should use tuple to avoid paying cost of double serialization..
*/
public class DatastoreRpcClient {
private final DatastoreRpcService rpcService;
public DatastoreRpcClient(DatastoreRpcService rpcService) {
this.rpcService = rpcService;
}
/**
* Retrieves storeId.
*
* @param name the name of the key-value store.
* @return the storeId.
*/
public String getStoreId(String name) {
GetStoreRequest.Builder builder = GetStoreRequest.newBuilder()
.setName(name);
try {
ReceivedResponseMessage<GetStoreResponse> response = rpcService.getGetStoreEndpoint().send(builder.build());
return response.getBody().getStoreId();
} catch (RpcException e) {
throw new DatastoreFatalException("Failed to find datastore " + name, e);
}
}
/**
* Get method to retrieve a key-value store entry.
*
* @param storeId the storeId.
* @param key the key of the key-value store entry to retrieve.
* @return the document representation of the key-value store entry retrieved with the provided key. Can be {@code null}
* if no entry with the provided key is found.
* @throws RpcException when RPC related exceptions are encountered.
*/
public Document<ByteString, ByteString> get(String storeId, ByteString key) throws RpcException {
final GetRequest.Builder builder = GetRequest.newBuilder();
builder.setStoreId(storeId);
builder.addKeys(key);
ReceivedResponseMessage<GetResponse> response = rpcService.getGetEndpoint().send(builder.build());
if (response.getBody().getDocumentsCount() > 0) {
DocumentResponse document = response.getBody().getDocuments(0);
if (!document.equals(DocumentResponse.getDefaultInstance())) {
return createImmutableDocumentFromKeyValueTag(document.getKey(), document.getValue(), document.getTag());
}
}
return null;
}
/**
* Get method to retrieve a list of key-value store entries.
*
* @param storeId the storeId.
* @param keys the list of keys which entries are to be retrieved from the store.
* @return a list of documents representing entries retrieved from the store. A document in the list can be {@code null}
* if no corresponding value is found.
* @throws RpcException when RPC related exceptions are encountered.
*/
public List<Document<ByteString, ByteString>> get(String storeId, List<ByteString> keys) throws RpcException {
final GetRequest.Builder builder = GetRequest.newBuilder();
builder.setStoreId(storeId);
builder.addAllKeys(keys);
ReceivedResponseMessage<GetResponse> response = rpcService.getGetEndpoint().send(builder.build());
return createListOfImmutableDocuments(response.getBody().getDocumentsList());
}
/**
* Contains method to determine whether the store has an entry of the provided key.
*
* @param storeId the storeId.
* @param key the key of the entry to lookup.
* @return true if entry exists in the store, false otherwise.
* @throws RpcException when RPC related errors are encountered.
*/
public boolean contains(String storeId, ByteString key) throws RpcException {
final ContainsRequest.Builder builder = ContainsRequest.newBuilder();
builder.setStoreId(storeId);
builder.setKey(key);
ReceivedResponseMessage<ContainsResponse> response = rpcService.getContainsEndpoint().send(builder.build());
return response.getBody().getContains();
}
/**
* Find method to retrieve documents satisfying provided range search criteria.
*
* @param request FindRequest to be sent.
* @return the documents satisfying the search criteria, or {@code null} if no entries in the store satisfies the criteria.
* @throws RpcException when RPC related errors are encountered.
*/
public Iterable<Document<ByteString, ByteString>> find(FindRequest request) throws RpcException {
ReceivedResponseMessage<FindResponse> response = rpcService.getFindEndpoint().send(request);
return createListOfImmutableDocuments(response.getBody().getDocumentsList());
}
/**
* Find method to retrieve all entries from the store.
*
* @param storeId the storeId.
* @return all the documents from the store, or {@code null} if no entries exist in the store.
* @throws RpcException when RPC related errors are encountered.
*/
public Iterable<Document<ByteString, ByteString>> find(String storeId) throws RpcException {
final FindRequest.Builder builder = FindRequest.newBuilder();
builder.setStoreId(storeId);
ReceivedResponseMessage<FindResponse> response = rpcService.getFindEndpoint().send(builder.build());
return createListOfImmutableDocuments(response.getBody().getDocumentsList());
}
/**
* Put method helper to delegate PutRequest.
*/
private String put(PutRequest request) throws RpcException {
final ReceivedResponseMessage<PutResponse> response = rpcService.getPutEndpoint().send(request);
if (response.getBody().hasErrorMessage()) {
if (response.getBody().getConcurrentModificationError()) {
throw new ConcurrentModificationException(response.getBody().getErrorMessage());
} else {
throw new RpcException(response.getBody().getErrorMessage());
}
}
if (response.getBody().hasTag()) {
return response.getBody().getTag();
}
return null;
}
/**
* Put method to store provided key value entry to the store.
*
* @param storeId the store ID.
* @param key the key of the entry to be stored.
* @param value the value of the key-value store entry to put.
* @return the new tag of the key-value store entry.
* @throws RpcException when RPC related errors are encountered.
* @throws ConcurrentModificationException when PutResponse received has ConcurrentModificationError.
*/
public String put(String storeId, ByteString key, ByteString value, PutRequestDocumentWriter indexMap) throws RpcException {
final PutRequest.Builder builder = PutRequest.newBuilder();
indexMap.toPutRequest(builder);
return put(builder
.setStoreId(storeId)
.setKey(key)
.setValue(value)
.build());
}
/**
* Put method to store provided key value entry to the store, provided with options.
*
* @param storeId the storeId.
* @param key the key of the entry to be stored.
* @param value the value of the entry to be stored.
* @param option the extra put options.
* @return the new tag of the key-value store entry.
* @throws RpcException
*/
public String put(String storeId, ByteString key, ByteString value, PutRequestDocumentWriter indexMap, KVStore.PutOption option) throws RpcException {
final RemoteDataStoreProtobuf.PutOptionInfo optionInfo = option.getPutOptionInfo();
final PutRequest.Builder builder = PutRequest.newBuilder();
indexMap.toPutRequest(builder);
return put(builder
.setStoreId(storeId)
.setKey(key)
.setValue(value)
.setOptionInfo(optionInfo)
.build());
}
/**
* Delete method to removed key-value store entry corresponding to the provided key from the store. Tag can be
* {@code null} if no validation is required.
*
* @param storeId the store ID.
* @param key the key of the key-value store entry to remove.
* @param tag the tag of the key-value store entry to remove. Can be {@code null} if no validation is required.
* @throws RpcException when RPC related errors are encountered.
* @throws ConcurrentModificationException when DeleteResponse received has ConcurrentModificationError.
*/
public void delete(String storeId, ByteString key, String tag) throws RpcException {
final DeleteRequest.Builder builder = DeleteRequest.newBuilder();
builder.setStoreId(storeId);
builder.setKey(key);
if (!Strings.isNullOrEmpty(tag)) {
builder.setTag(tag);
}
ReceivedResponseMessage<DeleteResponse> response = rpcService.getDeleteEndpoint().send(builder.build());
if (response.getBody().hasConcurrentModificationError()) {
throw new ConcurrentModificationException(response.getBody().getConcurrentModificationError());
}
}
/**
* Find method to retrieve documents satisfying provided search conditions.
*
* @param storeId the storeId.
* @param findByCondition the search condition.
* @return the documents satisfying the search condition, or {@code null} if no entries in the store satisfies the condition.
* @throws RpcException when RPC related errors are encountered.
*/
public Iterable<Document<ByteString, ByteString>> find(String storeId, FindByCondition findByCondition) throws IOException {
final SearchRequest.Builder builder = SearchRequest.newBuilder();
builder.setStoreId(storeId);
if (!findByCondition.getSort().isEmpty()) {
builder.addAllSort(findByCondition.getSort());
}
builder.setLimit(findByCondition.getLimit());
builder.setOffset(findByCondition.getOffset());
builder.setPageSize(findByCondition.getPageSize());
builder.setQuery(findByCondition.getCondition());
ReceivedResponseMessage<SearchResponse> response = rpcService.getSearchEndpoint().send(builder.build());
return createListOfImmutableDocuments(response.getBody().getDocumentsList());
}
/**
* Counts the number of entries that satisfy the provided conditions.
*
* @param storeId the storeId.
* @param conditions a list of conditions.
* @return the number of entries that satisfy the provided conditions.
* @throws IOException
*/
public List<Integer> getCounts(String storeId, SearchQuery... conditions) throws IOException {
final GetCountsRequest.Builder builder = GetCountsRequest.newBuilder();
builder.setStoreId(storeId);
for (SearchQuery condition: conditions) {
builder.addQueries(condition);
}
ReceivedResponseMessage<GetCountsResponse> response = rpcService.getGetCountsEndpoint().send(builder.build());
return response.getBody().getCountsList();
}
private Document<ByteString, ByteString> createImmutableDocumentFromKeyValueTag(ByteString key, ByteString value, String tag) {
ImmutableDocument.Builder<ByteString, ByteString> builder = new ImmutableDocument.Builder();
builder.setKey(key);
builder.setValue(value);
if (!Strings.isNullOrEmpty(tag)) {
builder.setTag(tag);
}
return builder.build();
}
/*
* Converts a list of DocumentResponse into a list of ImmutableDocument.
*/
private List<Document<ByteString, ByteString>> createListOfImmutableDocuments(List<DocumentResponse> documents) {
ArrayList<Document<ByteString, ByteString>> list = new ArrayList<>();
documents.forEach(document ->
list.add((document.equals(DocumentResponse.getDefaultInstance())) ? null
: createImmutableDocumentFromKeyValueTag(document.getKey(), document.getValue(), document.getTag())
));
return Collections.unmodifiableList(list);
}
}
| 4,101 |
3,967 | <filename>dali/kernels/test/kernel_test.cc
// Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <tuple>
#include "dali/kernels/kernel.h"
#include "dali/kernels/type_tag.h"
#include "dali/core/static_switch.h"
#include "dali/core/tuple_helpers.h"
namespace dali {
namespace kernels {
template <typename OutputType, typename Input1, typename Input2>
using ExampleKernel = examples::Kernel<OutputType, Input1, Input2>;
// Neither function present
struct Empty {
};
// Two run functions
struct TwoRuns {
KernelRequirements Setup(KernelContext &conext, const InListCPU<float, 3>&);
void Run();
void Run(KernelContext &conext, const OutListCPU<float, 3>&, const InListCPU<float, 3>&);
};
// No Setup
struct NoGetReq {
void Run(KernelContext &conext, const OutListCPU<float, 3>&, const InListCPU<float, 3>&);
};
// Setup returns wrong type
struct GetReqBadType {
int Setup(KernelContext &conext, const InListCPU<float, 3>&);
void Run(KernelContext &conext, const OutListCPU<float, 3>&, const InListCPU<float, 3>&);
};
// Setup doesn't take KernelContext & as its first argument
struct GetReqBadParamsType {
int Setup(const InListCPU<float, 3>&);
void Run(KernelContext &conext, const OutListCPU<float, 3>&, const InListCPU<float, 3>&);
};
// Run doesn't take KernelContext & as its first argument
struct RunBadParamsType {
KernelRequirements Setup(KernelContext &conext, const InListCPU<float, 3> &);
void Run(const OutListCPU<float, 3> &, const InListCPU<float, 3> &);
};
TEST(KernelAPI, InferIOArgs) {
static_assert(std::is_same<
kernel_inputs<ExampleKernel<float, float, float>>,
std::tuple<const InListGPU<float, 3>&, const InTensorGPU<float, 4>&>
>::value, "Wrong set of inputs detected");
static_assert(std::is_same<
kernel_outputs<ExampleKernel<int, float, int>>,
std::tuple<const OutListGPU<int, 3>&>
>::value, "Wrong set of outputs detected");
static_assert(std::is_same<
kernel_args<ExampleKernel<float, float, int>>,
std::tuple<const std::vector<float>&>
>::value, "Wrong set of arguments detected");
}
TEST(KernelAPI, EnforceConcept) {
static_assert(detail::has_unique_member_function_Run<ExampleKernel<float, float, int>>::value,
"ExampleKernel has Run function");
static_assert(!detail::has_unique_member_function_Run<Empty>::value,
"Empty has no Run function");
static_assert(!detail::has_unique_member_function_Run<TwoRuns>::value,
"TwoRuns has two Run functions");
check_kernel<ExampleKernel<int, int, float>>();
static_assert(!is_kernel<Empty>::value, "Empty has no Run function and cannot be a kernel");
static_assert(!is_kernel<NoGetReq>::value,
"Empty has no Setup function and cannot be a kernel");
static_assert(!is_kernel<TwoRuns>::value, "ToRuns has two Run functions");
static_assert(!is_kernel<RunBadParamsType>::value, "Run has bad parameters");
}
template <typename O, typename I1, typename I2>
KernelRequirements dali::kernels::examples::Kernel<O, I1, I2>::Setup(
KernelContext &context,
const InListGPU<I1, 3> &in1,
const InTensorGPU<I2, 4> &in2,
const std::vector<float> &aux) {
return {};
}
template <typename O, typename I1, typename I2>
void dali::kernels::examples::Kernel<O, I1, I2>::Run(KernelContext &context,
const OutListGPU<O, 3> &out,
const InListGPU<I1, 3> &in1,
const InTensorGPU<I2, 4> &in2,
const std::vector<float> &aux) {}
TEST(KernelAPI, CallWithTuples) {
InListGPU<float, 3> in1;
InTensorGPU<int, 4> in2;
OutListGPU<float, 3> out;
std::vector<float> aux;
examples::Kernel<float, float, int> K;
KernelContext context;
kernel::Run(K, context, std::tie(out), std::tie(in1, in2), std::tie(aux));
}
} // namespace kernels
} // namespace dali
| 1,561 |
563 | <reponame>philippguertler/mesh
package com.gentics.mesh.example;
import static com.gentics.mesh.example.ExampleUuids.MICROSCHEMA_UUID;
import static com.gentics.mesh.example.ExampleUuids.NODE_DELOREAN_UUID;
import static com.gentics.mesh.example.ExampleUuids.SCHEMA_FOLDER_UUID;
import static com.gentics.mesh.example.ExampleUuids.USER_EDITOR_UUID;
import com.gentics.mesh.core.rest.common.ListResponse;
import com.gentics.mesh.core.rest.common.PagingMetaInfo;
import com.gentics.mesh.core.rest.schema.MicroschemaReference;
import com.gentics.mesh.core.rest.schema.impl.MicroschemaReferenceImpl;
import com.gentics.mesh.core.rest.schema.impl.SchemaReferenceImpl;
import com.gentics.mesh.core.rest.user.NodeReference;
import com.gentics.mesh.core.rest.user.UserReference;
/**
* Abstract class which contains commonly used method to handle example REST Model POJO's.
*/
public abstract class AbstractExamples {
public static final String DATE_OLD = "2018-10-12T14:15:06.024Z";
public static final String DATE_NEW = "2018-11-20T20:12:01.084Z";
public static final long TIMESTAMP_OLD = 1541744513012L;
public static final long TIMESTAMP_NEW = 1542746513622L;
/**
* Return an ISO-8601 formatted timestamp.
*
* @return
*/
public String createNewTimestamp() {
return DATE_NEW;
}
/**
* Return an ISO-8601 formatted timestamp.
*
* @return
*/
public String createOldTimestamp() {
return DATE_OLD;
}
/**
* Set the paging meta information in the given response.
*
* @param response
* @param currentPage
* @param pageCount
* @param perPage
* @param totalCount
*/
public void setPaging(ListResponse<?> response, long currentPage, long pageCount, long perPage, long totalCount) {
PagingMetaInfo info = response.getMetainfo();
info.setCurrentPage(currentPage);
info.setPageCount(pageCount);
info.setPerPage(perPage);
info.setTotalCount(totalCount);
}
/**
* Create a dummy schema reference with the given name, random uuid and version 1.
*
* @param name
* @return
*/
public SchemaReferenceImpl getSchemaReference(String name) {
SchemaReferenceImpl schemaReference = new SchemaReferenceImpl();
schemaReference.setName(name);
schemaReference.setUuid(SCHEMA_FOLDER_UUID);
schemaReference.setVersion("1.0");
return schemaReference;
}
/**
* Create a user reference for user <NAME>.
*
* @return
*/
public UserReference createUserReference() {
UserReference reference = new UserReference();
reference.setUuid(USER_EDITOR_UUID);
reference.setFirstName("Joe");
reference.setLastName("Doe");
return reference;
}
public MicroschemaReference getMicroschemaReference(String name, String version) {
return new MicroschemaReferenceImpl().setName(name).setUuid(MICROSCHEMA_UUID).setVersion(version);
}
/**
* Create a node reference.
*
* @return
*/
public NodeReference createNodeReference() {
NodeReference reference = new NodeReference();
reference.setUuid(NODE_DELOREAN_UUID);
return reference;
}
}
| 1,026 |
834 | // Copyright 2004-present Facebook. All Rights Reserved.
#include "fboss/agent/hw/sai/switch/SaiPortManager.h"
namespace facebook::fboss {
void SaiPortManager::addRemovedHandle(PortID /*portID*/) {}
void SaiPortManager::removeRemovedHandleIf(PortID /*portID*/) {}
bool SaiPortManager::checkPortSerdesAttributes(
const SaiPortSerdesTraits::CreateAttributes& fromStore,
const SaiPortSerdesTraits::CreateAttributes& fromSwPort) {
auto checkSerdesAttribute =
[](auto type, auto& attrs1, auto& attrs2) -> bool {
return (
(std::get<std::optional<std::decay_t<decltype(type)>>>(attrs1)) ==
(std::get<std::optional<std::decay_t<decltype(type)>>>(attrs2)));
};
return (
(std::get<SaiPortSerdesTraits::Attributes::PortId>(fromStore) ==
std::get<SaiPortSerdesTraits::Attributes::PortId>(fromSwPort)) &&
(checkSerdesAttribute(
SaiPortSerdesTraits::Attributes::TxFirPre1{},
fromSwPort,
fromStore)) &&
(checkSerdesAttribute(
SaiPortSerdesTraits::Attributes::TxFirMain{},
fromSwPort,
fromStore)) &&
(checkSerdesAttribute(
SaiPortSerdesTraits::Attributes::TxFirPost1{},
fromSwPort,
fromStore)) &&
(checkSerdesAttribute(
SaiPortSerdesTraits::Attributes::RxCtleCode{},
fromSwPort,
fromStore)) &&
(checkSerdesAttribute(
SaiPortSerdesTraits::Attributes::RxDspMode{},
fromSwPort,
fromStore)) &&
(checkSerdesAttribute(
SaiPortSerdesTraits::Attributes::RxAfeTrim{},
fromSwPort,
fromStore)) &&
(checkSerdesAttribute(
SaiPortSerdesTraits::Attributes::RxAcCouplingByPass{},
fromSwPort,
fromStore)));
}
} // namespace facebook::fboss
| 786 |
412 | <reponame>mauguignard/cbmc<gh_stars>100-1000
#include <assert.h>
struct A
{
union
{
int a;
char b;
};
};
int main()
{
A obj;
obj.a = 'z';
assert(obj.b=='z'); // little endian assumption
assert(sizeof(A) == sizeof(int));
}
| 114 |
923 | <reponame>ToThangGTVT/Repeat
package core.userDefinedTask.manualBuild.steps;
import argo.jdom.JsonNode;
import core.controller.Core;
import core.userDefinedTask.manualBuild.ManuallyBuildStep;
public class MouseReleaseCurrentPositionStep extends ManuallyBuildStep {
private int mask;
public static MouseReleaseCurrentPositionStep of(int mask) {
MouseReleaseCurrentPositionStep result = new MouseReleaseCurrentPositionStep();
result.mask = mask;
return result;
}
@Override
public void execute(Core controller) throws InterruptedException {
controller.mouse().release(mask);
}
@Override
public String getDisplayString() {
return String.format("mouse release %s at current position", DisplayTextUtil.mouseMaskToString(mask));
}
public static MouseReleaseCurrentPositionStep parseJSON(JsonNode node) {
MouseReleaseCurrentPositionStep result = new MouseReleaseCurrentPositionStep();
result.parse(node);
return result;
}
@Override
public String getJsonSignature() {
return "mouse_release_current_position";
}
}
| 301 |
2,905 | settings = {
"ARCHIVE" : True,
"MAX_POSTS" : 5000
}
| 29 |
386 | <filename>src/test/java/eu/hansolo/fx/charts/RadarChartTest.java
/*
* Copyright (c) 2017 by <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 eu.hansolo.fx.charts;
import eu.hansolo.fx.charts.data.ValueChartItem;
import eu.hansolo.fx.charts.series.YSeries;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* User: hansolo
* Date: 07.08.17
* Time: 09:29
*/
public class RadarChartTest extends Application {
private static final Random RND = new Random();
private static final long INTERVAL = 10_000_000_000l;
private static final double ANIM_TIME = INTERVAL / 10_000_000;
private static final int ELEMENTS = 30;
private static final ChartType CHART_TYPE = ChartType.SMOOTH_RADAR_POLYGON;
private YSeries<ValueChartItem> series1;
private YSeries<ValueChartItem> series2;
private YSeries<ValueChartItem> series3;
private YChart<ValueChartItem> chart;
private Timeline timeline;
private long lastTimerCall;
private AnimationTimer timer;
@Override public void init() {
List<ValueChartItem> item1 = new ArrayList<>(ELEMENTS);
List<ValueChartItem> item2 = new ArrayList<>(ELEMENTS);
List<ValueChartItem> item3 = new ArrayList<>(ELEMENTS);
for (int i = 0 ; i < ELEMENTS ; i++) {
ValueChartItem dataPoint;
dataPoint = new ValueChartItem(RND.nextDouble() * 100, "P" + i);
item1.add(dataPoint);
dataPoint = new ValueChartItem(RND.nextDouble() * 100, "P" + i);
item2.add(dataPoint);
dataPoint = new ValueChartItem(RND.nextDouble() * 100, "P" + i);
item3.add(dataPoint);
}
series1 = new YSeries(item3, CHART_TYPE, new RadialGradient(0, 0, 0, 0, 1, true, CycleMethod.NO_CYCLE, new Stop(0.0, Color.rgb(0, 255, 255, 0.25)), new Stop(0.5, Color.rgb(255, 255, 0, 0.5)), new Stop(1.0, Color.rgb(255, 0, 255, 0.75))), Color.TRANSPARENT);
series2 = new YSeries(item1, CHART_TYPE, new RadialGradient(0, 0, 0, 0, 1, true, CycleMethod.NO_CYCLE, new Stop(0.0, Color.rgb(255, 0, 0, 0.25)), new Stop(0.5, Color.rgb(255, 255, 0, 0.5)), new Stop(1.0, Color.rgb(0, 200, 0, 0.75))), Color.TRANSPARENT);
series3 = new YSeries(item2, CHART_TYPE, new RadialGradient(0, 0, 0, 0, 1, true, CycleMethod.NO_CYCLE, new Stop(0.0, Color.rgb(0, 255, 255, 0.25)), new Stop(0.5, Color.rgb(0, 255, 255, 0.5)), new Stop(1.0, Color.rgb(0, 0, 255, 0.75))), Color.TRANSPARENT);
series2.setWithWrapping(true);
List<Category> categories = new ArrayList<>();
for (int i = 0 ; i < ELEMENTS ; i++) {
categories.add(new Category("P" + i));
}
chart = new YChart(new YPane(categories, series1, series2, series3));
chart.setPrefSize(600, 600);
timeline = new Timeline();
lastTimerCall = System.nanoTime();
timer = new AnimationTimer() {
@Override public void handle(final long now) {
if (now > lastTimerCall + INTERVAL) {
animateData();
long delta = System.nanoTime() - now;
timeline.play();
lastTimerCall = now + delta;
}
}
};
registerListener();
}
private void registerListener() {
timeline.currentTimeProperty().addListener(o -> chart.refresh());
}
@Override public void start(Stage stage) {
StackPane pane = new StackPane(chart);
Scene scene = new Scene(pane);
stage.setTitle("RadarChart");
stage.setScene(scene);
stage.show();
timer.start();
}
@Override public void stop() {
System.exit(0);
}
private void animateData() {
List<KeyFrame> keyFrames = new ArrayList<>();
animateSeries(series1, keyFrames);
animateSeries(series2, keyFrames);
animateSeries(series3, keyFrames);
timeline.getKeyFrames().setAll(keyFrames);
}
private void animateSeries(final YSeries<ValueChartItem> SERIES, final List<KeyFrame> KEY_FRAMES) {
SERIES.getItems().forEach(item -> {
KeyValue kv0 = new KeyValue(item.valueProperty(), item.getValue());
KeyValue kv1 = new KeyValue(item.valueProperty(), RND.nextDouble() * 100);
KeyFrame kf0 = new KeyFrame(Duration.ZERO, kv0);
KeyFrame kf1 = new KeyFrame(Duration.millis(ANIM_TIME), kv1);
KEY_FRAMES.add(kf0);
KEY_FRAMES.add(kf1);
});
}
public static void main(String[] args) {
launch(args);
}
}
| 2,561 |
14,668 | <gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.metrics_settings;
import android.os.Bundle;
import androidx.preference.PreferenceFragmentCompat;
import org.chromium.components.browser_ui.settings.SettingsUtils;
/**
* Settings fragment for metrics. This class represents a View in the MVC paradigm.
*/
public class MetricsSettingsFragment extends PreferenceFragmentCompat {
/**
* Initializes all the objects related to the preferences page.
*/
@Override
public void onCreatePreferences(Bundle bundle, String s) {
// Add all preferences and set the title.
getActivity().setTitle(R.string.prefs_metrics_settings);
SettingsUtils.addPreferencesFromResource(this, R.xml.metrics_preferences);
}
}
| 284 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "sal/config.h"
#include <vector>
#include "boost/noncopyable.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppu/unotype.hxx"
#include "osl/diagnose.h"
#include "rtl/byteseq.hxx"
#include "rtl/string.hxx"
#include "rtl/textcvt.h"
#include "rtl/textenc.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "typelib/typeclass.h"
#include "typelib/typedescription.h"
#include "typelib/typedescription.hxx"
#include "uno/dispatcher.hxx"
#include "binaryany.hxx"
#include "bridge.hxx"
#include "cache.hxx"
#include "lessoperators.hxx"
#include "marshal.hxx"
namespace binaryurp {
namespace {
namespace css = com::sun::star;
void write64(std::vector< unsigned char > * buffer, sal_uInt64 value) {
Marshal::write8(buffer, value >> 56);
Marshal::write8(buffer, (value >> 48) & 0xFF);
Marshal::write8(buffer, (value >> 40) & 0xFF);
Marshal::write8(buffer, (value >> 32) & 0xFF);
Marshal::write8(buffer, (value >> 24) & 0xFF);
Marshal::write8(buffer, (value >> 16) & 0xFF);
Marshal::write8(buffer, (value >> 8) & 0xFF);
Marshal::write8(buffer, value & 0xFF);
}
void writeCompressed(std::vector< unsigned char > * buffer, sal_uInt32 value) {
if (value < 0xFF) {
Marshal::write8(buffer, static_cast< sal_uInt8 >(value));
} else {
Marshal::write8(buffer, 0xFF);
Marshal::write32(buffer, value);
}
}
void writeString(
std::vector< unsigned char > * buffer, rtl::OUString const & value)
{
OSL_ASSERT(buffer != 0);
rtl::OString v;
if (!value.convertToString(
&v, RTL_TEXTENCODING_UTF8,
(RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |
RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR)))
{
throw css::uno::RuntimeException(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"UNO string contains invalid UTF-16 sequence")),
css::uno::Reference< css::uno::XInterface >());
}
writeCompressed(buffer, static_cast< sal_uInt32 >(v.getLength()));
buffer->insert(buffer->end(), v.getStr(), v.getStr() + v.getLength());
}
}
Marshal::Marshal(rtl::Reference< Bridge > const & bridge, WriterState & state):
bridge_(bridge), state_(state)
{
OSL_ASSERT(bridge.is());
}
Marshal::~Marshal() {}
void Marshal::write8(std::vector< unsigned char > * buffer, sal_uInt8 value) {
OSL_ASSERT(buffer != 0);
buffer->push_back(value);
}
void Marshal::write16(std::vector< unsigned char > * buffer, sal_uInt16 value) {
write8(buffer, value >> 8);
write8(buffer, value & 0xFF);
}
void Marshal::write32(std::vector< unsigned char > * buffer, sal_uInt32 value) {
write8(buffer, value >> 24);
write8(buffer, (value >> 16) & 0xFF);
write8(buffer, (value >> 8) & 0xFF);
write8(buffer, value & 0xFF);
}
void Marshal::writeValue(
std::vector< unsigned char > * buffer,
css::uno::TypeDescription const & type, BinaryAny const & value)
{
OSL_ASSERT(
type.is() &&
(type.get()->eTypeClass == typelib_TypeClass_ANY ||
value.getType().equals(type)));
writeValue(buffer, type, value.getValue(type));
}
void Marshal::writeType(
std::vector< unsigned char > * buffer,
css::uno::TypeDescription const & value)
{
value.makeComplete();
OSL_ASSERT(value.is());
typelib_TypeClass tc = value.get()->eTypeClass;
if (tc <= typelib_TypeClass_ANY) {
write8(buffer, static_cast< sal_uInt8 >(tc));
} else {
bool found;
sal_uInt16 idx = state_.typeCache.add(value, &found);
if (found) {
write8(buffer, static_cast< sal_uInt8 >(tc));
write16(buffer, idx);
} else {
write8(buffer, static_cast< sal_uInt8 >(tc) | 0x80);
write16(buffer, idx);
writeString(buffer, rtl::OUString(value.get()->pTypeName));
}
}
}
void Marshal::writeOid(
std::vector< unsigned char > * buffer, rtl::OUString const & oid)
{
bool found;
sal_uInt16 idx;
if ( oid.isEmpty() ) {
found = true;
idx = cache::ignore;
} else {
idx = state_.oidCache.add(oid, &found);
}
if (found) {
write8(buffer, 0);
} else {
writeString(buffer, oid);
}
write16(buffer, idx);
}
void Marshal::writeTid(
std::vector< unsigned char > * buffer, rtl::ByteSequence const & tid)
{
bool found;
sal_uInt16 idx = state_.tidCache.add(tid, &found);
if (found) {
write8(buffer, 0);
} else {
sal_Sequence * p = tid.getHandle();
writeValue(
buffer,
css::uno::TypeDescription(
cppu::UnoType< css::uno::Sequence< sal_Int8 > >::get()), &p);
}
write16(buffer, idx);
}
void Marshal::writeValue(
std::vector< unsigned char > * buffer,
css::uno::TypeDescription const & type, void const * value)
{
OSL_ASSERT(buffer != 0 && type.is());
type.makeComplete();
switch (type.get()->eTypeClass) {
case typelib_TypeClass_VOID:
break;
case typelib_TypeClass_BOOLEAN:
OSL_ASSERT(*static_cast< sal_uInt8 const * >(value) <= 1);
// fall through
case typelib_TypeClass_BYTE:
write8(buffer, *static_cast< sal_uInt8 const * >(value));
break;
case typelib_TypeClass_SHORT:
case typelib_TypeClass_UNSIGNED_SHORT:
case typelib_TypeClass_CHAR:
write16(buffer, *static_cast< sal_uInt16 const * >(value));
break;
case typelib_TypeClass_LONG:
case typelib_TypeClass_UNSIGNED_LONG:
case typelib_TypeClass_FLOAT:
case typelib_TypeClass_ENUM:
write32(buffer, *static_cast< sal_uInt32 const * >(value));
break;
case typelib_TypeClass_HYPER:
case typelib_TypeClass_UNSIGNED_HYPER:
case typelib_TypeClass_DOUBLE:
write64(buffer, *static_cast< sal_uInt64 const * >(value));
break;
case typelib_TypeClass_STRING:
writeString(
buffer,
rtl::OUString(*static_cast< rtl_uString * const * >(value)));
break;
case typelib_TypeClass_TYPE:
writeType(
buffer,
css::uno::TypeDescription(
*static_cast< typelib_TypeDescriptionReference * const * >(
value)));
break;
case typelib_TypeClass_ANY:
{
uno_Any const * p = static_cast< uno_Any const * >(value);
css::uno::TypeDescription t(p->pType);
writeType(buffer, t);
writeValue(buffer, t, p->pData);
break;
}
case typelib_TypeClass_SEQUENCE:
{
sal_Sequence * p = *static_cast< sal_Sequence * const * >(value);
writeCompressed(buffer, static_cast< sal_uInt32 >(p->nElements));
css::uno::TypeDescription ctd(
reinterpret_cast< typelib_IndirectTypeDescription * >(
type.get())->
pType);
OSL_ASSERT(ctd.is());
if (ctd.get()->eTypeClass == typelib_TypeClass_BYTE) {
buffer->insert(
buffer->end(), p->elements, p->elements + p->nElements);
} else {
for (sal_Int32 i = 0; i != p->nElements; ++i) {
writeValue(buffer, ctd, p->elements + i * ctd.get()->nSize);
}
}
break;
}
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
writeMemberValues(buffer, type, value);
break;
case typelib_TypeClass_INTERFACE:
writeOid(
buffer,
bridge_->registerOutgoingInterface(
css::uno::UnoInterfaceReference(
*static_cast< uno_Interface * const * >(value)),
type));
break;
default:
OSL_ASSERT(false); // this cannot happen
break;
}
}
void Marshal::writeMemberValues(
std::vector< unsigned char > * buffer,
css::uno::TypeDescription const & type, void const * aggregateValue)
{
OSL_ASSERT(
type.is() &&
(type.get()->eTypeClass == typelib_TypeClass_STRUCT ||
type.get()->eTypeClass == typelib_TypeClass_EXCEPTION) &&
aggregateValue != 0);
type.makeComplete();
typelib_CompoundTypeDescription * ctd =
reinterpret_cast< typelib_CompoundTypeDescription * >(type.get());
if (ctd->pBaseTypeDescription != 0) {
writeMemberValues(
buffer,
css::uno::TypeDescription(&ctd->pBaseTypeDescription->aBase),
aggregateValue);
}
for (sal_Int32 i = 0; i != ctd->nMembers; ++i) {
writeValue(
buffer, css::uno::TypeDescription(ctd->ppTypeRefs[i]),
(static_cast< char const * >(aggregateValue) +
ctd->pMemberOffsets[i]));
}
}
}
| 4,399 |
14,668 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_POLICY_EXTERNAL_DATA_HANDLERS_DEVICE_CLOUD_EXTERNAL_DATA_POLICY_HANDLER_H_
#define CHROME_BROWSER_ASH_POLICY_EXTERNAL_DATA_HANDLERS_DEVICE_CLOUD_EXTERNAL_DATA_POLICY_HANDLER_H_
#include "chrome/browser/ash/policy/external_data/device_cloud_external_data_policy_observer.h"
namespace policy {
// Base class for handling per-device external resources like wallpaper or
// printers configuration.
class DeviceCloudExternalDataPolicyHandler
: public DeviceCloudExternalDataPolicyObserver::Delegate {
public:
DeviceCloudExternalDataPolicyHandler();
DeviceCloudExternalDataPolicyHandler(
const DeviceCloudExternalDataPolicyHandler&) = delete;
DeviceCloudExternalDataPolicyHandler& operator=(
const DeviceCloudExternalDataPolicyHandler&) = delete;
virtual void Shutdown() = 0;
};
} // namespace policy
#endif // CHROME_BROWSER_ASH_POLICY_EXTERNAL_DATA_HANDLERS_DEVICE_CLOUD_EXTERNAL_DATA_POLICY_HANDLER_H_
| 366 |
678 | /*
* uid.c
*
* uid handling routines
* By <NAME> <<EMAIL>> 4/6/06
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
/* required for seteuid(2)/setegid(2) */
#define _BSD_SOURCE
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <tcl.h>
#include "uid.h"
/*
getuid
synopsis: getuid
*/
int getuidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
/* Check the arg count */
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tcl_NewLongObj(getuid()));
return TCL_OK;
}
/*
geteuid
synopsis: geteuid
*/
int geteuidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
/* Check the arg count */
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tcl_NewLongObj(geteuid()));
return TCL_OK;
}
/*
getgid
*/
int getgidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tcl_NewLongObj(getgid()));
return TCL_OK;
}
/*
getegid
*/
int getegidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
Tcl_SetObjResult(interp, Tcl_NewLongObj(getegid()));
return TCL_OK;
}
/*
setuid
synopsis: setuid uid
*/
int setuidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
long uid = 0;
/* Check the arg count */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "uid");
return TCL_ERROR;
}
/* Get the new uid */
if (TCL_OK != Tcl_GetLongFromObj(interp, objv[1], &uid))
return TCL_ERROR;
/* set the uid */
if (0 != setuid(uid)) {
char buffer[128];
snprintf(buffer, sizeof(buffer), "could not set uid to %ld: %d %s", uid, errno, strerror(errno));
Tcl_SetObjResult(interp, Tcl_NewStringObj(buffer, -1));
return TCL_ERROR;
}
return TCL_OK;
}
/*
seteuid
synopsis: seteuid uid
*/
int seteuidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
long uid = 0;
/* Check the arg count */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "uid");
return TCL_ERROR;
}
/* Get the new euid */
if (TCL_OK != Tcl_GetLongFromObj(interp, objv[1], &uid))
return TCL_ERROR;
/* set the euid */
if (0 != seteuid(uid)) {
char buffer[128];
snprintf(buffer, sizeof(buffer), "could not set effective uid to %ld: %d %s", uid, errno, strerror(errno));
Tcl_SetObjResult(interp, Tcl_NewStringObj(buffer, -1));
return TCL_ERROR;
}
return TCL_OK;
}
/*
setgid
*/
int setgidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
long gid;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "gid");
return TCL_ERROR;
}
if (TCL_OK != Tcl_GetLongFromObj(interp, objv[1], &gid)) {
return TCL_ERROR;
}
if (0 != setgid(gid)) {
char buffer[128];
snprintf(buffer, sizeof(buffer), "could not set gid to %ld: %d %s", gid, errno, strerror(errno));
Tcl_SetObjResult(interp, Tcl_NewStringObj(buffer, -1));
return TCL_ERROR;
}
return TCL_OK;
}
/*
setegid
*/
int setegidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
long gid;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "gid");
return TCL_ERROR;
}
if (TCL_OK != Tcl_GetLongFromObj(interp, objv[1], &gid)) {
return TCL_ERROR;
}
if (0 != setegid(gid)) {
char buffer[128];
snprintf(buffer, sizeof(buffer), "could not set effective gid to %ld: %d %s", gid, errno, strerror(errno));
Tcl_SetObjResult(interp, Tcl_NewStringObj(buffer, -1));
return TCL_ERROR;
}
return TCL_OK;
}
/**
* wrapper around getpwuid(3)
*
* getpwuid <uid> [<field>]
*
*/
int getpwuidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
uid_t uid;
const char *field = NULL;
struct passwd *pw;
Tcl_Obj *result;
/* Check the arg count */
if (objc < 2 || objc > 3) {
Tcl_WrongNumArgs(interp, 1, objv, "getpwuid uid ?field?");
return TCL_ERROR;
}
/* Need to cast uid from int to unsigned int */
if (Tcl_GetIntFromObj(interp, objv[1], (int *) &uid) != TCL_OK) {
Tcl_SetResult(interp, "invalid uid", TCL_STATIC);
return TCL_ERROR;
}
if (objc == 3) {
field = Tcl_GetString(objv[2]);
}
pw = getpwuid(uid);
if (pw == NULL) {
result = Tcl_NewStringObj("getpwuid failed for ", -1);
Tcl_AppendObjToObj(result, Tcl_NewIntObj(uid));
Tcl_SetObjResult(interp, result);
return TCL_ERROR;
}
if (field == NULL) {
Tcl_Obj *reslist;
reslist = Tcl_NewListObj(0, NULL);
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("name", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj(pw->pw_name, -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("passwd", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj(pw->pw_passwd, -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("uid", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewIntObj(pw->pw_uid));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("gid", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewIntObj(pw->pw_gid));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("gecos", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj(pw->pw_gecos, -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("dir", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj(pw->pw_dir, -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("shell", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj(pw->pw_shell, -1));
#ifdef __APPLE__
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("change", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewLongObj(pw->pw_change));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("class", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj(pw->pw_class, -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewStringObj("expire", -1));
Tcl_ListObjAppendElement(interp, reslist, Tcl_NewLongObj(pw->pw_expire));
#endif
Tcl_SetObjResult(interp, reslist);
return TCL_OK;
}
if (strcmp(field, "name") == 0) {
Tcl_SetResult(interp, pw->pw_name, TCL_VOLATILE);
return TCL_OK;
} else if (strcmp(field, "passwd") == 0) {
Tcl_SetResult(interp, pw->pw_passwd, TCL_VOLATILE);
return TCL_OK;
} else if (strcmp(field, "uid") == 0) {
Tcl_SetObjResult(interp, Tcl_NewIntObj(pw->pw_uid));
return TCL_OK;
} else if (strcmp(field, "gid") == 0) {
Tcl_SetObjResult(interp, Tcl_NewIntObj(pw->pw_gid));
return TCL_OK;
} else if (strcmp(field, "gecos") == 0) {
Tcl_SetResult(interp, pw->pw_gecos, TCL_VOLATILE);
return TCL_OK;
} else if (strcmp(field, "dir") == 0) {
Tcl_SetResult(interp, pw->pw_dir, TCL_VOLATILE);
return TCL_OK;
} else if (strcmp(field, "shell") == 0) {
Tcl_SetResult(interp, pw->pw_shell, TCL_VOLATILE);
return TCL_OK;
#ifdef __APPLE__
} else if (strcmp(field, "change") == 0) {
Tcl_SetObjResult(interp, Tcl_NewLongObj(pw->pw_change));
return TCL_OK;
} else if (strcmp(field, "class") == 0) {
Tcl_SetResult(interp, pw->pw_class, TCL_VOLATILE);
return TCL_OK;
} else if (strcmp(field, "expire") == 0) {
Tcl_SetObjResult(interp, Tcl_NewLongObj(pw->pw_expire));
return TCL_OK;
#endif
}
result = Tcl_NewStringObj("invalid field ", -1);
Tcl_AppendObjToObj(result, Tcl_NewStringObj(field, -1));
Tcl_SetObjResult(interp, result);
return TCL_ERROR;
}
/*
name_to_uid
synopsis: name_to_uid name
*/
int name_to_uidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
struct passwd *pwent;
char* name = NULL;
/* Check the arg count */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "name");
return TCL_ERROR;
}
/* Get the name */
name = Tcl_GetString(objv[1]);
if (name == NULL || !*name)
return TCL_ERROR;
/* Map the name --> uid */
pwent = getpwnam(name);
if (pwent == NULL)
Tcl_SetObjResult(interp, Tcl_NewIntObj(-1));
else
Tcl_SetObjResult(interp, Tcl_NewIntObj(pwent->pw_uid));
return TCL_OK;
}
/*
uid_to_name
synopsis: uid_to_name uid
*/
int uid_to_nameCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
long uid = 0;
struct passwd *pwent;
/* Check the arg count */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "uid");
return TCL_ERROR;
}
/* Get the uid */
if (TCL_OK != Tcl_GetLongFromObj(interp, objv[1], &uid))
return TCL_ERROR;
/* Map the uid --> name, or empty result on error */
pwent = getpwuid(uid);
if (pwent != NULL)
Tcl_SetResult(interp, pwent->pw_name, TCL_STATIC);
return TCL_OK;
}
/*
uname_to_gid
synopsis: uname_to_gid name
this function takes a *user* name
*/
int uname_to_gidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
struct passwd *pwent;
char* name = NULL;
/* Check the arg count */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "name");
return TCL_ERROR;
}
/* Get the name */
name = Tcl_GetString(objv[1]);
if (name == NULL || !*name)
return TCL_ERROR;
/* Map the name --> user gid */
pwent = getpwnam(name);
if (pwent == NULL)
Tcl_SetObjResult(interp, Tcl_NewIntObj(-1));
else
Tcl_SetObjResult(interp, Tcl_NewIntObj(pwent->pw_gid));
return TCL_OK;
}
/*
name_to_gid
synopsis: name_to_gid name
this function takes a *group* name
*/
int name_to_gidCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
struct group *grent;
char *name;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "name");
return TCL_ERROR;
}
name = Tcl_GetString(objv[1]);
if (name == NULL || !*name)
return TCL_ERROR;
grent = getgrnam(name);
if (grent == NULL)
Tcl_SetObjResult(interp, Tcl_NewIntObj(-1));
else
Tcl_SetObjResult(interp, Tcl_NewIntObj(grent->gr_gid));
return TCL_OK;
}
/*
gid_to_name
*/
int gid_to_nameCmd(ClientData clientData UNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
long gid;
struct group *grent;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "gid");
return TCL_ERROR;
}
if (TCL_OK != Tcl_GetLongFromObj(interp, objv[1], &gid))
return TCL_ERROR;
grent = getgrgid(gid);
if (grent != NULL)
Tcl_SetResult(interp, grent->gr_name, TCL_STATIC);
return TCL_OK;
}
| 5,585 |
1,442 | <filename>escher/include/escher/message_table_cell.h
#ifndef ESCHER_MESSAGE_TABLE_CELL_H
#define ESCHER_MESSAGE_TABLE_CELL_H
#include <escher/message_text_view.h>
#include <escher/i18n.h>
#include <escher/table_cell.h>
namespace Escher {
class MessageTableCell : public TableCell {
public:
MessageTableCell(I18n::Message label = (I18n::Message)0);
const View * labelView() const override { return &m_messageTextView; }
void setHighlighted(bool highlight) override;
void setMessage(I18n::Message message);
void setTextColor(KDColor color);
void setMessageFont(const KDFont * font);
void setBackgroundColor(KDColor color);
protected:
KDColor backgroundColor() const override { return m_backgroundColor; }
private:
MessageTextView m_messageTextView;
KDColor m_backgroundColor;
};
}
#endif
| 277 |
846 | <filename>src/main/java/com/alibaba/compileflow/engine/process/preruntime/generator/impl/tbbpm/LoopProcessGenerator.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 com.alibaba.compileflow.engine.process.preruntime.generator.impl.tbbpm;
import com.alibaba.compileflow.engine.common.CompileFlowException;
import com.alibaba.compileflow.engine.definition.tbbpm.LoopProcessNode;
import com.alibaba.compileflow.engine.common.ClassWrapper;
import com.alibaba.compileflow.engine.process.preruntime.generator.code.CodeTargetSupport;
import com.alibaba.compileflow.engine.process.preruntime.generator.factory.GeneratorFactory;
import com.alibaba.compileflow.engine.runtime.impl.AbstractProcessRuntime;
import org.apache.commons.lang.StringUtils;
/**
* @author pin
* @author yusu
*/
public class LoopProcessGenerator extends AbstractTbbpmNodeGenerator<LoopProcessNode> {
private static final String LOOP_FOR = "loop";
private static final String LOOP_WHILE = "while";
public LoopProcessGenerator(AbstractProcessRuntime runtime,
LoopProcessNode flowNode) {
super(runtime, flowNode);
}
@Override
public void generateCode(CodeTargetSupport codeTargetSupport) {
String loopType = flowNode.getLoopType();
String index = flowNode.getIndexVarName();
if (StringUtils.isEmpty(loopType) || loopType.equals(LOOP_FOR)) {
String collectionVarName = flowNode.getCollectionVarName();
String varName = flowNode.getVariableName();
String varClass = flowNode.getVariableClass();
if (varClass != null) {
addImportedType(codeTargetSupport, varClass);
ClassWrapper classWrapper = ClassWrapper.of(varClass);
varClass = classWrapper.getShortName();
} else {
varClass = "Object";
}
String foreachCondition = "for (" + varClass + " " + varName + " : " + collectionVarName + ") {";
if (StringUtils.isNotEmpty(index)) {
codeTargetSupport.addBodyLine("int " + index + " = -1;");
codeTargetSupport.addBodyLine(foreachCondition);
codeTargetSupport.addBodyLine(index + "++;");
} else {
codeTargetSupport.addBodyLine(foreachCondition);
}
} else if (loopType.equals(LOOP_WHILE)) {
String loopExpr = flowNode.getWhileExpression();
if (StringUtils.isNotEmpty(index)) {
codeTargetSupport.addBodyLine("int " + index + " = 0;");
String whileCondition = "for (; " + loopExpr + "; " + index + "++) {";
codeTargetSupport.addBodyLine(whileCondition);
} else {
String whileCondition = "for (; " + loopExpr + ";) {";
codeTargetSupport.addBodyLine(whileCondition);
}
} else {
throw new CompileFlowException("Unsupported loop type: " + loopType);
}
GeneratorFactory.getInstance().getContainerGenerator(flowNode, runtime).generateCode(codeTargetSupport);
codeTargetSupport.addBodyLine("}");
}
}
| 1,469 |
3,182 | <filename>src/main/java/de/plushnikov/intellij/plugin/action/delombok/DelombokDataAction.java
package de.plushnikov.intellij.plugin.action.delombok;
import com.intellij.openapi.application.ApplicationManager;
import de.plushnikov.intellij.plugin.processor.clazz.DataProcessor;
import org.jetbrains.annotations.NotNull;
public class DelombokDataAction extends AbstractDelombokAction {
@Override
@NotNull
protected DelombokHandler createHandler() {
return new DelombokHandler(ApplicationManager.getApplication().getService(DataProcessor.class));
}
}
| 176 |
1,856 | <gh_stars>1000+
#ifdef LINUX
#define LOG_MODULE UndefinedLogModule
#include "Logger.h"
#include "LinuxNicInformationSocket.h"
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <cerrno>
#include <cstdio>
#include <cstring>
#define INVALID_SOCKET_VALUE (-1)
namespace pcpp
{
static inline LinuxNicInformationSocket::LinuxSocket
openLinuxNicInformationSocket()
{
LinuxNicInformationSocket::LinuxSocket soc = socket(AF_INET, SOCK_DGRAM, 0);
if (soc < 0)
{
const char* error = std::strerror(errno);
LOG_DEBUG("Can't open Linux information socket. Errno string: "<< error);
return soc = INVALID_SOCKET_VALUE;
}
return soc;
}
LinuxNicInformationSocket::LinuxNicInformationSocket() :
m_Socket(openLinuxNicInformationSocket())
{}
LinuxNicInformationSocket::~LinuxNicInformationSocket()
{
if (m_Socket == INVALID_SOCKET_VALUE)
{
LOG_DEBUG("Closing not opened Linux NIC information socket");
}
else
{
close(m_Socket);
}
}
bool LinuxNicInformationSocket::makeRequest(
const char* nicName,
const IoctlType ioctlType,
ifreq* request
)
{
if (m_Socket == INVALID_SOCKET_VALUE)
{
m_Socket = openLinuxNicInformationSocket();
if (m_Socket == INVALID_SOCKET_VALUE)
{
LOG_ERROR(
"Request to Linux NIC incformation socket failed. "
"Can't open socket"
);
return false;
}
}
snprintf(request->ifr_name, IFNAMSIZ, "%s", nicName);
if (ioctl(m_Socket, ioctlType, request))
{
const char* error = std::strerror(errno);
LOG_ERROR(
"Request to Linux NIC incformation socket failed. "
"ioctl(2) failed with error string: "
<< error
);
return false;
}
return true;
}
} // namespace pcpp
#endif /* LINUX */ | 660 |
2,109 | /*
* This software is Copyright (c) 2013 magnum, and it is hereby released to the
* general public under the following terms: Redistribution and use in source
* and binary forms, with or without modification, are permitted.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_rakp;
#elif FMT_REGISTERS_H
john_register_one(&fmt_rakp);
#else
#include <string.h>
#include "arch.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 2048 // tuned for i7 using SSE2 and w/o HT
#endif
#endif
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "sha.h"
#include "johnswap.h"
#include "simd-intrinsics.h"
#include "memdbg.h"
#define FORMAT_LABEL "RAKP"
#define FORMAT_NAME "IPMI 2.0 RAKP (RMCP+)"
#ifdef SIMD_COEF_32
#define SHA1_N (SIMD_PARA_SHA1 * SIMD_COEF_32)
#endif
#define ALGORITHM_NAME "HMAC-SHA1 " SHA1_ALGORITHM_NAME
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 125
#define PAD_SIZE 64
#define BINARY_SIZE 20
#define BINARY_ALIGN sizeof(uint32_t)
#define SALT_LENGTH (2 * PAD_SIZE)
#define SALT_ALIGN MEM_ALIGN_NONE
#define SALT_MIN_SIZE (PAD_SIZE - 8)
#define SALT_MAX_SIZE (2 * PAD_SIZE - 8 - 1)
#define FORMAT_TAG "$rakp$"
#define TAG_LENGTH (sizeof(FORMAT_TAG) - 1)
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT SHA1_N
#define MAX_KEYS_PER_CRYPT SHA1_N
#define GETPOS(i, index) ((index & (SIMD_COEF_32 - 1)) * 4 + ((i) & (0xffffffff - 3)) * SIMD_COEF_32 + (3 - ((i) & 3)) + (unsigned int)index/SIMD_COEF_32 * SHA_BUF_SIZ * 4 * SIMD_COEF_32)
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
static struct fmt_tests tests[] = {
{"$rakp$a4a3a2a03f0b000094272eb1ba576450b0d98ad10727a9fb0ab83616e099e8bf5f7366c9c03d36a3000000000000000000000000000000001404726f6f74$0ea27d6d5effaa996e5edc855b944e179a2f2434", "calvin"},
{"$rakp$c358d2a72f0c00001135f9b254c274629208b22f1166d94d2eba47f21093e9734355a33593da16f2000000000000000000000000000000001404726f6f74$41fce60acf2885f87fcafdf658d6f97db12639a9", "calvin"},
{"$rakp$b7c2d6f13a43dce2e44ad120a9cd8a13d0ca23f0414275c0bbe1070d2d1299b1c04da0f1a0f1e4e2537300263a2200000000000000000000140768617368636174$472bdabe2d5d4bffd6add7b3ba79a291d104a9ef", "hashcat"},
/* dummy hash for testing long salts */
{"$rakp$787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878$ba4ecc30a0b36a6ba0db862fc95201a81b9252ee", ""},
{NULL}
};
#ifdef SIMD_COEF_32
#define cur_salt rakp_cur_salt
static unsigned char *crypt_key;
static unsigned char *ipad, *prep_ipad;
static unsigned char *opad, *prep_opad;
JTR_ALIGN(MEM_ALIGN_SIMD) unsigned char cur_salt[2][SHA_BUF_SIZ * 4 * SHA1_N];
static int bufsize;
#else
static struct {
int length;
unsigned char salt[SALT_LENGTH];
} cur_salt;
static uint32_t (*crypt_key)[BINARY_SIZE / sizeof(uint32_t)];
static unsigned char (*ipad)[PAD_SIZE];
static unsigned char (*opad)[PAD_SIZE];
static SHA_CTX *ipad_ctx;
static SHA_CTX *opad_ctx;
#endif
static char (*saved_plain)[PLAINTEXT_LENGTH + 1];
static int new_keys;
#define SALT_SIZE sizeof(cur_salt)
#ifdef SIMD_COEF_32
static void clear_keys(void)
{
memset(ipad, 0x36, bufsize);
memset(opad, 0x5C, bufsize);
}
#endif
static void init(struct fmt_main *self)
{
#ifdef SIMD_COEF_32
int i;
#endif
#ifdef _OPENMP
int omp_t = omp_get_num_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
#ifdef SIMD_COEF_32
bufsize = sizeof(*opad) * self->params.max_keys_per_crypt * SHA_BUF_SIZ * 4;
crypt_key = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD);
ipad = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD);
opad = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD);
prep_ipad = mem_calloc_align(self->params.max_keys_per_crypt *
BINARY_SIZE,
sizeof(*prep_ipad), MEM_ALIGN_SIMD);
prep_opad = mem_calloc_align(self->params.max_keys_per_crypt *
BINARY_SIZE,
sizeof(*prep_opad), MEM_ALIGN_SIMD);
for (i = 0; i < self->params.max_keys_per_crypt; ++i) {
crypt_key[GETPOS(BINARY_SIZE, i)] = 0x80;
((unsigned int*)crypt_key)[15 * SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32 * SHA_BUF_SIZ * SIMD_COEF_32] = (BINARY_SIZE + 64) << 3;
}
clear_keys();
#else
crypt_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_key));
ipad = mem_calloc(self->params.max_keys_per_crypt, sizeof(*ipad));
opad = mem_calloc(self->params.max_keys_per_crypt, sizeof(*opad));
ipad_ctx = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*ipad_ctx));
opad_ctx = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*opad_ctx));
#endif
saved_plain = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_plain));
}
static void done(void)
{
MEM_FREE(saved_plain);
#ifdef SIMD_COEF_32
MEM_FREE(prep_opad);
MEM_FREE(prep_ipad);
#else
MEM_FREE(opad_ctx);
MEM_FREE(ipad_ctx);
#endif
MEM_FREE(opad);
MEM_FREE(ipad);
MEM_FREE(crypt_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *p, *q = NULL;
int len;
p = ciphertext;
if (!strncmp(p, FORMAT_TAG, TAG_LENGTH))
p += TAG_LENGTH;
q = strrchr(ciphertext, '$');
if (!q)
return 0;
q = q + 1;
if ((q - p - 1) > SALT_MAX_SIZE * 2)
return 0;
if ((q - p - 1) < SALT_MIN_SIZE * 2)
return 0;
len = strspn(q, HEXCHARS_lc);
if (len != BINARY_SIZE * 2 || len != strlen(q))
return 0;
if (strspn(p, HEXCHARS_lc) != q - p - 1)
return 0;
return 1;
}
static void set_salt(void *salt)
{
memcpy(&cur_salt, salt, SALT_SIZE);
}
static void set_key(char *key, int index)
{
int len;
#ifdef SIMD_COEF_32
uint32_t *ipadp = (uint32_t*)&ipad[GETPOS(3, index)];
uint32_t *opadp = (uint32_t*)&opad[GETPOS(3, index)];
const uint32_t *keyp = (uint32_t*)key;
unsigned int temp;
len = strlen(key);
memcpy(saved_plain[index], key, len);
saved_plain[index][len] = 0;
if (len > PAD_SIZE) {
unsigned char k0[BINARY_SIZE];
SHA_CTX ctx;
int i;
SHA1_Init(&ctx);
SHA1_Update(&ctx, key, len);
SHA1_Final(k0, &ctx);
keyp = (unsigned int*)k0;
for (i = 0; i < BINARY_SIZE / 4; i++, ipadp += SIMD_COEF_32, opadp += SIMD_COEF_32)
{
temp = JOHNSWAP(*keyp++);
*ipadp ^= temp;
*opadp ^= temp;
}
}
else
while(((temp = JOHNSWAP(*keyp++)) & 0xff000000)) {
if (!(temp & 0x00ff0000) || !(temp & 0x0000ff00))
{
((unsigned short*)ipadp)[1] ^=
(unsigned short)(temp >> 16);
((unsigned short*)opadp)[1] ^=
(unsigned short)(temp >> 16);
break;
}
*ipadp ^= temp;
*opadp ^= temp;
if (!(temp & 0x000000ff))
break;
ipadp += SIMD_COEF_32;
opadp += SIMD_COEF_32;
}
#else
int i;
len = strlen(key);
memcpy(saved_plain[index], key, len);
saved_plain[index][len] = 0;
memset(ipad[index], 0x36, PAD_SIZE);
memset(opad[index], 0x5C, PAD_SIZE);
if (len > PAD_SIZE) {
SHA_CTX ctx;
unsigned char k0[BINARY_SIZE];
SHA1_Init(&ctx);
SHA1_Update(&ctx, key, len);
SHA1_Final(k0, &ctx);
len = BINARY_SIZE;
for (i = 0; i < len; i++)
{
ipad[index][i] ^= k0[i];
opad[index][i] ^= k0[i];
}
}
else
for (i = 0; i < len; i++)
{
ipad[index][i] ^= key[i];
opad[index][i] ^= key[i];
}
#endif
new_keys = 1;
}
static char *get_key(int index)
{
return saved_plain[index];
}
static int cmp_all(void *binary, int count)
{
#ifdef SIMD_COEF_32
unsigned int x, y = 0;
for (;y < (unsigned int)(count + SIMD_COEF_32 - 1) / SIMD_COEF_32; y++)
for (x = 0; x < SIMD_COEF_32; x++)
{
// NOTE crypt_key is in input format (4*SHA_BUF_SIZ*SIMD_COEF_32)
if (((uint32_t*)binary)[0] == ((uint32_t*)crypt_key)[x + y * SIMD_COEF_32 * SHA_BUF_SIZ])
return 1;
}
return 0;
#else
int index = 0;
#if defined(_OPENMP) || (MAX_KEYS_PER_CRYPT > 1)
for (index = 0; index < count; index++)
#endif
if (((uint32_t*)binary)[0] == crypt_key[index][0])
return 1;
return 0;
#endif
}
static int cmp_one(void *binary, int index)
{
#ifdef SIMD_COEF_32
int i;
for (i = 0; i < (BINARY_SIZE/4); i++)
// NOTE crypt_key is in input format (4 * SHA_BUF_SIZ * SIMD_COEF_32)
if (((uint32_t*)binary)[i] != ((uint32_t*)crypt_key)[i * SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32 * SHA_BUF_SIZ * SIMD_COEF_32])
return 0;
return 1;
#else
return !memcmp(binary, crypt_key[index], BINARY_SIZE);
#endif
}
static int cmp_exact(char *source, int index)
{
return (1);
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#if _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT)
#endif
{
#ifdef SIMD_COEF_32
if (new_keys) {
SIMDSHA1body(&ipad[index * SHA_BUF_SIZ * 4],
(unsigned int*)&prep_ipad[index * BINARY_SIZE],
NULL, SSEi_MIXED_IN);
SIMDSHA1body(&opad[index * SHA_BUF_SIZ * 4],
(unsigned int*)&prep_opad[index * BINARY_SIZE],
NULL, SSEi_MIXED_IN);
}
SIMDSHA1body(cur_salt[0],
(unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4],
(unsigned int*)&prep_ipad[index * BINARY_SIZE],
SSEi_MIXED_IN|SSEi_RELOAD|SSEi_OUTPUT_AS_INP_FMT);
SIMDSHA1body(cur_salt[1],
(unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4],
(unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4],
SSEi_MIXED_IN|SSEi_RELOAD_INP_FMT|SSEi_OUTPUT_AS_INP_FMT);
SIMDSHA1body(&crypt_key[index * SHA_BUF_SIZ * 4],
(unsigned int*)&crypt_key[index * SHA_BUF_SIZ * 4],
(unsigned int*)&prep_opad[index * BINARY_SIZE],
SSEi_MIXED_IN|SSEi_RELOAD|SSEi_OUTPUT_AS_INP_FMT);
#else
SHA_CTX ctx;
if (new_keys) {
SHA1_Init(&ipad_ctx[index]);
SHA1_Update(&ipad_ctx[index], ipad[index], PAD_SIZE);
SHA1_Init(&opad_ctx[index]);
SHA1_Update(&opad_ctx[index], opad[index], PAD_SIZE);
}
memcpy(&ctx, &ipad_ctx[index], sizeof(ctx));
SHA1_Update(&ctx, cur_salt.salt, cur_salt.length);
SHA1_Final((unsigned char*) crypt_key[index], &ctx);
memcpy(&ctx, &opad_ctx[index], sizeof(ctx));
SHA1_Update(&ctx, crypt_key[index], BINARY_SIZE);
SHA1_Final((unsigned char*) crypt_key[index], &ctx);
#endif
}
new_keys = 0;
return count;
}
static void *get_binary(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
p = strrchr(ciphertext, '$') + 1;
for (i = 0; i < BINARY_SIZE; i++) {
out[i] = (atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
#ifdef SIMD_COEF_32
alter_endianity(out, BINARY_SIZE);
#endif
return out;
}
static void *get_salt(char *ciphertext)
{
static unsigned char salt[SALT_LENGTH];
unsigned int i, len;
#ifdef SIMD_COEF_32
unsigned int j;
#endif
memset(salt, 0, sizeof(salt));
memset(&cur_salt, 0, sizeof(cur_salt));
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
ciphertext += TAG_LENGTH;
len = (strrchr(ciphertext, '$') - ciphertext) / 2;
for (i = 0; i < len; i++)
salt[i] = (atoi16[ARCH_INDEX(ciphertext[2 * i])] << 4) |
atoi16[ARCH_INDEX(ciphertext[2 * i + 1])];
#ifdef SIMD_COEF_32
for (i = 0; i < len; i++)
for (j = 0; j < SHA1_N; ++j)
cur_salt[i>>6][GETPOS(i & 63, j)] = ((unsigned char*)salt)[i];
for (i = 0; i < SHA1_N; ++i)
cur_salt[len>>6][GETPOS(len & 63, i)] = 0x80;
for (j = len + 1; j < SALT_LENGTH; ++j)
for (i = 0; i < SHA1_N; ++i)
cur_salt[j>>6][GETPOS(j & 63, i)] = 0;
for (i = 0; i < SHA1_N; ++i)
((unsigned int*)cur_salt[1])[15 * SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32 * SHA_BUF_SIZ * SIMD_COEF_32] = (len + 64) << 3;
return &cur_salt;
#else
cur_salt.length = len;
memcpy(cur_salt.salt, salt, len);
return &cur_salt;
#endif
}
struct fmt_main fmt_rakp = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT,
{ NULL },
{ NULL },
tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
set_key,
get_key,
#ifdef SIMD_COEF_32
clear_keys,
#else
fmt_default_clear_keys,
#endif
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
| 6,487 |
1,561 | // Copyright 1996-2021 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SpeedWidget.hpp"
#include <graph2d/Point2D.hpp>
#include <webots/robot.h>
#include <webots/vehicle/driver.h>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QLabel>
using namespace std;
SpeedWidget::SpeedWidget(QWidget *parent) : AbstractWidget(parent) {
mGraph->setYLabel("Speed [km/h]");
mValueLabel->setText("\n\n");
}
SpeedWidget::~SpeedWidget() {
}
void SpeedWidget::update() {
if (!mEnableCheckBox->isChecked())
return;
mValueLabel->setText("");
if (wbu_driver_get_control_mode() == SPEED) {
double targetSpeed = wbu_driver_get_target_cruising_speed();
mGraph->addPoint2D(Point2D(wb_robot_get_time(), targetSpeed, red()));
mValueLabel->setText("<font color='red'>Target speed: " + QString::number(targetSpeed, 'f', 2) +
QString(" km/h</font><br>"));
}
double speed = wbu_driver_get_current_speed();
mValueLabel->setText(mValueLabel->text() + QString("Current speed: ") + QString::number(speed, 'f', 2) + QString(" km/h"));
mGraph->addPoint2D(Point2D(wb_robot_get_time(), speed));
mGraph->updateXRange();
mGraph->extendYRange();
mGraph->keepNPoints(2 * pointsKeptNumber());
}
| 618 |
746 | <gh_stars>100-1000
package org.protege.editor.owl.ui.editor;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.selector.OWLAnnotationPropertySelectorPanel;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
/*
* Copyright (C) 2007, University of Manchester
*
*
*/
/**
* Author: drummond<br>
* http://www.cs.man.ac.uk/~drummond/<br><br>
* The University Of Manchester<br>
* Bio Health Informatics Group<br>
* Date: Jun 4, 2009<br><br>
*/
public class OWLAnnotationPropertyEditor extends AbstractOWLObjectEditor<OWLAnnotationProperty> {
private OWLAnnotationPropertySelectorPanel editor;
public OWLAnnotationPropertyEditor(OWLEditorKit owlEditorKit) {
editor = new OWLAnnotationPropertySelectorPanel(owlEditorKit);
}
@Nullable
public OWLAnnotationProperty getEditedObject() {
return editor.getSelectedObject();
}
public boolean setEditedObject(OWLAnnotationProperty p){
editor.setSelection(p);
return true;
}
@Nonnull
public String getEditorTypeName() {
return "Annotation Property";
}
public boolean canEdit(Object object) {
return object instanceof OWLAnnotationProperty;
}
@Nonnull
public JComponent getEditorComponent() {
return editor;
}
public void dispose() {
editor.dispose();
}
}
| 546 |
823 | <filename>scripts/convert.py
"""Convert entity annotation from spaCy v2 TRAIN_DATA format to spaCy v3
.spacy format."""
import srsly
import typer
import warnings
from pathlib import Path
import spacy
from spacy.tokens import DocBin
def convert(lang: str, input_path: Path, output_path: Path):
nlp = spacy.blank(lang)
db = DocBin()
for text, annot in srsly.read_json(input_path):
doc = nlp.make_doc(text)
ents = []
for start, end, label in annot["entities"]:
span = doc.char_span(start, end, label=label)
if span is None:
msg = f"Skipping entity [{start}, {end}, {label}] in the following text because the character span '{doc.text[start:end]}' does not align with token boundaries:\n\n{repr(text)}\n"
warnings.warn(msg)
else:
ents.append(span)
doc.ents = ents
db.add(doc)
db.to_disk(output_path)
if __name__ == "__main__":
typer.run(convert)
| 434 |
1,992 | <filename>tests/app.py
#!/bin/env python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
@app.cli.command()
def add():
"""Add test user."""
db.session.add(User(name='test'))
db.session.commit()
if __name__ == '__main__':
app.run()
| 235 |
376 | <reponame>BIGWangYuDong/mmfewshot<filename>configs/detection/tfa/coco/tfa_r101_fpn_coco_base-training.py<gh_stars>100-1000
_base_ = [
'../../_base_/datasets/fine_tune_based/base_coco.py',
'../../_base_/schedules/schedule.py',
'../../_base_/models/faster_rcnn_r50_caffe_fpn.py',
'../../_base_/default_runtime.py'
]
lr_config = dict(warmup_iters=1000, step=[85000, 100000])
runner = dict(max_iters=110000)
# model settings
model = dict(
pretrained='open-mmlab://detectron2/resnet101_caffe',
backbone=dict(depth=101),
roi_head=dict(bbox_head=dict(num_classes=60)))
| 265 |
360 | """Synchronize with Airbyte."""
from dataclasses import dataclass, field
from typing import Any, Dict, Optional
import requests
import time
from requests.exceptions import RequestException
from dbt.logger import GLOBAL_LOGGER as logger
from fal.telemetry import telemetry
class AirbyteJobState:
"""Possibe Airbyte job states."""
RUNNING = "running"
SUCCEEDED = "succeeded"
CANCELLED = "cancelled"
PENDING = "pending"
FAILED = "failed"
ERROR = "error"
INCOMPLETE = "incomplete"
@dataclass
class AirbyteClient:
"""Airbyte REST API connector class."""
host: str
max_retries: int = 5
retry_delay: float = 5
_base_url: str = field(init=False)
def __post_init__(self):
"""Set variables."""
self._base_url = self.host + "/api/v1"
def request(self, endpoint: str, data: Optional[Dict[str, Any]]):
"""Make a request to Airbyte REST API endpoint."""
headers = {"accept": "application/json"}
num_retries = 0
while True:
try:
response = requests.request(
method="POST",
url=self._base_url + endpoint,
headers=headers,
json=data,
timeout=5,
)
response.raise_for_status()
return response.json()
except RequestException as e:
logger.warn(f"Airbyte API request failed: {e}")
if num_retries == self.max_retries:
break
num_retries += 1
time.sleep(self.retry_delay)
raise Exception("Exceeded max number of retries.")
@telemetry.log_call("airbyte_client_sync")
def sync(self, connection_id: str) -> dict:
"""Start Airbyte connection sync."""
return self.request(
endpoint="/connections/sync", data={"connectionId": connection_id}
)
def get_job_status(self, job_id: int) -> dict:
"""Get job status."""
return self.request(endpoint="/jobs/get", data={"id": job_id})
def get_connection_data(self, connection_id: str) -> dict:
"""Get details of a connection."""
return self.request(
endpoint="/connections/get", data={"connectionId": connection_id}
)
@telemetry.log_call("airbyte_client_sync_and_wait")
def sync_and_wait(
self,
connection_id: str,
interval: float = 10,
timeout: float = None,
):
"""Start a sync operation for the given connector, and polls until done."""
connection = self.get_connection_data(connection_id)
job = self.sync(connection_id)
job_id = job.get("job", {}).get("id")
logger.info(f"Job {job_id} started for connection: {connection_id}.")
start = time.monotonic()
while True:
if timeout and start + timeout < time.monotonic():
raise Exception(
f"Timeout: Job {job_id} is not finished after {timeout} seconds"
)
time.sleep(interval)
job_details = self.get_job_status(job_id)
state = job_details.get("job", {}).get("status")
if state in (
AirbyteJobState.RUNNING,
AirbyteJobState.PENDING,
AirbyteJobState.INCOMPLETE,
):
continue
elif state == AirbyteJobState.SUCCEEDED:
break
elif state == AirbyteJobState.ERROR:
raise Exception(f"Job failed: {job_id}")
elif state == AirbyteJobState.CANCELLED:
raise Exception(f"Job cancelled: {job_id}")
else:
raise Exception(f"Unexpected job state `{state}` for job {job_id}")
return {"job_details": job_details, "connection_details": connection}
@telemetry.log_call("airbyte_sync")
def airbyte_sync(
host: str,
connection_id: str,
interval: float = 10,
timeout: float = None,
max_retries: int = 10,
):
"""Sync Airbyte connection."""
api = AirbyteClient(host=host, max_retries=max_retries)
return api.sync_and_wait(connection_id, interval=interval, timeout=timeout)
| 1,936 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-gwwv-284v-w5c5",
"modified": "2022-04-23T00:03:12Z",
"published": "2022-04-16T00:00:42Z",
"aliases": [
"CVE-2021-44510"
],
"details": "An issue was discovered in FIS GT.M through V7.0-000 (related to the YottaDB code base). Using crafted input, attackers can cause a calculation of the size of calls to memset in op_fnj3 in sr_port/op_fnj3.c to result in an extremely large value in order to cause a segmentation fault and crash the application.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-44510"
},
{
"type": "WEB",
"url": "https://gitlab.com/YottaDB/DB/YDB/-/issues/828"
},
{
"type": "WEB",
"url": "https://sourceforge.net/projects/fis-gtm/files/"
},
{
"type": "WEB",
"url": "http://tinco.pair.com/bhaskar/gtm/doc/articles/GTM_V7.0-002_Release_Notes.html"
}
],
"database_specific": {
"cwe_ids": [
"CWE-131"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 587 |
333 | #import "SCAudioManager.h"
| 10 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Villard","circ":"1ère circonscription","dpt":"Creuse","inscrits":282,"abs":155,"votants":127,"blancs":13,"nuls":7,"exp":107,"res":[{"nuance":"LR","nom":"<NAME>","voix":60},{"nuance":"REM","nom":"<NAME>","voix":47}]} | 105 |
391 | <gh_stars>100-1000
package com.sparrowwallet.sparrow.control;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.TreeItem;
import javafx.util.Callback;
import java.util.List;
import java.util.stream.Collectors;
public class RecursiveTreeItem<T> extends TreeItem<T> {
private final Callback<T, ObservableList<T>> childrenFactory;
private final Callback<T, Node> graphicsFactory;
public RecursiveTreeItem(Callback<T, ObservableList<T>> childrenFactory){
this(null, childrenFactory);
}
public RecursiveTreeItem(final T value, Callback<T, ObservableList<T>> childrenFactory){
this(value, (item) -> null, childrenFactory);
}
public RecursiveTreeItem(final T value, Callback<T, Node> graphicsFactory, Callback<T, ObservableList<T>> childrenFactory){
super(value, graphicsFactory.call(value));
this.graphicsFactory = graphicsFactory;
this.childrenFactory = childrenFactory;
if(value != null) {
addChildrenListener(value);
}
valueProperty().addListener((obs, oldValue, newValue)->{
if(newValue != null){
addChildrenListener(newValue);
}
});
this.setExpanded(false);
}
private void addChildrenListener(T value){
final ObservableList<T> children = childrenFactory.call(value);
children.forEach(child -> RecursiveTreeItem.this.getChildren().add(
new RecursiveTreeItem<>(child, this.graphicsFactory, childrenFactory)));
children.addListener((ListChangeListener<T>) change -> {
while(change.next()){
if(change.wasAdded()){
if(change.getFrom() >= RecursiveTreeItem.this.getChildren().size()) {
change.getAddedSubList().forEach(t-> RecursiveTreeItem.this.getChildren().add(new RecursiveTreeItem<>(t, this.graphicsFactory, childrenFactory)));
} else {
change.getAddedSubList().forEach(t-> RecursiveTreeItem.this.getChildren().add(change.getFrom(), new RecursiveTreeItem<>(t, this.graphicsFactory, childrenFactory)));
}
}
if(change.wasRemoved()){
change.getRemoved().forEach(t->{
final List<TreeItem<T>> itemsToRemove = RecursiveTreeItem.this
.getChildren()
.stream()
.filter(treeItem -> treeItem.getValue().equals(t))
.collect(Collectors.toList());
RecursiveTreeItem.this.getChildren().removeAll(itemsToRemove);
});
}
}
});
}
} | 1,273 |
2,962 | <filename>storio-content-resolver-annotations/src/main/java/com/pushtorefresh/storio3/contentresolver/annotations/StorIOContentResolverColumn.java<gh_stars>1000+
package com.pushtorefresh.storio3.contentresolver.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({FIELD, METHOD})
@Retention(RUNTIME)
public @interface StorIOContentResolverColumn {
/**
* Required: specifies column name
*
* @return non-null column name
*/
String name();
/**
* Optional: marks column as key, so it will be used to identify rows for Put and Delete Operations
*
* @return true if column is key, false otherwise
*/
boolean key() default false;
/**
* Optional: indicates that field should not be serialized when its value is {@code null}
* Should be used for not primitive types only
*
* @return true if column with {@code null} value should be ignored, false otherwise
*/
boolean ignoreNull() default false;
}
| 389 |
524 | //
// Created by succlz123 on 2017/10/5.
//
#ifndef BURSTLINKER_DISABLEDITHERERWITHRS_H
#define BURSTLINKER_DISABLEDITHERERWITHRS_H
#include "../../../../../src/Ditherer.h"
#include "DithererWithRs.h"
#include <RenderScript.h>
#include <vector>
using namespace android::RSC;
class DisableDithererWithRs : public DithererWithRs {
public:
void dither(uint32_t *originalColors, int width, int height, unsigned char *quantizerColors,
int quantizerSize, sp<RS> rs) override;
};
#endif //BURSTLINKER_DISABLEDITHERERWITHRS_H
| 222 |
323 | # SPDX-License-Identifier: Apache-2.0
import unittest
from distutils.version import StrictVersion
import numpy as np
from numpy.testing import assert_almost_equal
import scipy
from onnxruntime import InferenceSession, SessionOptions
try:
from onnxruntime.capi.onnxruntime_pybind11_state import Fail as OrtFail
except ImportError:
OrtFail = RuntimeError
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn import __version__ as sklver
try:
from sklearn.gaussian_process import GaussianProcessClassifier
except ImportError:
GaussianProcessClassifier = None
from skl2onnx.common.data_types import FloatTensorType, DoubleTensorType
from skl2onnx import to_onnx
from skl2onnx.helpers.onnx_helper import change_onnx_domain
from test_utils import dump_data_and_model, TARGET_OPSET
sklver_ = ".".join(sklver.split('.')[:2])
class TestSklearnGaussianProcessClassifier(unittest.TestCase):
@classmethod
def setUpClass(cls):
try:
from ortcustomops import (
onnx_op, PyCustomOpDef, get_library_path)
except ImportError:
return
@onnx_op(op_type="SolveFloat",
inputs=[PyCustomOpDef.dt_float, PyCustomOpDef.dt_float],
outputs=[PyCustomOpDef.dt_float])
def solveopf(a, b):
# The user custom op implementation here.
return scipy.linalg.solve(a, b).astype(np.float32)
@onnx_op(op_type="SolveDouble",
inputs=[PyCustomOpDef.dt_double, PyCustomOpDef.dt_double],
outputs=[PyCustomOpDef.dt_double])
def solveopd(a, b):
# The user custom op implementation here.
return scipy.linalg.solve(a, b).astype(np.float64)
cls.path = get_library_path()
def fit_classification_model(self, gp, n_classes=2):
data = load_iris()
X, y = data.data, data.target
if n_classes == 2:
y = y % 2
elif n_classes != 3:
raise NotImplementedError("n_classes must be 2 or 3")
X_train, X_test, y_train, y_test = train_test_split(
X, y, random_state=3)
gp.fit(X_train, y_train)
return gp, X_test.astype(np.float32)
def common_test_gpc(self, dtype=np.float32, n_classes=2):
gp = GaussianProcessClassifier()
gp, X = self.fit_classification_model(gp, n_classes=n_classes)
# return_cov=False, return_std=False
if dtype == np.float32:
cls = FloatTensorType
else:
cls = DoubleTensorType
model_onnx = to_onnx(
gp, initial_types=[('X', cls([None, None]))],
target_opset=TARGET_OPSET,
options={GaussianProcessClassifier: {
'zipmap': False, 'optim': 'cdist'}})
self.assertTrue(model_onnx is not None)
try:
sess = InferenceSession(model_onnx.SerializeToString())
except OrtFail:
if not hasattr(self, 'path'):
return
suffix = 'Double' if dtype == np.float64 else 'Float'
# Operator Solve is missing
model_onnx = change_onnx_domain(
model_onnx, {'Solve': ('Solve%s' % suffix, 'ai.onnx.contrib')})
so = SessionOptions()
so.register_custom_ops_library(self.path)
sess = InferenceSession(model_onnx.SerializeToString(), so)
res = sess.run(None, {'X': X.astype(dtype)})
assert_almost_equal(res[0].ravel(), gp.predict(X).ravel())
assert_almost_equal(res[1], gp.predict_proba(X),
decimal=3)
return
dt = 32 if dtype == np.float32 else 64
dump_data_and_model(
X.astype(dtype), gp, model_onnx, verbose=False,
basename="SklearnGaussianProcessRBFT%d%d" % (n_classes, dt))
@unittest.skipIf(TARGET_OPSET < 12, reason="einsum")
@unittest.skipIf(GaussianProcessClassifier is None,
reason="scikit-learn is too old")
@unittest.skipIf(StrictVersion(sklver_) < StrictVersion("0.22"),
reason="not available")
def test_gpc_float_bin(self):
self.common_test_gpc(dtype=np.float32)
@unittest.skipIf(TARGET_OPSET < 12, reason="einsum, reciprocal")
@unittest.skipIf(GaussianProcessClassifier is None,
reason="scikit-learn is too old")
@unittest.skipIf(StrictVersion(sklver_) < StrictVersion("0.22"),
reason="not available")
def test_gpc_double_bin(self):
self.common_test_gpc(dtype=np.float64)
if __name__ == "__main__":
unittest.main()
| 2,207 |
2,663 | <filename>Projects/Governance/Schemas/Docs-Concepts/R/Referral/Referral-Power/referral-power.json
{
"type": "Referral Power",
"definition": {
"text": "Referral Power is the Token Power that goes into the Referral Program, and determines how strong your participation is in the program.",
"updated": 1624782228096
},
"paragraphs": [
{
"style": "Text",
"text": "Right click and Edit to enter edit mode and change this text. ENTER to write new paragraphs. ESC to exit edit mode. Then you can use docs.save to save your changes and app.contribute to send it to the main repository."
}
]
} | 235 |
780 | package com.codeborne.selenide.junit5;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Screenshots;
import com.codeborne.selenide.ex.UIAssertionError;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import java.lang.reflect.Method;
import java.util.Optional;
/**
* Use this class to automatically take screenshots in case of ANY errors in tests (not only Selenide errors).
* <p>
* How to use in Java:
* <pre>
* {@code @ExtendWith({ScreenShooterExtension.class})}
* public class MyTest {...}
* </pre>
* <p>
* How to use in Java (with customization):
* <pre>
* public class MyTest {
* {@code @RegisterExtension}
* static ScreenShooterExtension screenshotEmAll = new ScreenShooterExtension(true);
* ...
* }
* </pre>
* <p>
* How to use in Kotlin:
*
* <pre>
* {@code @ExtendWith(ScreenShooterExtension::class)}
* public class MyTest {...}
* </pre>
* <p>
* How to use in Kotlin (with customization):
*
* <pre>
* public class MyTest {
* companion object {
* {@code @JvmField}
* {@code @RegisterExtension}
* val screenshotEmAll: ScreenShooterExtension = ScreenShooterExtension(true);
* }
* ...
* }
* </pre>
*
* @author <NAME>
* @since 4.12.2
*/
@ParametersAreNonnullByDefault
public class ScreenShooterExtension implements BeforeEachCallback, AfterEachCallback {
private static final Logger log = LoggerFactory.getLogger(ScreenShooterExtension.class);
private final boolean captureSuccessfulTests;
public ScreenShooterExtension() {
this(false);
}
/**
* @param captureSuccessfulTests param that indicate if need to capture successful tests
*/
public ScreenShooterExtension(final boolean captureSuccessfulTests) {
this.captureSuccessfulTests = captureSuccessfulTests;
}
/**
* One-liner to configure Configuration.reportsFolder property.
*
* @param folderWithScreenshots Folder to put screenshots to
* @return current extension instance
*/
@Nonnull
public ScreenShooterExtension to(final String folderWithScreenshots) {
Configuration.reportsFolder = folderWithScreenshots;
return this;
}
@Override
public void beforeEach(final ExtensionContext context) {
final Optional<Class<?>> testClass = context.getTestClass();
final String className = testClass.map(Class::getName).orElse("EmptyClass");
final Optional<Method> testMethod = context.getTestMethod();
final String methodName = testMethod.map(Method::getName).orElse("emptyMethod");
Screenshots.startContext(className, methodName);
}
@Override
public void afterEach(final ExtensionContext context) {
if (captureSuccessfulTests) {
log.info(Screenshots.saveScreenshotAndPageSource());
} else {
context.getExecutionException().ifPresent(error -> {
if (!(error instanceof UIAssertionError)) {
log.info(Screenshots.saveScreenshotAndPageSource());
}
});
}
Screenshots.finishContext();
}
}
| 1,090 |
357 | /*
* Copyright © 2019 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
static
DWORD
_VmDirSetSearchPriorityMap(
PLW_HASHMAP pSearchTypePriMap,
PLW_HASHMAP pAttrTypePriMap
);
static
VOID
_VmDirFreeFilterTypeArray(
PVDIR_FILTER_TYPE_PRI pArray
);
static
VOID
_VmDirFreeAttrTypeArray(
PVDIR_ATTR_TYPE_PRI pArray
);
// Input string format, e.g. "163:5"
// TODO, like to see "LDAP_FILTER_EQUALITY:5" instead
static
DWORD
_VmDirParseSearchTypes(
PSTR pszInput,
int * piSearchType,
int * piPri
)
{
PSTR pszPos = NULL;
DWORD dwError = 0;
pszPos = VmDirStringChrA(pszInput, ':');
if (!pszPos)
{
BAIL_WITH_VMDIR_ERROR(dwError, VMDIR_ERROR_INVALID_CONFIGURATION);
}
*pszPos = '\0';
*piSearchType = VmDirStringToIA(pszInput);
pszPos++;
*piPri = VmDirStringToIA(pszPos);
cleanup:
return dwError;
error:
goto cleanup;
}
// Input string format, e.g. "sAMAccountName:1"
static
DWORD
_VmDirParseAttrTypes(
PSTR pszInput,
PSTR* ppszAt,
int * piPri
)
{
PSTR pszPos = NULL;
DWORD dwError = 0;
PSTR pszAt = NULL;
*ppszAt = NULL;
*piPri = 0;
pszPos = VmDirStringChrA(pszInput, ':');
if (!pszPos)
{
BAIL_WITH_VMDIR_ERROR(dwError, VMDIR_ERROR_INVALID_CONFIGURATION);
}
*pszPos = '\0';
dwError = VmDirAllocateStringA(pszInput, &pszAt);
BAIL_ON_VMDIR_ERROR(dwError);
*ppszAt = pszAt;
pszPos++;
*piPri = VmDirStringToIA(pszPos);
cleanup:
return dwError;
error:
goto cleanup;
}
static
DWORD
_VmDirReadIteratorPriMapEntry(
PVDIR_FILTER_TYPE_PRI* ppSearchTypesPri,
PVDIR_ATTR_TYPE_PRI* ppAttrTypesPri
)
{
VDIR_ENTRY_ARRAY entryArray = {0};
PVDIR_ATTRIBUTE pAttr = NULL;
PVDIR_FILTER_TYPE_PRI pSearchTypesPri = NULL;
PVDIR_ATTR_TYPE_PRI pAttrTypesPri = NULL;
DWORD dwError = 0;
int i = 0;
dwError = VmDirSimpleEqualFilterInternalSearch(
CFG_ITERATION_MAP_DN,
LDAP_SCOPE_BASE,
ATTR_OBJECT_CLASS,
OC_ITERATOR_PRI_MAP,
&entryArray);
BAIL_ON_VMDIR_ERROR(dwError);
if (entryArray.iSize == 0)
{
BAIL_WITH_VMDIR_ERROR(dwError, VMDIR_ERROR_BACKEND_ENTRY_NOTFOUND);
}
pAttr = VmDirEntryFindAttribute(ATTR_SEARCH_TYPE_PRI, entryArray.pEntry);
if (pAttr)
{
dwError = VmDirAllocateMemory((pAttr->numVals+1) * sizeof(VDIR_FILTER_TYPE_PRI), (PVOID*)&pSearchTypesPri);
BAIL_ON_VMDIR_ERROR(dwError);
for (i = 0; i < pAttr->numVals; i++)
{
dwError = _VmDirParseSearchTypes(
pAttr->vals[i].lberbv.bv_val,
&pSearchTypesPri[i].iFilterType,
&pSearchTypesPri[i].iPri);
BAIL_ON_VMDIR_ERROR(dwError);
}
}
pAttr = VmDirEntryFindAttribute(ATTR_ATTR_TYPE_PRI, entryArray.pEntry);
if (pAttr)
{
dwError = VmDirAllocateMemory((pAttr->numVals+1) * sizeof(VDIR_ATTR_TYPE_PRI), (PVOID*)&pAttrTypesPri);
BAIL_ON_VMDIR_ERROR(dwError);
for (i = 0; i < pAttr->numVals; i++)
{
dwError = _VmDirParseAttrTypes(
pAttr->vals[i].lberbv.bv_val,
&pAttrTypesPri[i].pszAttrType,
&pAttrTypesPri[i].iPri);
BAIL_ON_VMDIR_ERROR(dwError);
}
}
*ppSearchTypesPri = pSearchTypesPri;
*ppAttrTypesPri = pAttrTypesPri;
cleanup:
VmDirFreeEntryArrayContent(&entryArray);
return dwError;
error:
VMDIR_SAFE_FREE_MEMORY(pSearchTypesPri);
VMDIR_SAFE_FREE_MEMORY(pAttrTypesPri);
goto cleanup;
}
static
DWORD
_VmDirAddDefaultIteratorPriMapEntry(
VOID
)
{
DWORD dwError = 0;
PVDIR_SCHEMA_CTX pSchemaCtx = NULL;
int iAttrCnt = 0;
PSTR * ppAttributes = NULL;
int i = 0;
int j = 0;
// The final priority is the matching value in this table, plus the base value UNIQ_ATTR_BASE_PRI
// when the index is globally unique or, NON_UNIQ_ATTR_BASE_PRI. if not, the base value is overridden if the
// attribute type is found in attrTypesPri.
VDIR_FILTER_TYPE_PRI searchTypesPri[] =
{
{LDAP_FILTER_EQUALITY /* 163 */, 5},
{LDAP_FILTER_LE /* 166 */, -20}, /* disable */
{LDAP_FILTER_GE /* 165 */, 3},
{FILTER_ONE_LEVEL_SEARCH /* 0 */, 1},
{LDAP_FILTER_SUBSTRINGS /* 164 */, 1},
{LDAP_FILTER_PRESENT /* 135 */, -20}, /* disable, use one/sub instead */
{0, 0}
};
VDIR_ATTR_TYPE_PRI attrTypesPri[] =
{
{ATTR_PARENT_ID, 2},
{ATTR_SAM_ACCOUNT_NAME, 1},
{ATTR_OBJECT_CLASS, -20}, /* disable objectclass on iterator */
{NULL, 0}
};
PSTR ppDefaultAttrs[] =
{
ATTR_OBJECT_CLASS, OC_TOP,
ATTR_OBJECT_CLASS, OC_ITERATOR_PRI_MAP,
ATTR_CN, CFG_ITERATION_MAP,
NULL
};
iAttrCnt = sizeof(ppDefaultAttrs)/sizeof(PSTR) + \
2 * sizeof(searchTypesPri)/sizeof(VDIR_FILTER_TYPE_PRI) + \
2 * sizeof(attrTypesPri)/sizeof(VDIR_ATTR_TYPE_PRI) + 2;
dwError = VmDirAllocateMemory(iAttrCnt*sizeof(PSTR), (PVOID*)&ppAttributes);
BAIL_ON_VMDIR_ERROR(dwError);
for (j=0; ppDefaultAttrs[j]; j++)
{
dwError = VmDirAllocateStringPrintf(&ppAttributes[i++], "%s", ppDefaultAttrs[j]);
BAIL_ON_VMDIR_ERROR(dwError);
}
for (j=0; searchTypesPri[j].iPri; j++)
{
dwError = VmDirAllocateStringPrintf(&ppAttributes[i++], "%s", ATTR_SEARCH_TYPE_PRI);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirAllocateStringPrintf(&ppAttributes[i++],
"%d:%d", searchTypesPri[j].iFilterType, searchTypesPri[j].iPri);
BAIL_ON_VMDIR_ERROR(dwError);
}
for (j=0; attrTypesPri[j].iPri; j++)
{
dwError = VmDirAllocateStringPrintf(&ppAttributes[i++], "%s", ATTR_ATTR_TYPE_PRI);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirAllocateStringPrintf(&ppAttributes[i++], "%s:%d",
attrTypesPri[j].pszAttrType, attrTypesPri[j].iPri);
BAIL_ON_VMDIR_ERROR(dwError);
}
ppAttributes[i] = NULL;
dwError = VmDirSchemaCtxAcquire(&pSchemaCtx);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirSimpleEntryCreate(
pSchemaCtx,
ppAttributes,
CFG_ITERATION_MAP_DN,
0);
BAIL_ON_VMDIR_ERROR(dwError);
VMDIR_LOG_INFO( VMDIR_LOG_MASK_ALL, "%s: succeeded", __func__);
cleanup:
for (i=0; ppAttributes[i]; i++)
{
VMDIR_SAFE_FREE_MEMORY(ppAttributes[i]);
}
VMDIR_SAFE_FREE_MEMORY(ppAttributes);
VmDirSchemaCtxRelease(pSchemaCtx);
return dwError;
error:
VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: error %d", __func__, dwError);
goto cleanup;
}
static
DWORD
_VmDirSetSearchPriorityMap(
PLW_HASHMAP pSearchTypePriMap,
PLW_HASHMAP pAttrTypePriMap
)
{
DWORD dwError = 0;
DWORD dwIndex = 0;
PLW_HASHMAP pLocalSearchMap = NULL;
PLW_HASHMAP pLocalAttrMap = NULL;
if (!gVmdirServerGlobals.searchOptMap.bMapLoaded)
{
memset(&gVmdirServerGlobals.searchOptMap, 0, sizeof(gVmdirServerGlobals.searchOptMap));
dwError = VmDirAllocateMemory(
sizeof(PVOID) * VMDIR_SEARCH_MAP_CACHE_SIZE,
(PVOID)&gVmdirServerGlobals.searchOptMap.ppSearchTypePriMap);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirAllocateMemory(
sizeof(PVOID) * VMDIR_SEARCH_MAP_CACHE_SIZE,
(PVOID)&gVmdirServerGlobals.searchOptMap.ppAttrTypePriMap);
BAIL_ON_VMDIR_ERROR(dwError);
gVmdirServerGlobals.searchOptMap.ppSearchTypePriMap[0] = pSearchTypePriMap;
gVmdirServerGlobals.searchOptMap.ppAttrTypePriMap[0] = pAttrTypePriMap;
gVmdirServerGlobals.searchOptMap.bMapLoaded = TRUE;
}
else
{
PLW_HASHMAP *ppSearchTypePriMap = gVmdirServerGlobals.searchOptMap.ppSearchTypePriMap;
PLW_HASHMAP *ppAttrTypePriMap = gVmdirServerGlobals.searchOptMap.ppAttrTypePriMap;
{ // section to atomically point cache to latest version
LwInterlockedIncrement64(&gVmdirServerGlobals.searchOptMap.iNext);
dwIndex = gVmdirServerGlobals.searchOptMap.iNext % VMDIR_SEARCH_MAP_CACHE_SIZE;
assert(dwIndex != gVmdirServerGlobals.searchOptMap.iCurrent);
pLocalSearchMap = ppSearchTypePriMap[dwIndex];
pLocalAttrMap = ppAttrTypePriMap[dwIndex];
ppSearchTypePriMap[dwIndex] = pSearchTypePriMap;
ppAttrTypePriMap[dwIndex] = pAttrTypePriMap;
LwInterlockedExchange64(&gVmdirServerGlobals.searchOptMap.iCurrent, dwIndex);
}
if (pLocalSearchMap)
{
LwRtlHashMapClear(pLocalSearchMap, VmDirSimpleHashMapPairFree, NULL);
LwRtlFreeHashMap(&pLocalSearchMap);
}
if (pLocalAttrMap)
{
LwRtlHashMapClear(pLocalAttrMap, VmDirSimpleHashMapPairFree, NULL);
LwRtlFreeHashMap(&pLocalAttrMap);
}
}
VMDIR_LOG_INFO(VMDIR_LOG_MASK_ALL, "%s: curent serach priority map index (%d)", __func__, dwIndex);
error:
return dwError;
}
/*
* Start up time function to load "cn=iteratorprimap,cn=config" into cache for iterator based
* cost evaluation.
*/
DWORD
VmDirLoadSearchPriorityMap(
VOID
)
{
DWORD dwError = 0;
DWORD dwCnt = 0;
DWORD dwPropertyCnt = 0;
PVDIR_INDEX_PROPERTY pIndexProperty = NULL;
PVDIR_FILTER_TYPE_PRI pSearchTypesPri = NULL;
PVDIR_ATTR_TYPE_PRI pAttrTypesPri = NULL;
PLW_HASHMAP pSearchTypePriMap = NULL;
PLW_HASHMAP pAttrTypePriMap = NULL;
PSTR pszKey = NULL;
PSTR pszVal = NULL;
if (gVmdirGlobals.dwEnableSearchOptimization == 0)
{
VMDIR_LOG_INFO(VMDIR_LOG_MASK_ALL, "%s: Search optimization disabled", __func__);
goto cleanup;
}
dwError = LwRtlCreateHashMap(
&pSearchTypePriMap,
LwRtlHashDigestPstrCaseless,
LwRtlHashEqualPstrCaseless,
NULL);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = LwRtlCreateHashMap(
&pAttrTypePriMap,
LwRtlHashDigestPstrCaseless,
LwRtlHashEqualPstrCaseless,
NULL);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = _VmDirReadIteratorPriMapEntry(&pSearchTypesPri, &pAttrTypesPri);
if (dwError == VMDIR_ERROR_BACKEND_ENTRY_NOTFOUND)
{
dwError = _VmDirAddDefaultIteratorPriMapEntry();
if (dwError == VMDIR_ERROR_NO_SUCH_ATTRIBUTE)
{
VMDIR_LOG_WARNING(VMDIR_LOG_MASK_ALL, "%s: iterator search optimization needs schema upgrade.", __func__);
dwError = 0; // TODO, should just load default value into cache instead?
goto cleanup;
}
BAIL_ON_VMDIR_ERROR(dwError);
dwError = _VmDirReadIteratorPriMapEntry(&pSearchTypesPri, &pAttrTypesPri);
}
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirIndexMapGetProperty(&pIndexProperty);
BAIL_ON_VMDIR_ERROR(dwError);
for (dwPropertyCnt= 0; pIndexProperty[dwPropertyCnt].pszName; dwPropertyCnt++)
{
PSTR pszAttr = NULL;
int iPriVal = 0;
pszAttr = pIndexProperty[dwPropertyCnt].pszName;
iPriVal = pIndexProperty[dwPropertyCnt].bGlobalUnique ? UNIQ_ATTR_BASE_PRI : NON_UNIQ_ATTR_BASE_PRI;
for (dwCnt=0; (pAttrTypesPri && pAttrTypesPri[dwCnt].pszAttrType); dwCnt++)
{
if (VmDirStringCompareA(pszAttr, pAttrTypesPri[dwCnt].pszAttrType, FALSE) == 0)
{
iPriVal += pAttrTypesPri[dwCnt].iPri;
break;
}
}
dwError = VmDirAllocateStringPrintf(&pszKey, "%s", pszAttr);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirAllocateStringPrintf(&pszVal, "%d", iPriVal);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = LwRtlHashMapInsert(pAttrTypePriMap, pszKey, pszVal, NULL);
BAIL_ON_VMDIR_ERROR(dwError);
VMDIR_LOG_INFO(VMDIR_LOG_MASK_ALL, "%s: add key:value %s: %s onto AttrTypePriMap", __func__, pszKey, pszVal);
}
for (dwCnt=0;
pSearchTypesPri && (pSearchTypesPri[dwCnt].iFilterType || pSearchTypesPri[dwCnt].iPri) ;
dwCnt++)
{
dwError = VmDirAllocateStringPrintf(&pszKey, "%d", pSearchTypesPri[dwCnt].iFilterType);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirAllocateStringPrintf(&pszVal, "%d", pSearchTypesPri[dwCnt].iPri);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = LwRtlHashMapInsert(pSearchTypePriMap, pszKey, pszVal, NULL);
BAIL_ON_VMDIR_ERROR(dwError);
VMDIR_LOG_INFO(VMDIR_LOG_MASK_ALL, "%s: add key:value %s: %s onto SearchTypePriMap", __func__, pszKey, pszVal);
}
dwError = _VmDirSetSearchPriorityMap(pSearchTypePriMap, pAttrTypePriMap);
BAIL_ON_VMDIR_ERROR(dwError);
cleanup:
_VmDirFreeFilterTypeArray(pSearchTypesPri);
_VmDirFreeAttrTypeArray(pAttrTypesPri);
VmDirIndexMapFreeProperty(pIndexProperty);
return dwError;
error:
if (pSearchTypePriMap)
{
LwRtlHashMapClear(pSearchTypePriMap, VmDirSimpleHashMapPairFree, NULL);
LwRtlFreeHashMap(&pSearchTypePriMap);
}
if (pAttrTypePriMap)
{
LwRtlHashMapClear(pAttrTypePriMap, VmDirSimpleHashMapPairFree, NULL);
LwRtlFreeHashMap(&pAttrTypePriMap);
}
VMDIR_LOG_ERROR(VMDIR_LOG_MASK_ALL, "%s: error %d", __func__, dwError);
goto cleanup;
}
/*
* Search global map that is currently loaded with static rules.
*/
int
VmDirGetSearchPri(
PVDIR_SEARCHOPT_PARAM pOptParm
)
{
int iTotalPri = 0;
PSTR pszFixedPri = NULL;
char key[VMDIR_SIZE_128]= {0};
DWORD dwError = 0;
if (!pOptParm)
{
BAIL_WITH_VMDIR_ERROR(dwError, VMDIR_ERROR_INVALID_PARAMETER);
}
if (pOptParm->bPagedSearch || pOptParm->iSizeLimit|| pOptParm->iTimeLimit)
{
iTotalPri = PAGED_OR_LIMIT_RAISED_PRI;
}
dwError = VmDirStringNPrintFA(key, sizeof(key), sizeof(key)-1, "%d", pOptParm->iSearchType);
BAIL_ON_VMDIR_ERROR(dwError);
if (LwRtlHashMapFindKey(
gVmdirServerGlobals.searchOptMap.ppSearchTypePriMap[
gVmdirServerGlobals.searchOptMap.iCurrent],
(PVOID*)&pszFixedPri,
key) == 0)
{
iTotalPri += atoi(pszFixedPri);
}
dwError = VmDirStringNPrintFA(key, sizeof(key), sizeof(key)-1, "%s", pOptParm->pszAttrType);
BAIL_ON_VMDIR_ERROR(dwError);
pszFixedPri = NULL;
if (LwRtlHashMapFindKey(
gVmdirServerGlobals.searchOptMap.ppAttrTypePriMap[
gVmdirServerGlobals.searchOptMap.iCurrent],
(PVOID*)&pszFixedPri,
key) == 0)
{
iTotalPri += atoi(pszFixedPri);
}
cleanup:
return iTotalPri;
error:
iTotalPri = 0;
goto cleanup;
}
static
VOID
_VmDirFreeFilterTypeArray(
PVDIR_FILTER_TYPE_PRI pArray
)
{
if (pArray)
{
VMDIR_SAFE_FREE_MEMORY(pArray);
}
}
static
VOID
_VmDirFreeAttrTypeArray(
PVDIR_ATTR_TYPE_PRI pArray
)
{
PVDIR_ATTR_TYPE_PRI pBase = pArray;
if (pArray)
{
while (pBase->pszAttrType)
{
VMDIR_SAFE_FREE_MEMORY(pBase->pszAttrType);
pBase++;
}
VMDIR_SAFE_FREE_MEMORY(pArray);
}
}
| 8,330 |
828 | import shopify
import json
from test.test_helper import TestCase
class ApplicationCreditTest(TestCase):
def test_get_application_credit(self):
self.fake("application_credits/445365009", method="GET", body=self.load_fixture("application_credit"), code=200)
application_credit = shopify.ApplicationCredit.find(445365009)
self.assertEqual("5.00", application_credit.amount)
def test_get_all_application_credits(self):
self.fake("application_credits", method="GET", body=self.load_fixture("application_credits"), code=200)
application_credits = shopify.ApplicationCredit.find()
self.assertEqual(1, len(application_credits))
self.assertEqual(445365009, application_credits[0].id)
def test_create_application_credit(self):
self.fake(
"application_credits",
method="POST",
body=self.load_fixture("application_credit"),
headers={"Content-type": "application/json"},
code=201,
)
application_credit = shopify.ApplicationCredit.create(
{"description": "application credit for refund", "amount": 5.0}
)
expected_body = {"application_credit": {"description": "application credit for refund", "amount": 5.0}}
self.assertEqual(expected_body, json.loads(self.http.request.data.decode("utf-8")))
| 527 |
2,405 | <filename>STM32F1/libraries/MapleCoOS116/utility/mm.c<gh_stars>1000+
/**
*******************************************************************************
* @file mm.c
* @version V1.1.6
* @date 2014.05.23
* @brief memory management implementation code of CooCox CoOS kernel.
*******************************************************************************
* @copy
*
* 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 <ORGANIZATION> nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* <h2><center>© COPYRIGHT 2014 CooCox </center></h2>
*******************************************************************************
*/
/*---------------------------- Include ---------------------------------------*/
#include <coocox.h>
#if CFG_MM_EN > 0
/*---------------------------- Variable Define -------------------------------*/
MM MemoryTbl[CFG_MAX_MM] = {{0}};/*!< Table which save memory control block. */
U32 MemoryIDVessel = 0; /*!< Memory ID container. */
/**
*******************************************************************************
* @brief Create a memory partition
* @param[in] memBuf Specify memory partition head address.
* @param[in] blockSize Specify memory block size.
* @param[in] blockNum Specify memory block number.
* @param[out] None
* @retval E_CREATE_FAIL Create memory partition fail.
* @retval others Create memory partition successful.
*
* @par Description
* @details This function is called to create a memory partition.
*******************************************************************************
*/
OS_MMID CoCreateMemPartition(U8* memBuf,U32 blockSize,U32 blockNum)
{
U8 i,j;
U8 *memory;
P_MemBlk memBlk;
memory = memBuf;
#if CFG_PAR_CHECKOUT_EN >0 /* Check validity of parameter */
if(memBuf == Co_NULL)
{
return E_CREATE_FAIL;
}
if(blockSize == 0)
{
return E_CREATE_FAIL;
}
if((blockSize&0x3) != 0)
{
return E_CREATE_FAIL;
}
if(blockNum<=1)
{
return E_CREATE_FAIL;
}
#endif
OsSchedLock(); /* Lock schedule */
for(i = 0; i < CFG_MAX_MM; i++)
{
if((MemoryIDVessel & (1 << i)) == 0) /* Is free memory ID? */
{
MemoryIDVessel |= (1<<i); /* Yes,assign ID to this memory block */
OsSchedUnlock(); /* Unlock schedule */
MemoryTbl[i].memAddr = memory;/* Initialize memory control block*/
MemoryTbl[i].freeBlock = memory;
MemoryTbl[i].blockSize = blockSize;
MemoryTbl[i].blockNum = blockNum;
memBlk = (P_MemBlk)memory; /* Bulid list in this memory block*/
for(j=0;j<blockNum-1;j++)
{
memory = memory+blockSize;
memBlk->nextBlock = (P_MemBlk)memory;
memBlk = memBlk->nextBlock;
}
memBlk->nextBlock = Co_NULL;
return i; /* Return memory block ID */
}
}
OsSchedUnlock(); /* Unlock schedule */
return E_CREATE_FAIL; /* Error return */
}
/**
*******************************************************************************
* @brief Delete a memory partition
* @param[in] mmID Specify memory partition that want to delete.
* @param[out] None
* @retval E_INVALID_ID The memory partition id passed was invalid,delete fail.
* @retval E_OK Delete successful.
*
* @par Description
* @details This function is called to Delete a memory partition.
*******************************************************************************
*/
StatusType CoDelMemoryPartition(OS_MMID mmID)
{
P_MM memCtl;
#if CFG_PAR_CHECKOUT_EN >0 /* Check validity of parameter */
if(mmID >= CFG_MAX_MM)
{
return E_INVALID_ID;
}
if( ((1<<mmID)&MemoryIDVessel) == 0)
{
return E_INVALID_ID;
}
#endif
OsSchedLock(); /* Lock schedule */
memCtl = &MemoryTbl[mmID]; /* Release memory control block */
MemoryIDVessel &= ~(1<<mmID);
OsSchedUnlock(); /* Unlock schedule */
memCtl->memAddr = Co_NULL;
memCtl->freeBlock = Co_NULL;
memCtl->blockSize = 0;
memCtl->blockNum = 0;
return E_OK; /* Return OK */
}
/**
*******************************************************************************
* @brief Get free block number in a memory partition
* @param[in] mmID Specify memory partition.
*
* @param[out] E_INVALID_ID Invalid ID was passed and get counter failure.
* @param[out] E_OK Get current counter successful.
* @retval fbNum The number of free block.
*
* @par Description
* @details This function is called to get free block number in a memory
* partition.
*******************************************************************************
*/
U32 CoGetFreeBlockNum(OS_MMID mmID,StatusType* perr)
{
U32 fbNum;
P_MM memCtl;
P_MemBlk memBlk;
#if CFG_PAR_CHECKOUT_EN >0 /* Check validity of parameter */
if(mmID >= CFG_MAX_MM)
{
*perr = E_INVALID_ID;
return 0;
}
if( ((1<<mmID)&MemoryIDVessel) == 0)
{
*perr = E_INVALID_ID; /* Invalid memory id,return 0 */
return 0;
}
#endif
memCtl = &MemoryTbl[mmID];
OsSchedLock(); /* Lock schedule */
memBlk = (P_MemBlk)(memCtl->freeBlock);/* Get the free item in memory list*/
fbNum = 0;
while(memBlk != Co_NULL) /* Get counter of free item */
{
fbNum++;
memBlk = memBlk->nextBlock; /* Get next free iterm */
}
OsSchedUnlock(); /* Unlock schedul */
*perr = E_OK;
return fbNum; /* Return the counter of free item */
}
/**
*******************************************************************************
* @brief Get a memory buffer from memory partition
* @param[in] mmID Specify memory partition that want to assign buffer.
* @param[out] None
* @retval Co_NULL Assign buffer fail.
* @retval others Assign buffer successful,and return the buffer pointer.
*
* @par Description
* @details This function is called to Delete a memory partition.
*******************************************************************************
*/
void* CoGetMemoryBuffer(OS_MMID mmID)
{
P_MM memCtl;
P_MemBlk memBlk;
#if CFG_PAR_CHECKOUT_EN >0 /* Check validity of parameter */
if(mmID >= CFG_MAX_MM)
{
return Co_NULL;
}
if( ((1<<mmID)&MemoryIDVessel) == 0)
{
return Co_NULL;
}
#endif
memCtl = &MemoryTbl[mmID];
OsSchedLock(); /* Lock schedule */
if(memCtl->freeBlock == Co_NULL ) /* Is there no free item in memory list */
{
OsSchedUnlock(); /* Unlock schedule */
return Co_NULL; /* Yes,error return */
}
memBlk = (P_MemBlk)memCtl->freeBlock; /* Get free memory block */
memCtl->freeBlock = (U8*)memBlk->nextBlock; /* Reset the first free item */
OsSchedUnlock(); /* Unlock schedule */
return memBlk; /* Return free memory block address */
}
/**
*******************************************************************************
* @brief Free a memory buffer to memory partition
* @param[in] mmID Specify memory partition.
* @param[in] buf Specify memory buffer that want to free.
* @param[out] None
* @retval E_INVALID_ID The memory partition id passed was invalid.
* @retval E_INVALID_PARAMETER The parameter passed was invalid.
* @retval E_OK Free successful.
*
* @par Description
* @details This function is called to Delete a memory partition.
*******************************************************************************
*/
StatusType CoFreeMemoryBuffer(OS_MMID mmID,void* buf)
{
P_MM memCtl;
P_MemBlk memBlk;
#if CFG_PAR_CHECKOUT_EN >0 /* Check validity of parameter */
if(mmID >= CFG_MAX_MM)
{
return E_INVALID_ID;
}
if( ((1<<mmID)&MemoryIDVessel) == 0)
{
return E_INVALID_ID;
}
if(buf == Co_NULL)
{
return E_INVALID_PARAMETER;
}
#endif
memCtl = &MemoryTbl[mmID];
#if CFG_PAR_CHECKOUT_EN >0 /* Check validity of parameter */
if((U32)buf < (U32)(memCtl->memAddr))
{
return E_INVALID_PARAMETER;
}
if((U32)buf > (U32)(memCtl->memAddr + memCtl->blockSize*memCtl->blockNum))
{
return E_INVALID_PARAMETER;
}
if(((U32)buf - (U32)(memCtl->memAddr))%(memCtl->blockSize) != 0)
{
return E_INVALID_PARAMETER;
}
#endif
memBlk = (P_MemBlk)buf; /* Reset the first free item */
OsSchedLock();
memBlk->nextBlock = (P_MemBlk)memCtl->freeBlock;
memCtl->freeBlock = buf;
OsSchedUnlock();
return E_OK; /* Return OK */
}
#endif
| 4,850 |
563 | from __future__ import unicode_literals
try:
from django.urls import re_path
except ImportError:
from django.conf.urls import url as re_path
from django.contrib import admin
from paypal.standard.ipn import views
urlpatterns = [
re_path(r'^ipn/$', views.ipn),
re_path(r'^admin/', admin.site.urls),
]
| 124 |
1,264 | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.jsprit.examples;
import com.graphhopper.jsprit.analysis.toolbox.Plotter;
import com.graphhopper.jsprit.analysis.toolbox.Plotter.Label;
import com.graphhopper.jsprit.core.algorithm.VehicleRoutingAlgorithm;
import com.graphhopper.jsprit.core.algorithm.box.Jsprit;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
import com.graphhopper.jsprit.core.problem.vehicle.Vehicle;
import com.graphhopper.jsprit.core.reporting.SolutionPrinter;
import com.graphhopper.jsprit.core.util.Solutions;
import com.graphhopper.jsprit.io.problem.VrpXMLReader;
import com.graphhopper.jsprit.util.Examples;
import java.util.Collection;
public class MultipleDepotWithInitialRoutesExample {
public static void main(String[] args) {
/*
* some preparation - create output folder
*/
Examples.createOutputFolder();
VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
/*
* Read cordeau-instance p01
*/
new VrpXMLReader(vrpBuilder).read("input/cordeau01.xml");
/*
* Add initial route with 1_4_vehicle and services 44, 26
*/
VehicleRoute initialRoute = VehicleRoute.Builder.newInstance(getVehicle("1_4_vehicle", vrpBuilder)).addService(getService("44", vrpBuilder))
.addService(getService("26", vrpBuilder)).build();
vrpBuilder.addInitialVehicleRoute(initialRoute);
/*
* build the problem
*/
VehicleRoutingProblem vrp = vrpBuilder.build();
/*
* since job (service) 26 and 44 are already planned in initial route and thus static AND sequence is fixed they
* should not be in jobMap anymore (only variable jobs are in jobMap)
*/
assert !vrp.getJobs().containsKey("26") : "strange. service 26 should not be part of the problem";
assert !vrp.getJobs().containsKey("44") : "strange. service 44 should not be part of the problem";
/*
* plot to see how the problem looks like
*/
new Plotter(vrp).setLabel(Label.ID).plot("output/cordeau01_problem_withInitialRoute.png", "c");
/*
* solve the problem
*/
// VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp)
// .setProperty(Jsprit.Parameter.ITERATIONS,"10000").buildAlgorithm();
VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp);
Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions();
SolutionPrinter.print(Solutions.bestOf(solutions));
new Plotter(vrp, Solutions.bestOf(solutions)).setLabel(Label.ID).plot("output/cordeau01_solution_withInitialRoute.png", "p01");
}
private static Service getService(String serviceId, Builder vrpBuilder) {
for (Job j : vrpBuilder.getAddedJobs()) {
if (j.getId().equals(serviceId)) {
return (Service) j;
}
}
return null;
}
private static Vehicle getVehicle(String vehicleId, Builder vrpBuilder) {
for (Vehicle v : vrpBuilder.getAddedVehicles()) {
if (v.getId().equals(vehicleId)) return v;
}
return null;
}
}
| 1,530 |
1,144 | <reponame>dram/metasfresh
package de.metas.util.lang;
import lombok.NonNull;
/*
* #%L
* de.metas.util
* %%
* Copyright (C) 2020 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
public enum Priority
{
HIGHEST(Integer.MIN_VALUE), //
MEDIUM(100), //
LOWEST(Integer.MAX_VALUE), //
;
private final int value;
Priority(final int value)
{
this.value = value;
}
public int toInt()
{
return value;
}
public boolean isHigherThan(@NonNull final Priority other)
{
return this.value < other.value;
}
}
| 375 |
843 | <reponame>tor-vs-floki/nakadi
package org.zalando.nakadi.exceptions.runtime;
public class ConnectionSlotOccupiedException extends NakadiBaseException {
}
| 50 |
2,293 | #include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
char *UTS_sprintf_wrap();
char *do_efmt();
char *do_gfmt();
char *Fill();
/* main(argc, argv)
* char **argv;
* {
* double d;
* char *Fmt, *Ret;
* char obuf[200];
*
* assert(argc > 2);
* Fmt = argv[1];
* d = strtod(argv[2], (char **)0);
*
* putchar('{');
* printf(Fmt, d);
* printf("}\n");
*
* Ret = UTS_sprintf_wrap(obuf, Fmt, d);
* assert(Ret == obuf);
*
* printf("{%s}\n", obuf);
* }
*/
char *
UTS_sprintf_wrap(obuf, fmt, d,
a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15)
char *obuf, *fmt;
double d;
{
int fmtlen, Width=0, Precision=6, Alt=0, Plus=0, Minus=0,
Zero = 0;
int FmtChar, BaseFmt = 0;
char *f = fmt, *AfterWidth = 0, *AfterPrecision = 0;
char *Dot;
if(*f++ != '%') {
return
sprintf(obuf, fmt, d, a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15);
}
fmtlen = strlen(fmt);
FmtChar = fmt[fmtlen - 1];
switch(FmtChar) {
case 'f':
case 'F':
return
sprintf(obuf, fmt, d, a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15);
case 'e':
case 'E':
BaseFmt = 'e';
goto BaseFmt_IsSet;
case 'g':
case 'G':
BaseFmt = 'g';
BaseFmt_IsSet:
if(*f == '#') { Alt = 1; ++f; } /* Always has '.' */
if(*f == '+') { Plus = 1; ++f; } /* Force explicit sign */
if(*f == '-') { Minus = 1; ++f; } /* Left justify */
if(*f == '0') { Zero = 1; ++f;} /* Fill using 0s*/
if(Dot = strchr(f, '.')) {
Precision = strtol(Dot+1, &AfterPrecision, 0);
}
if(!Dot || (Dot && Dot > f)) { /* Next char=='.' => no width*/
Width = strtol(f, &AfterWidth, 0);
}
if(Dot) { f = AfterPrecision; }
else if(AfterWidth) { f = AfterWidth; }
if(*f != FmtChar) goto regular_sprintf;
/* It doesn't look like a f.p. sprintf call */
/* from Perl_sv_vcatpvfn */
if(BaseFmt == 'e') {
return do_efmt(d, obuf, Width, Precision, Alt,
Plus, Minus, Zero, FmtChar == 'E');
} else {
return do_gfmt(d, obuf, Width, Precision, Alt,
Plus, Minus, Zero, FmtChar == 'G');
}
default:
regular_sprintf:
return
sprintf(obuf, fmt, d, a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15);
}
}
char *
do_efmt(d, obuf, Width, Precision, Alt, Plus, Minus, Zero, UpperCase)
char *obuf;
double d;
{
char *Ecvt;
char *ob;
int decpt, sign, E;
int len;
int AllZeroes = 0;
Ecvt = ecvt( d , Precision+1, &decpt, &sign);
/* fprintf(stderr, "decpt=%d, sign=%d\n", decpt, sign); */
len = strlen(Ecvt);
if(strspn(Ecvt, "0") == len) AllZeroes = 1;
ob = obuf;
if(sign) *ob++ = '-';
else if(Plus) *ob++ = '+';
*ob++ = Ecvt[0];
if(Precision > 0 || Alt) *ob++ = '.';
strcpy(ob, &Ecvt[1]);
ob += strlen(ob); /* ADVANCE TO END OF WHAT WE JUST ADDED */
*ob++ = UpperCase ? 'E' : 'e';
if(AllZeroes) E = 0;
else E = decpt - 1;
if(E < 0) { *ob++ = '-'; E = -E; }
else { *ob++ = '+'; }
sprintf(ob, "%.2d", E); /* Too much horsepower used here */
if(Width > strlen(obuf)) return Fill(obuf, Width, Minus, Zero);
else return obuf;
}
char *
do_gfmt(d, obuf, Width, Precision, Alt, Plus, Minus, Zero, UpperCase)
char *obuf;
double d;
{
char *Ecvt = gcvt(d, Precision ? Precision : 1, obuf);
int len = strlen(obuf);
/* gcvt fails (maybe give a warning? For now return empty string): */
if(!Ecvt) { *obuf = '\0'; return obuf; }
/* printf("Ecvt='%s'\n", Ecvt); */
if(Plus && (Ecvt[0] != '-')) {
memmove(obuf+1, obuf, len+1); /* "+1" to get '\0' at end */
obuf[0] = '+';
++len;
}
if(Alt && !strchr(Ecvt, '.')) {
int LenUpTo_E = strcspn(obuf, "eE");
int E_etc_len = strlen(&obuf[LenUpTo_E]);
/* ABOVE: Will be 0 if there's no E/e because */
/* strcspn will return length of whole string */
if(E_etc_len)
memmove(obuf+LenUpTo_E+1, obuf+LenUpTo_E, E_etc_len);
obuf[LenUpTo_E] = '.';
obuf[LenUpTo_E + 1 + E_etc_len ] = '\0';
}
{ char *E_loc;
if(UpperCase && (E_loc = strchr(obuf, 'e'))) { *E_loc = 'E'; }
}
if(Width > len)
return Fill(obuf, Width, Minus, Zero);
else
return obuf;
}
char *
Fill(obuf, Width, LeftJustify, Zero)
char *obuf;
{
int W = strlen(obuf);
int diff = Width - W;
/* LeftJustify means there was a '-' flag, and in that case, */
/* printf man page (UTS4.4) says ignore '0' */
char FillChar = (Zero && !LeftJustify) ? '0' : ' ';
int i;
int LeftFill = ! LeftJustify;
if(Width <= W) return obuf;
if(LeftFill) {
memmove(obuf+diff, obuf, W+1); /* "+1" to get '\0' at end */
for(i=0 ; i < diff ; ++i) { obuf[i] = FillChar; }
} else {
for(i=W ; i < Width ; ++i)
obuf[i] = FillChar;
obuf[Width] = '\0';
}
return obuf;
}
| 2,327 |
910 | /*
* Copyright (c) 2021 VMware, Inc.
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.dbsp.algebraic.staticTyping;
/**
* Finite functions that map values into a group G also form a group themselves.
* This is the implementation of that group.
* @param <D> Domain of the finite functions.
* @param <T> Codomain of finite functions.
*/
public class FiniteFunctionGroup<D, T> implements Group<FiniteFunction<D, T>> {
final Group<T> group;
public FiniteFunctionGroup(Group<T> group) {
this.group = group;
}
@Override
public FiniteFunction<D, T> negate(FiniteFunction<D, T> data) {
return new FiniteFunction<D, T>() {
@Override
public T apply(D d) {
return FiniteFunctionGroup.this.group.negate(data.apply(d));
}
};
}
@Override
public FiniteFunction<D, T> add(FiniteFunction<D, T> left, FiniteFunction<D, T> right) {
return new FiniteFunction<D, T>() {
@Override
public T apply(D d) {
T first = left.apply(d);
T second = right.apply(d);
return FiniteFunctionGroup.this.group.add(first, second);
}
};
}
@Override
public FiniteFunction<D, T> zero() {
return new FiniteFunction<D, T>() {
@Override
public T apply(D d) {
return FiniteFunctionGroup.this.group.zero();
}
};
}
} | 934 |
978 | <filename>deps/cinder/include/boost/predef/compiler/palm.h
/*
Copyright <NAME> 2008-2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_PREDEF_COMPILER_PALM_H
#define BOOST_PREDEF_COMPILER_PALM_H
#include <boost/predef/version_number.h>
#include <boost/predef/make.h>
/*`
[heading `BOOST_COMP_PALM`]
Palm C/C++ compiler.
Version number available as major, minor, and patch.
[table
[[__predef_symbol__] [__predef_version__]]
[[`_PACC_VER`] [__predef_detection__]]
[[`_PACC_VER`] [V.R.P]]
]
*/
#define BOOST_COMP_PALM BOOST_VERSION_NUMBER_NOT_AVAILABLE
#if defined(_PACC_VER)
# define BOOST_COMP_PALM_DETECTION BOOST_PREDEF_MAKE_0X_VRRPP000(_PACC_VER)
#endif
#ifdef BOOST_COMP_PALM_DETECTION
# if defined(BOOST_PREDEF_DETAIL_COMP_DETECTED)
# define BOOST_COMP_PALM_EMULATED BOOST_COMP_PALM_DETECTION
# else
# undef BOOST_COMP_PALM
# define BOOST_COMP_PALM BOOST_COMP_PALM_DETECTION
# endif
# define BOOST_COMP_PALM_AVAILABLE
# include <boost/predef/detail/comp_detected.h>
#endif
#define BOOST_COMP_PALM_NAME "Palm C/C++"
#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_COMP_PALM,BOOST_COMP_PALM_NAME)
#ifdef BOOST_COMP_PALM_EMULATED
#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_COMP_PALM_EMULATED,BOOST_COMP_PALM_NAME)
#endif
#endif
| 715 |
3,482 | <filename>Question_31_40/answers_py/answer_31.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Affine
def affine(img, dx=30, dy=30):
# get shape
H, W, C = img.shape
# Affine hyper parameters
a = 1.
b = dx / H
c = dy / W
d = 1.
tx = 0.
ty = 0.
# prepare temporary
_img = np.zeros((H+2, W+2, C), dtype=np.float32)
# insert image to center of temporary
_img[1:H+1, 1:W+1] = img
# prepare affine image temporary
H_new = np.ceil(dy + H).astype(np.int)
W_new = np.ceil(dx + W).astype(np.int)
out = np.zeros((H_new, W_new, C), dtype=np.float32)
# preprare assigned index
x_new = np.tile(np.arange(W_new), (H_new, 1))
y_new = np.arange(H_new).repeat(W_new).reshape(H_new, -1)
# prepare inverse matrix for affine
adbc = a * d - b * c
x = np.round((d * x_new - b * y_new) / adbc).astype(np.int) - tx + 1
y = np.round((-c * x_new + a * y_new) / adbc).astype(np.int) - ty + 1
x = np.minimum(np.maximum(x, 0), W+1).astype(np.int)
y = np.minimum(np.maximum(y, 0), H+1).astype(np.int)
# assign value from original to affine image
out[y_new, x_new] = _img[y, x]
out = out.astype(np.uint8)
return out
# Read image
img = cv2.imread("imori.jpg").astype(np.float32)
# Affine
out = affine(img, dx=30, dy=30)
# Save result
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.imwrite("out.jpg", out)
| 672 |
2,759 | <filename>src/yb/gen_yrpc/proxy_generator.cc
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include "yb/gen_yrpc/proxy_generator.h"
#include <google/protobuf/descriptor.h>
#include "yb/gen_yrpc/metric_descriptor.h"
#include "yb/gen_yrpc/model.h"
namespace yb {
namespace gen_yrpc {
namespace {
std::vector<MetricDescriptor> outbound_metrics = {
{
.name = "request_bytes",
.prefix = "proxy_",
.kind = "counter",
.extra_args = "",
.units = "yb::MetricUnit::kBytes",
.description = "Bytes sent by",
},
{
.name = "response_bytes",
.prefix = "proxy_",
.kind = "counter",
.extra_args = "",
.units = "yb::MetricUnit::kBytes",
.description = "Bytes received in response to",
},
};
} // namespace
void ProxyGenerator::Header(YBPrinter printer, const google::protobuf::FileDescriptor *file) {
printer(
"// THIS FILE IS AUTOGENERATED FROM $path$\n"
"\n"
"#pragma once\n"
"\n"
"#include \"$path_no_extension$.pb.h\"\n"
);
if (HasLightweightMethod(file, rpc::RpcSides::PROXY)) {
printer("#include \"$path_no_extension$.messages.h\"\n");
}
printer(
"\n"
"#include \"yb/rpc/proxy.h\"\n"
"#include \"yb/util/status.h\"\n"
"#include \"yb/util/net/net_fwd.h\"\n"
"\n"
"namespace yb {\n"
"namespace rpc {\n"
"class Proxy;\n"
"}\n"
"}\n"
"\n"
"$open_namespace$"
"\n"
"\n"
);
for (int service_idx = 0; service_idx < file->service_count(); ++service_idx) {
const auto* service = file->service(service_idx);
ScopedSubstituter service_subs(printer, service);
printer(
"class $service_name$Proxy : public ::yb::rpc::ProxyBase {\n"
" public:\n"
" $service_name$Proxy(\n"
" ::yb::rpc::ProxyCache* cache, const ::yb::HostPort& remote,\n"
" const ::yb::rpc::Protocol* protocol = nullptr,\n"
" const ::yb::MonoDelta& resolve_cache_timeout = ::yb::MonoDelta());\n"
);
for (int method_idx = 0; method_idx < service->method_count(); ++method_idx) {
ScopedSubstituter method_subs(printer, service->method(method_idx), rpc::RpcSides::PROXY);
printer(
"\n"
" ::yb::Status $rpc_name$(const $request$ &req, $response$ *resp,\n"
" ::yb::rpc::RpcController *controller) const;\n"
" void $rpc_name$Async(const $request$ &req,\n"
" $response$ *response,\n"
" ::yb::rpc::RpcController *controller,\n"
" ::yb::rpc::ResponseCallback callback) const;\n"
);
}
printer("};\n\n");
}
printer(
"$close_namespace$"
);
}
void ProxyGenerator::Source(YBPrinter printer, const google::protobuf::FileDescriptor *file) {
printer(
"// THIS FILE IS AUTOGENERATED FROM $path$\n"
"\n"
"#include \"$path_no_extension$.proxy.h\"\n"
"\n"
"#include \"$path_no_extension$.service.h\"\n\n"
"#include \"yb/rpc/proxy.h\"\n"
"#include \"yb/rpc/outbound_call.h\"\n"
"#include \"yb/util/metrics.h\"\n"
"#include \"yb/util/net/sockaddr.h\"\n"
"\n"
);
GenerateMetricDefines(printer, file, outbound_metrics);
printer(
"$open_namespace$\n\n"
"namespace {\n\n"
);
for (int service_idx = 0; service_idx < file->service_count(); ++service_idx) {
const auto* service = file->service(service_idx);
ScopedSubstituter service_subs(printer, service);
printer("const std::string kFull$service_name$Name = \"$original_full_service_name$\";\n\n");
printer(
"::yb::rpc::ProxyMetricsPtr Create$service_name$Metrics("
"const scoped_refptr<MetricEntity>& entity) {\n"
" auto result = std::make_shared<"
"::yb::rpc::ProxyMetricsImpl<$service_method_count$>>();\n"
);
GenerateMethodAssignments(
printer, service, "result->value[to_underlying($service_method_enum$::$metric_enum_key$)]",
false, outbound_metrics);
printer(
" return result;\n}\n\n"
);
}
printer(
"\n} // namespace\n\n"
);
for (int service_idx = 0; service_idx < file->service_count(); ++service_idx) {
const auto* service = file->service(service_idx);
ScopedSubstituter service_subs(printer, service);
printer(
"$service_name$Proxy::$service_name$Proxy(\n"
" ::yb::rpc::ProxyCache* cache, const ::yb::HostPort& remote,\n"
" const ::yb::rpc::Protocol* protocol,\n"
" const ::yb::MonoDelta& resolve_cache_timeout)\n"
" : ProxyBase(kFull$service_name$Name, &Create$service_name$Metrics,\n"
" cache, remote, protocol, resolve_cache_timeout) {}\n\n"
);
for (int method_idx = 0; method_idx < service->method_count(); ++method_idx) {
ScopedSubstituter method_subs(printer, service->method(method_idx), rpc::RpcSides::PROXY);
printer(
"::yb::Status $service_name$Proxy::$rpc_name$(\n"
" const $request$ &req, $response$ *resp, ::yb::rpc::RpcController *controller) "
"const {\n"
" static ::yb::rpc::RemoteMethod method(\"$full_service_name$\", \"$rpc_name$\");\n"
" return proxy().SyncRequest(\n"
" &method, metrics<$service_method_count$>(static_cast<size_t>("
"$service_method_enum$::$metric_enum_key$)), req, resp, controller);\n"
"}\n"
"\n"
"void $service_name$Proxy::$rpc_name$Async(\n"
" const $request$ &req, $response$ *resp, ::yb::rpc::RpcController *controller,\n"
" ::yb::rpc::ResponseCallback callback) const {\n"
" static ::yb::rpc::RemoteMethod method(\"$full_service_name$\", \"$rpc_name$\");\n"
" proxy().AsyncRequest(\n"
" &method, metrics<$service_method_count$>(static_cast<size_t>("
"$service_method_enum$::$metric_enum_key$)), req, resp, controller, "
"std::move(callback));\n"
"}\n"
"\n"
);
}
}
printer("$close_namespace$");
}
} // namespace gen_yrpc
} // namespace yb
| 3,070 |
1,330 | package jonathanfinerty.once;
import androidx.annotation.NonNull;
import androidx.test.core.app.ApplicationProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = 28)
public class ConcurrencyTests {
@Before
public void Setup() {
Once.initialise(ApplicationProvider.getApplicationContext());
}
@After
public void CleanUp() {
Once.clearAll();
}
@Test
public void concurrentMarkDone() throws Throwable {
testConcurrency(() -> Once.markDone("tag under test"));
}
@Test
public void concurrentToDo() throws Throwable {
testConcurrency(() -> Once.toDo("tag under test"));
}
private void testConcurrency(Runnable functionUnderTest) throws Throwable {
ExceptionTrackingThreadFactory threadFactory = new ExceptionTrackingThreadFactory();
ExecutorService exec = Executors.newFixedThreadPool(16, threadFactory);
for (int i = 0; i < 10000; i++) {
exec.execute(functionUnderTest);
}
exec.shutdown();
exec.awaitTermination(10, TimeUnit.SECONDS);
if (threadFactory.getLastExceptionThrown() != null) {
throw threadFactory.getLastExceptionThrown();
}
}
public static final class ExceptionTrackingThreadFactory implements ThreadFactory {
private Throwable lastExceptionThrown;
public Throwable getLastExceptionThrown() {
return lastExceptionThrown;
}
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread t = new Thread(runnable);
t.setUncaughtExceptionHandler((thread, throwable) -> lastExceptionThrown = throwable);
return t;
}
}
}
| 780 |
2,151 | <gh_stars>1000+
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_AUTOCOMPLETE_SHORTCUTS_EXTENSIONS_MANAGER_H_
#define CHROME_BROWSER_AUTOCOMPLETE_SHORTCUTS_EXTENSIONS_MANAGER_H_
#include "base/macros.h"
#include "base/scoped_observer.h"
#include "base/supports_user_data.h"
#include "extensions/browser/extension_registry_observer.h"
class Profile;
namespace extensions {
class ExtensionRegistry;
}
// This class manages the removal of shortcuts associated with an extension when
// that extension is unloaded.
class ShortcutsExtensionsManager
: public base::SupportsUserData::Data,
public extensions::ExtensionRegistryObserver {
public:
explicit ShortcutsExtensionsManager(Profile* profile);
~ShortcutsExtensionsManager() override;
// extensions::ExtensionRegistryObserver:
void OnExtensionUnloaded(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) override;
void OnShutdown(extensions::ExtensionRegistry* registry) override;
private:
ScopedObserver<extensions::ExtensionRegistry,
extensions::ExtensionRegistryObserver>
registry_observer_;
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(ShortcutsExtensionsManager);
};
#endif // CHROME_BROWSER_AUTOCOMPLETE_SHORTCUTS_EXTENSIONS_MANAGER_H_
| 526 |
14,668 | #!/usr/bin/env vpython3
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit test for milestones.py"""
import argparse
import os
import sys
import tempfile
import textwrap
import unittest
INFRA_CONFIG_DIR = os.path.abspath(os.path.join(__file__, '..', '..', '..'))
sys.path.append(os.path.join(INFRA_CONFIG_DIR, 'scripts'))
import milestones
class ParseError(Exception):
pass
class ArgumentParser(argparse.ArgumentParser):
"""Test version of ArgumentParser
This behaves the same as argparse.ArgumentParser except that the error
method raises an instance of ParseError rather than printing output
and exiting. This simplifies testing for error conditions and puts the
actual error information in the traceback for unexpectedly failing
tests.
"""
def error(self, message):
raise ParseError(message)
class MilestonesUnitTest(unittest.TestCase):
def test_parse_args_fails_without_subcommand(self):
with self.assertRaises(ParseError) as caught:
milestones.parse_args([], parser_type=ArgumentParser)
self.assertEqual(str(caught.exception), 'no sub-command specified')
def test_activate_parse_args_fails_when_missing_required_args(self):
with self.assertRaises(ParseError) as caught:
milestones.parse_args(['activate'], parser_type=ArgumentParser)
self.assertEqual(
str(caught.exception),
'the following arguments are required: --milestone, --branch')
def test_activate_parse_args(self):
args = milestones.parse_args(
['activate', '--milestone', 'MM', '--branch', 'BBBB'],
parser_type=ArgumentParser)
self.assertEqual(args.milestone, 'MM')
self.assertEqual(args.branch, 'BBBB')
def test_numeric_sort_key(self):
self.assertEqual(
sorted(['b10', 'b010', 'b9', 'a10', 'a1', 'a9'],
key=milestones.numeric_sort_key),
['a1', 'a9', 'a10', 'b9', 'b010', 'b10'])
def test_add_milestone_fails_when_milestone_already_active(self):
current_milestones = {
'99': {
'name': 'm99',
'project': 'chromium-m99',
'ref': 'refs/branch-heads/AAAA',
},
}
with self.assertRaises(milestones.MilestonesException) as caught:
milestones.add_milestone(
current_milestones, milestone='99', branch='BBBB')
self.assertIn(
"there is already an active milestone with id '99'",
str(caught.exception))
def test_add_milestone(self):
current_milestones = {
'99': {
'name': 'm99',
'project': 'chromium-m99',
'ref': 'refs/branch-heads/AAAA',
},
'101': {
'name': 'm101',
'project': 'chromium-m101',
'ref': 'refs/branch-heads/BBBB',
},
}
output = milestones.add_milestone(
current_milestones, milestone='100', branch='CCCC')
self.assertEqual(output, textwrap.dedent("""\
{
"99": {
"name": "m99",
"project": "chromium-m99",
"ref": "refs/branch-heads/AAAA"
},
"100": {
"name": "m100",
"project": "chromium-m100",
"ref": "refs/branch-heads/CCCC"
},
"101": {
"name": "m101",
"project": "chromium-m101",
"ref": "refs/branch-heads/BBBB"
}
}
"""))
def test_remove_milestone_fails_when_milestone_not_active(self):
current_milestones = {}
with self.assertRaises(milestones.MilestonesException) as caught:
milestones.remove_milestone(current_milestones, '99')
self.assertIn(
"'99' does not refer to an active milestone", str(caught.exception))
def test_remove_milestone(self):
current_milestones = {
'99': {
'name': 'm99',
'project': 'chromium-m99',
'ref': 'refs/branch-heads/AAAA',
},
'101': {
'name': 'm101',
'project': 'chromium-m101',
'ref': 'refs/branch-heads/BBBB',
},
'100': {
'name': 'm100',
'project': 'chromium-m100',
'ref': 'refs/branch-heads/CCCC'
},
}
output = milestones.remove_milestone(current_milestones, milestone='99')
self.assertEqual(output, textwrap.dedent("""\
{
"100": {
"name": "m100",
"project": "chromium-m100",
"ref": "refs/branch-heads/CCCC"
},
"101": {
"name": "m101",
"project": "chromium-m101",
"ref": "refs/branch-heads/BBBB"
}
}
"""))
if __name__ == '__main__':
unittest.main() | 2,269 |
488 | <gh_stars>100-1000
[
"../../protos/google/cloud/vision/v1p2beta1/geometry.proto",
"../../protos/google/cloud/vision/v1p2beta1/image_annotator.proto",
"../../protos/google/cloud/vision/v1p2beta1/text_annotation.proto",
"../../protos/google/cloud/vision/v1p2beta1/web_detection.proto"
]
| 127 |
5,169 | <reponame>Gantios/Specs<filename>Specs/5/2/f/AlivcConan/0.9.5.2/AlivcConan.podspec.json
{
"name": "AlivcConan",
"version": "0.9.5.2",
"summary": "AlivcConan_iOS",
"description": "It's an SDK for aliyun conan sdk, which implement by Objective-C.",
"homepage": "https://github.com/aliyunvideo/AlivcConanSDK",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"aliyunvideo": "<EMAIL>"
},
"source": {
"git": "https://github.com/aliyunvideo/AlivcConanSDK.git",
"tag": "0.9.5.2"
},
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"subspecs": [
{
"name": "AlivcConan",
"vendored_frameworks": "AlivcConan.framework"
}
]
}
| 343 |
6,717 | <filename>tools/vsimporter/src/PBX/PBXTargetDependency.cpp
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "PlistFuncs.h"
#include "SBLog.h"
#include "PBXTargetDependency.h"
#include "PBXTarget.h"
#include "PBXContainerItemProxy.h"
#include "PBXObjectIdConvert.h"
PBXTargetDependency::~PBXTargetDependency() {
}
PBXTargetDependency::PBXTargetDependency() : m_targetPtr(NULL), m_targetProxyPtr(NULL) {
}
PBXTargetDependency* PBXTargetDependency::createFromPlist(const String& id,
const Plist::dictionary_type& plist,
const PBXDocument* pbxDoc) {
PBXTargetDependency* ret = new PBXTargetDependency;
ret->initFromPlist(id, plist, pbxDoc);
return ret;
}
void PBXTargetDependency::initFromPlist(const String& id, const Plist::dictionary_type& plist, const PBXDocument* pbxDoc) {
// Call super init
PBXObject::initFromPlist(id, plist, pbxDoc);
// Get name. Not sure about its usefullness though.
getStringForKey(plist, "name", m_name, VALUE_OPTIONAL, m_parseER);
// Get target
getStringForKey(plist, "target", m_targetId, VALUE_OPTIONAL, m_parseER);
// Get targetProxy
// Not sure what it means when targetProxy is not specified, but sometimes it's not.
getStringForKey(plist, "targetProxy", m_targetProxyId, VALUE_OPTIONAL, m_parseER);
}
void PBXTargetDependency::resolvePointers() {
// Resolve target ptr
convertObjectId(m_pbxDoc, m_targetId, m_targetPtr);
// Resolve targetProxy ptr
convertObjectId(m_pbxDoc, m_targetProxyId, m_targetProxyPtr);
}
| 869 |
3,631 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.mvel.integrationtests.session;
import java.util.Collection;
import org.drools.core.base.RuleNameEndsWithAgendaFilter;
import org.drools.core.base.RuleNameEqualsAgendaFilter;
import org.drools.core.base.RuleNameMatchesAgendaFilter;
import org.drools.core.base.RuleNameStartsWithAgendaFilter;
import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
import org.drools.testcoverage.common.util.KieBaseUtil;
import org.drools.testcoverage.common.util.TestParametersUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieSessionConfiguration;
import org.kie.api.runtime.conf.DirectFiringOption;
import org.kie.api.runtime.rule.AgendaFilter;
import org.mockito.ArgumentCaptor;
import static org.assertj.core.api.Assertions.fail;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(Parameterized.class)
public class AgendaFilterTest {
private final KieBaseTestConfiguration kieBaseTestConfiguration;
public AgendaFilterTest(final KieBaseTestConfiguration kieBaseTestConfiguration) {
this.kieBaseTestConfiguration = kieBaseTestConfiguration;
}
@Parameterized.Parameters(name = "KieBase type={0}")
public static Collection<Object[]> getParameters() {
return TestParametersUtil.getKieBaseCloudConfigurations(true);
}
@Test
public void testAgendaFilterRuleNameStartsWith() {
testAgendaFilter(new RuleNameStartsWithAgendaFilter("B"), "Bbb");
}
@Test
public void testAgendaFilterRuleNameEndsWith() {
testAgendaFilter(new RuleNameEndsWithAgendaFilter("a"), "Aaa");
}
@Test
public void testAgendaFilterRuleNameMatches() {
testAgendaFilter(new RuleNameMatchesAgendaFilter(".*b."), "Bbb");
}
@Test
public void testAgendaFilterRuleNameEquals() {
testAgendaFilter(new RuleNameEqualsAgendaFilter("Aaa"), "Aaa");
}
private void testAgendaFilter(final AgendaFilter agendaFilter, final String expectedMatchingRuleName) {
final String str = "package org.drools.compiler\n" +
"rule Aaa when then end\n" +
"rule Bbb when then end\n";
KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
KieSession ksession = kbase.newKieSession();
final org.kie.api.event.rule.AgendaEventListener ael = mock(org.kie.api.event.rule.AgendaEventListener.class);
ksession.addEventListener(ael);
final int rules = ksession.fireAllRules(agendaFilter);
assertEquals(1, rules);
final ArgumentCaptor<org.kie.api.event.rule.AfterMatchFiredEvent> arg = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
verify(ael).afterMatchFired(arg.capture());
assertThat(arg.getValue().getMatch().getRule().getName(), is(expectedMatchingRuleName));
}
@Test
public void testDirectFiringIgnoresAgendaFilter() {
// DROOLS-6510
String str =
"rule R when\n" +
" String() \n" +
"then\n" +
" throw new IllegalStateException();\n" +
"end";
try {
KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
KieSessionConfiguration config = KieServices.get().newKieSessionConfiguration();
config.setOption(DirectFiringOption.YES);
Environment environment = KieServices.get().newEnvironment();
KieSession ksession = kbase.newKieSession(config, environment);
ksession.insert("Lukas");
assertEquals(0, ksession.fireAllRules(match -> false));
} catch (Throwable ex) {
fail("Should not have thrown.", ex);
}
}
}
| 1,766 |
2,151 | <filename>ios/chrome/browser/ui/main/transitions/bvc_container_to_tab_switcher_animator.h
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_MAIN_TRANSITIONS_BVC_CONTAINER_TO_TAB_SWITCHER_ANIMATOR_H_
#define IOS_CHROME_BROWSER_UI_MAIN_TRANSITIONS_BVC_CONTAINER_TO_TAB_SWITCHER_ANIMATOR_H_
#import <UIKit/UIKit.h>
@protocol TabSwitcher;
@interface BVCContainerToTabSwitcherAnimator
: NSObject<UIViewControllerAnimatedTransitioning>
// The TabSwitcher to animate.
@property(nonatomic, readwrite, weak) id<TabSwitcher> tabSwitcher;
@end
#endif // IOS_CHROME_BROWSER_UI_MAIN_TRANSITIONS_BVC_CONTAINER_TO_TAB_SWITCHER_ANIMATOR_H_
| 306 |
335 | <filename>P/Plasmapheresis_noun.json
{
"word": "Plasmapheresis",
"definitions": [
"A method of removing blood plasma from the body by withdrawing blood, separating it into plasma and cells, and transfusing the cells back into the bloodstream. It is performed especially to remove antibodies in treating autoimmune conditions."
],
"parts-of-speech": "Noun"
} | 113 |
2,151 | <reponame>cohortfsllc/cohort-cocl2-sandbox
#!/usr/bin/python
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import posixpath
import subprocess
import sys
import urlparse
import file_tools
import log_tools
import platform
GIT_ALTERNATES_PATH = os.path.join('.git', 'objects', 'info', 'alternates')
class InvalidRepoException(Exception):
def __init__(self, expected_repo, msg, *args):
Exception.__init__(self, msg % args)
self.expected_repo = expected_repo
def GitCmd():
"""Return the git command to execute for the host platform."""
if platform.IsWindows():
# On windows, we want to use the depot_tools version of git, which has
# git.bat as an entry point. When running through the msys command
# prompt, subprocess does not handle batch files. Explicitly invoking
# cmd.exe to be sure we run the correct git in this case.
return ['cmd.exe', '/c', 'git.bat']
else:
return ['git']
def CheckGitOutput(args):
"""Run a git subcommand and capture its stdout a la subprocess.check_output.
Args:
args: list of arguments to 'git'
"""
return log_tools.CheckOutput(GitCmd() + args)
def ValidateGitRepo(url, directory, clobber_mismatch=False, logger=None):
"""Validates a git repository tracks a particular URL.
Given a git directory, this function will validate if the git directory
actually tracks an expected URL. If the directory does not exist nothing
will be done.
Args:
url: URL to look for.
directory: Directory to look for.
clobber_mismatch: If True, will delete invalid directories instead of raising
an exception.
"""
if logger is None:
logger = log_tools.GetConsoleLogger()
git_dir = os.path.join(directory, '.git')
if os.path.exists(git_dir):
try:
if IsURLInRemoteRepoList(url, directory, include_fetch=True,
include_push=False):
return
logger.warn('Local git repo (%s) does not track url (%s)',
directory, url)
except:
logger.error('Invalid git repo: %s', directory)
if not clobber_mismatch:
raise InvalidRepoException(url, 'Invalid local git repo: %s', directory)
else:
logger.debug('Clobbering invalid git repo %s' % directory)
file_tools.RemoveDirectoryIfPresent(directory)
elif os.path.exists(directory) and len(os.listdir(directory)) != 0:
if not clobber_mismatch:
raise InvalidRepoException(url,
'Invalid non-empty repository destination %s',
directory)
else:
logger.debug('Clobbering intended repository destination: %s', directory)
file_tools.RemoveDirectoryIfPresent(directory)
def SyncGitRepo(url, destination, revision, reclone=False, pathspec=None,
git_cache=None, push_url=None, logger=None):
"""Sync an individual git repo.
Args:
url: URL to sync
destination: Directory to check out into.
revision: Pinned revision to check out. If None, do not check out a
pinned revision.
reclone: If True, delete the destination directory and re-clone the repo.
pathspec: If not None, add the path to the git checkout command, which
causes it to just update the working tree without switching
branches.
git_cache: If set, assumes URL has been populated within the git cache
directory specified and sets the fetch URL to be from the
git_cache.
"""
if logger is None:
logger = log_tools.GetConsoleLogger()
if reclone:
logger.debug('Clobbering source directory %s' % destination)
file_tools.RemoveDirectoryIfPresent(destination)
if git_cache:
git_cache_url = GetGitCacheURL(git_cache, url)
else:
git_cache_url = None
# If the destination is a git repository, validate the tracked origin.
git_dir = os.path.join(destination, '.git')
if os.path.exists(git_dir):
if not IsURLInRemoteRepoList(url, destination, include_fetch=True,
include_push=False):
# If the git cache URL is being tracked instead of the fetch URL, we
# can safely redirect it to the fetch URL instead.
if git_cache_url and IsURLInRemoteRepoList(git_cache_url, destination,
include_fetch=True,
include_push=False):
GitSetRemoteRepo(url, destination, push_url=push_url,
logger=logger)
else:
logger.error('Git Repo (%s) does not track URL: %s',
destination, url)
raise InvalidRepoException(url, 'Could not sync git repo: %s',
destination)
# Make sure the push URL is set correctly as well.
if not IsURLInRemoteRepoList(push_url, destination, include_fetch=False,
include_push=True):
GitSetRemoteRepo(url, destination, push_url=push_url)
git = GitCmd()
if not os.path.exists(git_dir):
logger.info('Cloning %s...' % url)
file_tools.MakeDirectoryIfAbsent(destination)
clone_args = ['clone', '-n']
if git_cache_url:
clone_args.extend(['--reference', git_cache_url])
log_tools.CheckCall(git + clone_args + [url, '.'],
logger=logger, cwd=destination)
if url != push_url:
GitSetRemoteRepo(url, destination, push_url=push_url, logger=logger)
# If a git cache URL is supplied, make sure it is setup as a git alternate.
if git_cache_url:
git_alternates = [git_cache_url]
else:
git_alternates = []
GitSetRepoAlternates(destination, git_alternates, append=False, logger=logger)
if revision is not None:
logger.info('Checking out pinned revision...')
log_tools.CheckCall(git + ['fetch', '--all'],
logger=logger, cwd=destination)
path = [pathspec] if pathspec else []
log_tools.CheckCall(
git + ['checkout', revision] + path,
logger=logger, cwd=destination)
def CleanGitWorkingDir(directory, reset=False, path=None, logger=None):
"""Clean all or part of an existing git checkout.
Args:
directory: Directory where the git repo is currently checked out
reset: If True, also reset the working directory to HEAD
path: path to clean, relative to the repo directory. If None,
clean the whole working directory
"""
repo_path = [path] if path else []
log_tools.CheckCall(GitCmd() + ['clean', '-dffx'] + repo_path,
logger=logger, cwd=directory)
if reset:
log_tools.CheckCall(GitCmd() + ['reset', '--hard', 'HEAD'],
logger=logger, cwd=directory)
def PopulateGitCache(cache_dir, url_list, logger=None):
"""Fetches a git repo that combines a list of git repos.
This is an interface to the "git cache" command found within depot_tools.
You can populate a cache directory then obtain the local cache url using
GetGitCacheURL(). It is best to sync with the shared option so that the
cloned repository shares the same git objects.
Args:
cache_dir: Local directory where git cache will be populated.
url_list: List of URLs which cache_dir should be populated with.
"""
if url_list:
file_tools.MakeDirectoryIfAbsent(cache_dir)
git = GitCmd()
for url in url_list:
log_tools.CheckCall(git + ['cache', 'populate', '-c', '.', url],
logger=logger, cwd=cache_dir)
def GetGitCacheURL(cache_dir, url, logger=None):
"""Converts a regular git URL to a git cache URL within a cache directory.
Args:
url: original Git URL that is already populated within the cache directory.
cache_dir: Git cache directory that has already populated the URL.
Returns:
Git Cache URL where a git repository can clone/fetch from.
"""
# Make sure we are using absolute paths or else cache exists return relative.
cache_dir = os.path.abspath(cache_dir)
# For CygWin, we must first convert the cache_dir name to a non-cygwin path.
cygwin_path = False
if platform.IsCygWin() and cache_dir.startswith('/cygdrive/'):
cygwin_path = True
drive, file_path = cache_dir[len('/cygdrive/'):].split('/', 1)
cache_dir = drive + ':\\' + file_path.replace('/', '\\')
git_url = log_tools.CheckOutput(GitCmd() + ['cache', 'exists',
'-c', cache_dir,
url],
logger=logger).strip()
# For windows, make sure the git cache URL is a posix path.
if platform.IsWindows():
git_url = git_url.replace('\\', '/')
return git_url
def GitRevInfo(directory):
"""Get the git revision information of a git checkout.
Args:
directory: Existing git working directory.
"""
get_url_command = GitCmd() + ['ls-remote', '--get-url', 'origin']
url = log_tools.CheckOutput(get_url_command, cwd=directory).strip()
# If the URL is actually a directory, it might be a git-cache directory.
# Re-run from that directory to get the actual remote URL.
if os.path.isdir(url):
url = log_tools.CheckOutput(get_url_command, cwd=url).strip()
rev = log_tools.CheckOutput(GitCmd() + ['rev-parse', 'HEAD'],
cwd=directory).strip()
return url, rev
def GetAuthenticatedGitURL(url):
"""Returns the authenticated version of a git URL.
In chromium, there is a special URL that is the "authenticated" version. The
URLs are identical but the authenticated one has special privileges.
"""
urlsplit = urlparse.urlsplit(url)
if urlsplit.scheme in ('https', 'http'):
urldict = urlsplit._asdict()
urldict['scheme'] = 'https'
urldict['path'] = '/a' + urlsplit.path
urlsplit = urlparse.SplitResult(**urldict)
return urlsplit.geturl()
def GitRemoteRepoList(directory, include_fetch=True, include_push=True,
logger=None):
"""Returns a list of remote git repos associated with a directory.
Args:
directory: Existing git working directory.
Returns:
List of (repo_name, repo_url) for tracked remote repos.
"""
remote_repos = log_tools.CheckOutput(GitCmd() + ['remote', '-v'],
logger=logger, cwd=directory)
repo_set = set()
for remote_repo_line in remote_repos.splitlines():
repo_name, repo_url, repo_type = remote_repo_line.split()
if include_fetch and repo_type == '(fetch)':
repo_set.add((repo_name, repo_url))
elif include_push and repo_type == '(push)':
repo_set.add((repo_name, repo_url))
return sorted(repo_set)
def GitSetRemoteRepo(url, directory, push_url=None,
repo_name='origin', logger=None):
"""Sets the remotely tracked URL for a git repository.
Args:
url: Remote git URL to set.
directory: Local git repository to set tracked repo for.
push_url: If specified, uses a different URL for pushing.
repo_name: set the URL for a particular remote repo name.
"""
git = GitCmd()
try:
log_tools.CheckCall(git + ['remote', 'set-url', repo_name, url],
logger=logger, cwd=directory)
except subprocess.CalledProcessError:
# If setting the URL failed, repo_name may be new. Try adding the URL.
log_tools.CheckCall(git + ['remote', 'add', repo_name, url],
logger=logger, cwd=directory)
if push_url:
log_tools.CheckCall(git + ['remote', 'set-url', '--push',
repo_name, push_url],
logger=logger, cwd=directory)
def IsURLInRemoteRepoList(url, directory, include_fetch=True, include_push=True,
try_authenticated_url=True, logger=None):
"""Returns whether or not a url is a remote repo in a local git directory.
Args:
url: URL to look for in remote repo list.
directory: Existing git working directory.
"""
if try_authenticated_url:
valid_urls = (url, GetAuthenticatedGitURL(url))
else:
valid_urls = (url,)
remote_repo_list = GitRemoteRepoList(directory,
include_fetch=include_fetch,
include_push=include_push,
logger=logger)
return len([repo_name for
repo_name, repo_url in remote_repo_list
if repo_url in valid_urls]) > 0
def GitGetRepoAlternates(directory):
"""Gets the list of git alternates for a local git repo.
Args:
directory: Local git repository to get the git alternate for.
Returns:
List of git alternates set for the local git repository.
"""
git_alternates_file = os.path.join(directory, GIT_ALTERNATES_PATH)
if os.path.isfile(git_alternates_file):
with open(git_alternates_file, 'rt') as f:
alternates_list = []
for line in f.readlines():
line = line.strip()
if line:
if posixpath.basename(line) == 'objects':
line = posixpath.dirname(line)
alternates_list.append(line)
return alternates_list
return []
def GitSetRepoAlternates(directory, alternates_list, append=True, logger=None):
"""Sets the list of git alternates for a local git repo.
Args:
directory: Local git repository.
alternates_list: List of local git repositories for the git alternates.
append: If True, will append the list to currently set list of alternates.
"""
if logger is None:
logger = log_tools.GetConsoleLogger()
git_alternates_file = os.path.join(directory, GIT_ALTERNATES_PATH)
git_alternates_dir = os.path.dirname(git_alternates_file)
if not os.path.isdir(git_alternates_dir):
raise InvalidRepoException(directory,
'Invalid local git repo: %s', directory)
original_alternates_list = GitGetRepoAlternates(directory)
if append:
alternates_list.extend(original_alternates_list)
alternates_list = sorted(set(alternates_list))
if set(original_alternates_list) != set(alternates_list):
lines = [posixpath.join(line, 'objects') + '\n' for line in alternates_list]
logger.info('Setting git alternates:\n\t%s', '\t'.join(lines))
with open(git_alternates_file, 'wb') as f:
f.writelines(lines)
| 5,651 |
497 | <filename>trunk/configs/boards/NEWIFI-Y1S/Gboard.h<gh_stars>100-1000
/* NEWIFI Y1S */
#define BOARD_PID "NEWIFI-Y1S"
#define BOARD_NAME "NEWIFI-Y1S"
#define BOARD_DESC "NEWIFI Y1S Wireless Router"
#define BOARD_VENDOR_NAME "Lenovo(Beijing) Limited"
#define BOARD_VENDOR_URL "http://www.newifi.com/"
#define BOARD_MODEL_URL "http://www.newifi.com/product_newifi1.shtml"
#define BOARD_BOOT_TIME 25
#define BOARD_FLASH_TIME 120
#undef BOARD_GPIO_BTN_RESET
#define BOARD_GPIO_BTN_WPS 11
#undef BOARD_GPIO_BTN_WLTOG
#undef BOARD_GPIO_LED_ALL
#define BOARD_GPIO_LED_WIFI 72
#define BOARD_GPIO_LED_SW5G 50 /* soft led */
#define BOARD_GPIO_LED_POWER 9
#undef BOARD_GPIO_LED_LAN 55
#define BOARD_GPIO_LED_WAN 51
#define BOARD_GPIO_LED_USB 52
#undef BOARD_GPIO_LED_ROUTER
#undef BOARD_GPIO_PWR_USB
/*#define BOARD_GPIO_PWR_USB 54
#define BOARD_GPIO_PWR_USB2 55
#define BOARD_GPIO_PWR_USB3 56*/
#define BOARD_HAS_5G_11AC 1
#define BOARD_NUM_ANT_5G_TX 2
#define BOARD_NUM_ANT_5G_RX 2
#define BOARD_NUM_ANT_2G_TX 2
#define BOARD_NUM_ANT_2G_RX 2
#define BOARD_NUM_ETH_LEDS 1
#define BOARD_HAS_EPHY_L1000 1
#define BOARD_HAS_EPHY_W1000 1
| 565 |
348 | {"nom":"Champsanglard","circ":"1ère circonscription","dpt":"Creuse","inscrits":188,"abs":93,"votants":95,"blancs":13,"nuls":3,"exp":79,"res":[{"nuance":"REM","nom":"<NAME>","voix":53},{"nuance":"LR","nom":"<NAME>","voix":26}]} | 89 |
887 | <gh_stars>100-1000
#ifndef __CCD_CONFIG_H_
#define __CCD_CONFIG_H_
#define CCD_DOUBLE 1
#endif
| 50 |
4,551 | <reponame>kageiit/robolectric
package org.robolectric.manifest;
/**
* Holds permission data from manifest.
*/
public class PermissionItemData extends PackageItemData {
private final String label;
private final String description;
private final String permissionGroup;
private final String protectionLevel;
public PermissionItemData(String name, String label, String description,
String permissionGroup, String protectionLevel, MetaData metaData) {
super(name, metaData);
this.label = label;
this.description = description;
this.permissionGroup = permissionGroup;
this.protectionLevel = protectionLevel;
}
public String getLabel() {
return label;
}
public String getDescription() {
return description;
}
public String getPermissionGroup() {
return permissionGroup;
}
public String getProtectionLevel() {
return protectionLevel;
}
}
| 259 |
1,139 | package com.journaldev.androidextendedfab;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ExtendedFloatingActionButton extendedFAB;
ExtendedFloatingActionButton extendedFAB2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
extendedFAB = findViewById(R.id.extFab);
extendedFAB2 = findViewById(R.id.extFab2);
extendedFAB2.setOnClickListener(this);
extendedFAB.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.extFab:
if(extendedFAB.isExtended())
{
extendedFAB.shrink(true);
}
else{
extendedFAB.extend(true);
}
break;
case R.id.extFab2:
if(extendedFAB.isShown())
extendedFAB.hide(true);
else {
extendedFAB.show(true);
}
break;
}
}
}
| 671 |
526 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria term. */
package org.odpi.openmetadata.accessservices.subjectarea.handlers;
import org.odpi.openmetadata.accessservices.subjectarea.properties.objects.common.Config;
import org.odpi.openmetadata.accessservices.subjectarea.responses.SubjectAreaOMASAPIResponse;
import org.odpi.openmetadata.commonservices.generichandlers.*;
/**
* SubjectAreaTermHandler manages config objects from the property server. It runs server-side in the subject Area
* OMAS and retrieves configuration information.
*/
public class SubjectAreaConfigHandler extends SubjectAreaHandler {
private static final String className = SubjectAreaConfigHandler.class.getName();
/**
* Construct the Subject Area Config Handler
* needed to operate within a single server instance.
*
* @param genericHandler generic handler
* @param maxPageSize maximum page size
*/
public SubjectAreaConfigHandler(OpenMetadataAPIGenericHandler genericHandler, int maxPageSize) {
super(genericHandler, maxPageSize);
}
/**
* Get the subject area configuration.
* @param userId user id of the caller
* @return config response
*/
public SubjectAreaOMASAPIResponse<Config> getConfig(String userId) {
// TODO check the userid
SubjectAreaOMASAPIResponse<Config> response = new SubjectAreaOMASAPIResponse<>();
Config config = new Config();
config.setMaxPageSize(maxPageSize);
response.addResult(config);
return response;
}
} | 522 |
938 | <reponame>LaudateCorpus1/swift-llvm<gh_stars>100-1000
//===- AMDGPURegisterBankInfo.cpp -------------------------------*- C++ -*-==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the RegisterBankInfo class for
/// AMDGPU.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//
#include "AMDGPURegisterBankInfo.h"
#include "AMDGPUInstrInfo.h"
#include "AMDGPUSubtarget.h"
#include "SIMachineFunctionInfo.h"
#include "SIRegisterInfo.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
#include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Constants.h"
#define GET_TARGET_REGBANK_IMPL
#include "AMDGPUGenRegisterBank.inc"
// This file will be TableGen'ed at some point.
#include "AMDGPUGenRegisterBankInfo.def"
using namespace llvm;
AMDGPURegisterBankInfo::AMDGPURegisterBankInfo(const TargetRegisterInfo &TRI)
: AMDGPUGenRegisterBankInfo(),
TRI(static_cast<const SIRegisterInfo*>(&TRI)) {
// HACK: Until this is fully tablegen'd.
static bool AlreadyInit = false;
if (AlreadyInit)
return;
AlreadyInit = true;
const RegisterBank &RBSGPR = getRegBank(AMDGPU::SGPRRegBankID);
(void)RBSGPR;
assert(&RBSGPR == &AMDGPU::SGPRRegBank);
const RegisterBank &RBVGPR = getRegBank(AMDGPU::VGPRRegBankID);
(void)RBVGPR;
assert(&RBVGPR == &AMDGPU::VGPRRegBank);
}
unsigned AMDGPURegisterBankInfo::copyCost(const RegisterBank &Dst,
const RegisterBank &Src,
unsigned Size) const {
if (Dst.getID() == AMDGPU::SGPRRegBankID &&
Src.getID() == AMDGPU::VGPRRegBankID) {
return std::numeric_limits<unsigned>::max();
}
// SGPRRegBank with size 1 is actually vcc or another 64-bit sgpr written by
// the valu.
if (Size == 1 && Dst.getID() == AMDGPU::SCCRegBankID &&
(Src.getID() == AMDGPU::SGPRRegBankID ||
Src.getID() == AMDGPU::VGPRRegBankID ||
Src.getID() == AMDGPU::VCCRegBankID))
return std::numeric_limits<unsigned>::max();
if (Dst.getID() == AMDGPU::SCCRegBankID &&
Src.getID() == AMDGPU::VCCRegBankID)
return std::numeric_limits<unsigned>::max();
return RegisterBankInfo::copyCost(Dst, Src, Size);
}
unsigned AMDGPURegisterBankInfo::getBreakDownCost(
const ValueMapping &ValMapping,
const RegisterBank *CurBank) const {
assert(ValMapping.NumBreakDowns == 2 &&
ValMapping.BreakDown[0].Length == 32 &&
ValMapping.BreakDown[0].StartIdx == 0 &&
ValMapping.BreakDown[1].Length == 32 &&
ValMapping.BreakDown[1].StartIdx == 32 &&
ValMapping.BreakDown[0].RegBank == ValMapping.BreakDown[1].RegBank);
// 32-bit extract of a 64-bit value is just access of a subregister, so free.
// TODO: Cost of 0 hits assert, though it's not clear it's what we really
// want.
// TODO: 32-bit insert to a 64-bit SGPR may incur a non-free copy due to SGPR
// alignment restrictions, but this probably isn't important.
return 1;
}
const RegisterBank &AMDGPURegisterBankInfo::getRegBankFromRegClass(
const TargetRegisterClass &RC) const {
if (TRI->isSGPRClass(&RC))
return getRegBank(AMDGPU::SGPRRegBankID);
return getRegBank(AMDGPU::VGPRRegBankID);
}
template <unsigned NumOps>
RegisterBankInfo::InstructionMappings
AMDGPURegisterBankInfo::addMappingFromTable(
const MachineInstr &MI, const MachineRegisterInfo &MRI,
const std::array<unsigned, NumOps> RegSrcOpIdx,
ArrayRef<OpRegBankEntry<NumOps>> Table) const {
InstructionMappings AltMappings;
SmallVector<const ValueMapping *, 10> Operands(MI.getNumOperands());
unsigned Sizes[NumOps];
for (unsigned I = 0; I < NumOps; ++I) {
unsigned Reg = MI.getOperand(RegSrcOpIdx[I]).getReg();
Sizes[I] = getSizeInBits(Reg, MRI, *TRI);
}
for (unsigned I = 0, E = MI.getNumExplicitDefs(); I != E; ++I) {
unsigned SizeI = getSizeInBits(MI.getOperand(I).getReg(), MRI, *TRI);
Operands[I] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, SizeI);
}
unsigned MappingID = 0;
for (const auto &Entry : Table) {
for (unsigned I = 0; I < NumOps; ++I) {
int OpIdx = RegSrcOpIdx[I];
Operands[OpIdx] = AMDGPU::getValueMapping(Entry.RegBanks[I], Sizes[I]);
}
AltMappings.push_back(&getInstructionMapping(MappingID++, Entry.Cost,
getOperandsMapping(Operands),
Operands.size()));
}
return AltMappings;
}
RegisterBankInfo::InstructionMappings
AMDGPURegisterBankInfo::getInstrAlternativeMappingsIntrinsicWSideEffects(
const MachineInstr &MI, const MachineRegisterInfo &MRI) const {
switch (MI.getOperand(MI.getNumExplicitDefs()).getIntrinsicID()) {
case Intrinsic::amdgcn_buffer_load: {
static const OpRegBankEntry<3> Table[4] = {
// Perfectly legal.
{ { AMDGPU::SGPRRegBankID, AMDGPU::VGPRRegBankID, AMDGPU::SGPRRegBankID }, 1 },
{ { AMDGPU::SGPRRegBankID, AMDGPU::VGPRRegBankID, AMDGPU::VGPRRegBankID }, 1 },
// Waterfall loop needed for rsrc. In the worst case this will execute
// approximately an extra 10 * wavesize + 2 instructions.
{ { AMDGPU::VGPRRegBankID, AMDGPU::VGPRRegBankID, AMDGPU::SGPRRegBankID }, 1000 },
{ { AMDGPU::VGPRRegBankID, AMDGPU::VGPRRegBankID, AMDGPU::VGPRRegBankID }, 1000 }
};
// rsrc, voffset, offset
const std::array<unsigned, 3> RegSrcOpIdx = { { 2, 3, 4 } };
return addMappingFromTable<3>(MI, MRI, RegSrcOpIdx, makeArrayRef(Table));
}
case Intrinsic::amdgcn_s_buffer_load: {
static const OpRegBankEntry<2> Table[4] = {
// Perfectly legal.
{ { AMDGPU::SGPRRegBankID, AMDGPU::SGPRRegBankID }, 1 },
// Only need 1 register in loop
{ { AMDGPU::SGPRRegBankID, AMDGPU::VGPRRegBankID }, 300 },
// Have to waterfall the resource.
{ { AMDGPU::VGPRRegBankID, AMDGPU::SGPRRegBankID }, 1000 },
// Have to waterfall the resource, and the offset.
{ { AMDGPU::VGPRRegBankID, AMDGPU::VGPRRegBankID }, 1500 }
};
// rsrc, offset
const std::array<unsigned, 2> RegSrcOpIdx = { { 2, 3 } };
return addMappingFromTable<2>(MI, MRI, RegSrcOpIdx, makeArrayRef(Table));
}
default:
return RegisterBankInfo::getInstrAlternativeMappings(MI);
}
}
RegisterBankInfo::InstructionMappings
AMDGPURegisterBankInfo::getInstrAlternativeMappings(
const MachineInstr &MI) const {
const MachineFunction &MF = *MI.getParent()->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
InstructionMappings AltMappings;
switch (MI.getOpcode()) {
case TargetOpcode::G_AND:
case TargetOpcode::G_OR:
case TargetOpcode::G_XOR: {
unsigned Size = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
if (Size != 64)
break;
const InstructionMapping &SSMapping = getInstructionMapping(
1, 1, getOperandsMapping(
{AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size)}),
3); // Num Operands
AltMappings.push_back(&SSMapping);
const InstructionMapping &VVMapping = getInstructionMapping(
2, 2, getOperandsMapping(
{AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size)}),
3); // Num Operands
AltMappings.push_back(&VVMapping);
const InstructionMapping &SVMapping = getInstructionMapping(
3, 3, getOperandsMapping(
{AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size)}),
3); // Num Operands
AltMappings.push_back(&SVMapping);
// SGPR in LHS is slightly preferrable, so make it VS more expnesive than
// SV.
const InstructionMapping &VSMapping = getInstructionMapping(
3, 4, getOperandsMapping(
{AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::SGPRRegBankID, Size)}),
3); // Num Operands
AltMappings.push_back(&VSMapping);
break;
}
case TargetOpcode::G_LOAD: {
unsigned Size = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
// FIXME: Should we be hard coding the size for these mappings?
const InstructionMapping &SSMapping = getInstructionMapping(
1, 1, getOperandsMapping(
{AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 64)}),
2); // Num Operands
AltMappings.push_back(&SSMapping);
const InstructionMapping &VVMapping = getInstructionMapping(
2, 1, getOperandsMapping(
{AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 64)}),
2); // Num Operands
AltMappings.push_back(&VVMapping);
// FIXME: Should this be the pointer-size (64-bits) or the size of the
// register that will hold the bufffer resourc (128-bits).
const InstructionMapping &VSMapping = getInstructionMapping(
3, 1, getOperandsMapping(
{AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 64)}),
2); // Num Operands
AltMappings.push_back(&VSMapping);
return AltMappings;
}
case TargetOpcode::G_ICMP: {
unsigned Size = getSizeInBits(MI.getOperand(2).getReg(), MRI, *TRI);
const InstructionMapping &SSMapping = getInstructionMapping(1, 1,
getOperandsMapping({AMDGPU::getValueMapping(AMDGPU::SCCRegBankID, 1),
nullptr, // Predicate operand.
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size)}),
4); // Num Operands
AltMappings.push_back(&SSMapping);
const InstructionMapping &SVMapping = getInstructionMapping(2, 1,
getOperandsMapping({AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1),
nullptr, // Predicate operand.
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size)}),
4); // Num Operands
AltMappings.push_back(&SVMapping);
const InstructionMapping &VSMapping = getInstructionMapping(3, 1,
getOperandsMapping({AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1),
nullptr, // Predicate operand.
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size)}),
4); // Num Operands
AltMappings.push_back(&VSMapping);
const InstructionMapping &VVMapping = getInstructionMapping(4, 1,
getOperandsMapping({AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1),
nullptr, // Predicate operand.
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size)}),
4); // Num Operands
AltMappings.push_back(&VVMapping);
return AltMappings;
}
case TargetOpcode::G_SELECT: {
unsigned Size = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
const InstructionMapping &SSMapping = getInstructionMapping(1, 1,
getOperandsMapping({AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SCCRegBankID, 1),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size)}),
4); // Num Operands
AltMappings.push_back(&SSMapping);
const InstructionMapping &VVMapping = getInstructionMapping(2, 1,
getOperandsMapping({AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size)}),
4); // Num Operands
AltMappings.push_back(&VVMapping);
return AltMappings;
}
case TargetOpcode::G_UADDE:
case TargetOpcode::G_USUBE:
case TargetOpcode::G_SADDE:
case TargetOpcode::G_SSUBE: {
unsigned Size = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
const InstructionMapping &SSMapping = getInstructionMapping(1, 1,
getOperandsMapping(
{AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SCCRegBankID, 1),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::SCCRegBankID, 1)}),
5); // Num Operands
AltMappings.push_back(&SSMapping);
const InstructionMapping &VVMapping = getInstructionMapping(2, 1,
getOperandsMapping({AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1),
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size),
AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1)}),
5); // Num Operands
AltMappings.push_back(&VVMapping);
return AltMappings;
}
case AMDGPU::G_BRCOND: {
assert(MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() == 1);
const InstructionMapping &SMapping = getInstructionMapping(
1, 1, getOperandsMapping(
{AMDGPU::getValueMapping(AMDGPU::SCCRegBankID, 1), nullptr}),
2); // Num Operands
AltMappings.push_back(&SMapping);
const InstructionMapping &VMapping = getInstructionMapping(
1, 1, getOperandsMapping(
{AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1), nullptr }),
2); // Num Operands
AltMappings.push_back(&VMapping);
return AltMappings;
}
case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS:
return getInstrAlternativeMappingsIntrinsicWSideEffects(MI, MRI);
default:
break;
}
return RegisterBankInfo::getInstrAlternativeMappings(MI);
}
void AMDGPURegisterBankInfo::split64BitValueForMapping(
MachineIRBuilder &B,
SmallVector<unsigned, 2> &Regs,
LLT HalfTy,
unsigned Reg) const {
assert(HalfTy.getSizeInBits() == 32);
MachineRegisterInfo *MRI = B.getMRI();
unsigned LoLHS = MRI->createGenericVirtualRegister(HalfTy);
unsigned HiLHS = MRI->createGenericVirtualRegister(HalfTy);
const RegisterBank *Bank = getRegBank(Reg, *MRI, *TRI);
MRI->setRegBank(LoLHS, *Bank);
MRI->setRegBank(HiLHS, *Bank);
Regs.push_back(LoLHS);
Regs.push_back(HiLHS);
B.buildInstr(AMDGPU::G_UNMERGE_VALUES)
.addDef(LoLHS)
.addDef(HiLHS)
.addUse(Reg);
}
/// Replace the current type each register in \p Regs has with \p NewTy
static void setRegsToType(MachineRegisterInfo &MRI, ArrayRef<unsigned> Regs,
LLT NewTy) {
for (unsigned Reg : Regs) {
assert(MRI.getType(Reg).getSizeInBits() == NewTy.getSizeInBits());
MRI.setType(Reg, NewTy);
}
}
static LLT getHalfSizedType(LLT Ty) {
if (Ty.isVector()) {
assert(Ty.getNumElements() % 2 == 0);
return LLT::scalarOrVector(Ty.getNumElements() / 2, Ty.getElementType());
}
assert(Ty.getSizeInBits() % 2 == 0);
return LLT::scalar(Ty.getSizeInBits() / 2);
}
/// Legalize instruction \p MI where operands in \p OpIndices must be SGPRs. If
/// any of the required SGPR operands are VGPRs, perform a waterfall loop to
/// execute the instruction for each unique combination of values in all lanes
/// in the wave. The block will be split such that rest of the instructions are
/// moved to a new block.
///
/// Essentially performs this loop:
//
/// Save Execution Mask
/// For (Lane : Wavefront) {
/// Enable Lane, Disable all other lanes
/// SGPR = read SGPR value for current lane from VGPR
/// VGPRResult[Lane] = use_op SGPR
/// }
/// Restore Execution Mask
///
/// There is additional complexity to try for compare values to identify the
/// unique values used.
void AMDGPURegisterBankInfo::executeInWaterfallLoop(
MachineInstr &MI, MachineRegisterInfo &MRI,
ArrayRef<unsigned> OpIndices) const {
MachineFunction *MF = MI.getParent()->getParent();
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIInstrInfo *TII = ST.getInstrInfo();
MachineBasicBlock::iterator I(MI);
MachineBasicBlock &MBB = *MI.getParent();
const DebugLoc &DL = MI.getDebugLoc();
// Use a set to avoid extra readfirstlanes in the case where multiple operands
// are the same register.
SmallSet<unsigned, 4> SGPROperandRegs;
for (unsigned Op : OpIndices) {
assert(MI.getOperand(Op).isUse());
unsigned Reg = MI.getOperand(Op).getReg();
const RegisterBank *OpBank = getRegBank(Reg, MRI, *TRI);
if (OpBank->getID() == AMDGPU::VGPRRegBankID)
SGPROperandRegs.insert(Reg);
}
// No operands need to be replaced, so no need to loop.
if (SGPROperandRegs.empty())
return;
MachineIRBuilder B(MI);
SmallVector<unsigned, 4> ResultRegs;
SmallVector<unsigned, 4> InitResultRegs;
SmallVector<unsigned, 4> PhiRegs;
for (MachineOperand &Def : MI.defs()) {
LLT ResTy = MRI.getType(Def.getReg());
const RegisterBank *DefBank = getRegBank(Def.getReg(), MRI, *TRI);
ResultRegs.push_back(Def.getReg());
unsigned InitReg = B.buildUndef(ResTy).getReg(0);
unsigned PhiReg = MRI.createGenericVirtualRegister(ResTy);
InitResultRegs.push_back(InitReg);
PhiRegs.push_back(PhiReg);
MRI.setRegBank(PhiReg, *DefBank);
MRI.setRegBank(InitReg, *DefBank);
}
unsigned SaveExecReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
unsigned InitSaveExecReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
// Don't bother using generic instructions/registers for the exec mask.
B.buildInstr(TargetOpcode::IMPLICIT_DEF)
.addDef(InitSaveExecReg);
unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
// To insert the loop we need to split the block. Move everything before this
// point to a new block, and insert a new empty block before this instruction.
MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
MachineBasicBlock *RestoreExecBB = MF->CreateMachineBasicBlock();
MachineFunction::iterator MBBI(MBB);
++MBBI;
MF->insert(MBBI, LoopBB);
MF->insert(MBBI, RestoreExecBB);
MF->insert(MBBI, RemainderBB);
LoopBB->addSuccessor(RestoreExecBB);
LoopBB->addSuccessor(LoopBB);
// Move the rest of the block into a new block.
RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
MBB.addSuccessor(LoopBB);
RestoreExecBB->addSuccessor(RemainderBB);
B.setInsertPt(*LoopBB, LoopBB->end());
B.buildInstr(TargetOpcode::PHI)
.addDef(PhiExec)
.addReg(InitSaveExecReg)
.addMBB(&MBB)
.addReg(NewExec)
.addMBB(LoopBB);
for (auto Result : zip(InitResultRegs, ResultRegs, PhiRegs)) {
B.buildInstr(TargetOpcode::G_PHI)
.addDef(std::get<2>(Result))
.addReg(std::get<0>(Result)) // Initial value / implicit_def
.addMBB(&MBB)
.addReg(std::get<1>(Result)) // Mid-loop value.
.addMBB(LoopBB);
}
// Move the instruction into the loop.
LoopBB->splice(LoopBB->end(), &MBB, I);
I = std::prev(LoopBB->end());
B.setInstr(*I);
unsigned CondReg = AMDGPU::NoRegister;
for (MachineOperand &Op : MI.uses()) {
if (!Op.isReg())
continue;
assert(!Op.isDef());
if (SGPROperandRegs.count(Op.getReg())) {
LLT OpTy = MRI.getType(Op.getReg());
unsigned OpSize = OpTy.getSizeInBits();
// Can only do a readlane of 32-bit pieces.
if (OpSize == 32) {
// Avoid extra copies in the simple case of one 32-bit register.
unsigned CurrentLaneOpReg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
MRI.setType(CurrentLaneOpReg, OpTy);
constrainGenericRegister(Op.getReg(), AMDGPU::VGPR_32RegClass, MRI);
// Read the next variant <- also loop target.
BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentLaneOpReg)
.addReg(Op.getReg());
unsigned NewCondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
bool First = CondReg == AMDGPU::NoRegister;
if (First)
CondReg = NewCondReg;
// Compare the just read M0 value to all possible Idx values.
B.buildInstr(AMDGPU::V_CMP_EQ_U32_e64)
.addDef(NewCondReg)
.addReg(CurrentLaneOpReg)
.addReg(Op.getReg());
Op.setReg(CurrentLaneOpReg);
if (!First) {
unsigned AndReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
// If there are multiple operands to consider, and the conditions.
B.buildInstr(AMDGPU::S_AND_B64)
.addDef(AndReg)
.addReg(NewCondReg)
.addReg(CondReg);
CondReg = AndReg;
}
} else {
LLT S32 = LLT::scalar(32);
SmallVector<unsigned, 8> ReadlanePieces;
// The compares can be done as 64-bit, but the extract needs to be done
// in 32-bit pieces.
bool Is64 = OpSize % 64 == 0;
LLT UnmergeTy = OpSize % 64 == 0 ? LLT::scalar(64) : LLT::scalar(32);
unsigned CmpOp = OpSize % 64 == 0 ? AMDGPU::V_CMP_EQ_U64_e64
: AMDGPU::V_CMP_EQ_U32_e64;
// The compares can be done as 64-bit, but the extract needs to be done
// in 32-bit pieces.
// Insert the unmerge before the loop.
B.setMBB(MBB);
auto Unmerge = B.buildUnmerge(UnmergeTy, Op.getReg());
B.setInstr(*I);
unsigned NumPieces = Unmerge->getNumOperands() - 1;
for (unsigned PieceIdx = 0; PieceIdx != NumPieces; ++PieceIdx) {
unsigned UnmergePiece = Unmerge.getReg(PieceIdx);
unsigned CurrentLaneOpReg;
if (Is64) {
unsigned CurrentLaneOpRegLo = MRI.createGenericVirtualRegister(S32);
unsigned CurrentLaneOpRegHi = MRI.createGenericVirtualRegister(S32);
MRI.setRegClass(UnmergePiece, &AMDGPU::VReg_64RegClass);
MRI.setRegClass(CurrentLaneOpRegLo, &AMDGPU::SReg_32_XM0RegClass);
MRI.setRegClass(CurrentLaneOpRegHi, &AMDGPU::SReg_32_XM0RegClass);
// Read the next variant <- also loop target.
BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
CurrentLaneOpRegLo)
.addReg(UnmergePiece, 0, AMDGPU::sub0);
// Read the next variant <- also loop target.
BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
CurrentLaneOpRegHi)
.addReg(UnmergePiece, 0, AMDGPU::sub1);
CurrentLaneOpReg =
B.buildMerge(LLT::scalar(64),
{CurrentLaneOpRegLo, CurrentLaneOpRegHi})
.getReg(0);
MRI.setRegClass(CurrentLaneOpReg, &AMDGPU::SReg_64_XEXECRegClass);
if (OpTy.getScalarSizeInBits() == 64) {
// If we need to produce a 64-bit element vector, so use the
// merged pieces
ReadlanePieces.push_back(CurrentLaneOpReg);
} else {
// 32-bit element type.
ReadlanePieces.push_back(CurrentLaneOpRegLo);
ReadlanePieces.push_back(CurrentLaneOpRegHi);
}
} else {
CurrentLaneOpReg = MRI.createGenericVirtualRegister(LLT::scalar(32));
MRI.setRegClass(UnmergePiece, &AMDGPU::VGPR_32RegClass);
MRI.setRegClass(CurrentLaneOpReg, &AMDGPU::SReg_32_XM0RegClass);
// Read the next variant <- also loop target.
BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32),
CurrentLaneOpReg)
.addReg(UnmergePiece);
ReadlanePieces.push_back(CurrentLaneOpReg);
}
unsigned NewCondReg
= MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
bool First = CondReg == AMDGPU::NoRegister;
if (First)
CondReg = NewCondReg;
B.buildInstr(CmpOp)
.addDef(NewCondReg)
.addReg(CurrentLaneOpReg)
.addReg(UnmergePiece);
if (!First) {
unsigned AndReg
= MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
// If there are multiple operands to consider, and the conditions.
B.buildInstr(AMDGPU::S_AND_B64)
.addDef(AndReg)
.addReg(NewCondReg)
.addReg(CondReg);
CondReg = AndReg;
}
}
// FIXME: Build merge seems to switch to CONCAT_VECTORS but not
// BUILD_VECTOR
if (OpTy.isVector()) {
auto Merge = B.buildBuildVector(OpTy, ReadlanePieces);
Op.setReg(Merge.getReg(0));
} else {
auto Merge = B.buildMerge(OpTy, ReadlanePieces);
Op.setReg(Merge.getReg(0));
}
MRI.setRegBank(Op.getReg(), getRegBank(AMDGPU::SGPRRegBankID));
}
}
}
B.setInsertPt(*LoopBB, LoopBB->end());
// Update EXEC, save the original EXEC value to VCC.
B.buildInstr(AMDGPU::S_AND_SAVEEXEC_B64)
.addDef(NewExec)
.addReg(CondReg, RegState::Kill);
MRI.setSimpleHint(NewExec, CondReg);
// Update EXEC, switch all done bits to 0 and all todo bits to 1.
B.buildInstr(AMDGPU::S_XOR_B64_term)
.addDef(AMDGPU::EXEC)
.addReg(AMDGPU::EXEC)
.addReg(NewExec);
// XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
// s_cbranch_scc0?
// Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
B.buildInstr(AMDGPU::S_CBRANCH_EXECNZ)
.addMBB(LoopBB);
// Save the EXEC mask before the loop.
BuildMI(MBB, MBB.end(), DL, TII->get(AMDGPU::S_MOV_B64_term), SaveExecReg)
.addReg(AMDGPU::EXEC);
// Restore the EXEC mask after the loop.
B.setMBB(*RestoreExecBB);
B.buildInstr(AMDGPU::S_MOV_B64_term)
.addDef(AMDGPU::EXEC)
.addReg(SaveExecReg);
}
void AMDGPURegisterBankInfo::applyMappingImpl(
const OperandsMapper &OpdMapper) const {
MachineInstr &MI = OpdMapper.getMI();
unsigned Opc = MI.getOpcode();
MachineRegisterInfo &MRI = OpdMapper.getMRI();
switch (Opc) {
case AMDGPU::G_SELECT: {
unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
if (DstTy.getSizeInBits() != 64)
break;
LLT HalfTy = getHalfSizedType(DstTy);
SmallVector<unsigned, 2> DefRegs(OpdMapper.getVRegs(0));
SmallVector<unsigned, 1> Src0Regs(OpdMapper.getVRegs(1));
SmallVector<unsigned, 2> Src1Regs(OpdMapper.getVRegs(2));
SmallVector<unsigned, 2> Src2Regs(OpdMapper.getVRegs(3));
// All inputs are SGPRs, nothing special to do.
if (DefRegs.empty()) {
assert(Src1Regs.empty() && Src2Regs.empty());
break;
}
MachineIRBuilder B(MI);
if (Src0Regs.empty())
Src0Regs.push_back(MI.getOperand(1).getReg());
else {
assert(Src0Regs.size() == 1);
}
if (Src1Regs.empty())
split64BitValueForMapping(B, Src1Regs, HalfTy, MI.getOperand(2).getReg());
else {
setRegsToType(MRI, Src1Regs, HalfTy);
}
if (Src2Regs.empty())
split64BitValueForMapping(B, Src2Regs, HalfTy, MI.getOperand(3).getReg());
else
setRegsToType(MRI, Src2Regs, HalfTy);
setRegsToType(MRI, DefRegs, HalfTy);
B.buildSelect(DefRegs[0], Src0Regs[0], Src1Regs[0], Src2Regs[0]);
B.buildSelect(DefRegs[1], Src0Regs[0], Src1Regs[1], Src2Regs[1]);
MRI.setRegBank(DstReg, getRegBank(AMDGPU::VGPRRegBankID));
MI.eraseFromParent();
return;
}
case AMDGPU::G_AND:
case AMDGPU::G_OR:
case AMDGPU::G_XOR: {
// 64-bit and is only available on the SALU, so split into 2 32-bit ops if
// there is a VGPR input.
unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
if (DstTy.getSizeInBits() != 64)
break;
LLT HalfTy = getHalfSizedType(DstTy);
SmallVector<unsigned, 2> DefRegs(OpdMapper.getVRegs(0));
SmallVector<unsigned, 2> Src0Regs(OpdMapper.getVRegs(1));
SmallVector<unsigned, 2> Src1Regs(OpdMapper.getVRegs(2));
// All inputs are SGPRs, nothing special to do.
if (DefRegs.empty()) {
assert(Src0Regs.empty() && Src1Regs.empty());
break;
}
assert(DefRegs.size() == 2);
assert(Src0Regs.size() == Src1Regs.size() &&
(Src0Regs.empty() || Src0Regs.size() == 2));
// Depending on where the source registers came from, the generic code may
// have decided to split the inputs already or not. If not, we still need to
// extract the values.
MachineIRBuilder B(MI);
if (Src0Regs.empty())
split64BitValueForMapping(B, Src0Regs, HalfTy, MI.getOperand(1).getReg());
else
setRegsToType(MRI, Src0Regs, HalfTy);
if (Src1Regs.empty())
split64BitValueForMapping(B, Src1Regs, HalfTy, MI.getOperand(2).getReg());
else
setRegsToType(MRI, Src1Regs, HalfTy);
setRegsToType(MRI, DefRegs, HalfTy);
B.buildInstr(Opc)
.addDef(DefRegs[0])
.addUse(Src0Regs[0])
.addUse(Src1Regs[0]);
B.buildInstr(Opc)
.addDef(DefRegs[1])
.addUse(Src0Regs[1])
.addUse(Src1Regs[1]);
MRI.setRegBank(DstReg, getRegBank(AMDGPU::VGPRRegBankID));
MI.eraseFromParent();
return;
}
case AMDGPU::G_EXTRACT_VECTOR_ELT:
applyDefaultMapping(OpdMapper);
executeInWaterfallLoop(MI, MRI, { 2 });
return;
case AMDGPU::G_INTRINSIC: {
switch (MI.getOperand(MI.getNumExplicitDefs()).getIntrinsicID()) {
case Intrinsic::amdgcn_s_buffer_load: {
// FIXME: Move to G_INTRINSIC_W_SIDE_EFFECTS
executeInWaterfallLoop(MI, MRI, { 2, 3 });
return;
}
default:
break;
}
break;
}
case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
switch (MI.getOperand(MI.getNumExplicitDefs()).getIntrinsicID()) {
case Intrinsic::amdgcn_buffer_load: {
executeInWaterfallLoop(MI, MRI, { 2 });
return;
}
default:
break;
}
break;
}
default:
break;
}
return applyDefaultMapping(OpdMapper);
}
static bool isInstrUniform(const MachineInstr &MI) {
if (!MI.hasOneMemOperand())
return false;
const MachineMemOperand *MMO = *MI.memoperands_begin();
return AMDGPUInstrInfo::isUniformMMO(MMO);
}
bool AMDGPURegisterBankInfo::isSALUMapping(const MachineInstr &MI) const {
const MachineFunction &MF = *MI.getParent()->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
for (unsigned i = 0, e = MI.getNumOperands();i != e; ++i) {
if (!MI.getOperand(i).isReg())
continue;
unsigned Reg = MI.getOperand(i).getReg();
if (const RegisterBank *Bank = getRegBank(Reg, MRI, *TRI)) {
if (Bank->getID() == AMDGPU::VGPRRegBankID)
return false;
assert(Bank->getID() == AMDGPU::SGPRRegBankID ||
Bank->getID() == AMDGPU::SCCRegBankID);
}
}
return true;
}
const RegisterBankInfo::InstructionMapping &
AMDGPURegisterBankInfo::getDefaultMappingSOP(const MachineInstr &MI) const {
const MachineFunction &MF = *MI.getParent()->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
SmallVector<const ValueMapping*, 8> OpdsMapping(MI.getNumOperands());
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
unsigned Size = getSizeInBits(MI.getOperand(i).getReg(), MRI, *TRI);
unsigned BankID = Size == 1 ? AMDGPU::SCCRegBankID : AMDGPU::SGPRRegBankID;
OpdsMapping[i] = AMDGPU::getValueMapping(BankID, Size);
}
return getInstructionMapping(1, 1, getOperandsMapping(OpdsMapping),
MI.getNumOperands());
}
const RegisterBankInfo::InstructionMapping &
AMDGPURegisterBankInfo::getDefaultMappingVOP(const MachineInstr &MI) const {
const MachineFunction &MF = *MI.getParent()->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
SmallVector<const ValueMapping*, 8> OpdsMapping(MI.getNumOperands());
unsigned OpdIdx = 0;
unsigned Size0 = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
OpdsMapping[OpdIdx++] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size0);
if (MI.getOperand(OpdIdx).isIntrinsicID())
OpdsMapping[OpdIdx++] = nullptr;
unsigned Reg1 = MI.getOperand(OpdIdx).getReg();
unsigned Size1 = getSizeInBits(Reg1, MRI, *TRI);
unsigned DefaultBankID = Size1 == 1 ?
AMDGPU::VCCRegBankID : AMDGPU::VGPRRegBankID;
unsigned Bank1 = getRegBankID(Reg1, MRI, *TRI, DefaultBankID);
OpdsMapping[OpdIdx++] = AMDGPU::getValueMapping(Bank1, Size1);
for (unsigned e = MI.getNumOperands(); OpdIdx != e; ++OpdIdx) {
const MachineOperand &MO = MI.getOperand(OpdIdx);
if (!MO.isReg())
continue;
unsigned Size = getSizeInBits(MO.getReg(), MRI, *TRI);
unsigned BankID = Size == 1 ? AMDGPU::VCCRegBankID : AMDGPU::VGPRRegBankID;
OpdsMapping[OpdIdx] = AMDGPU::getValueMapping(BankID, Size);
}
return getInstructionMapping(1, 1, getOperandsMapping(OpdsMapping),
MI.getNumOperands());
}
const RegisterBankInfo::InstructionMapping &
AMDGPURegisterBankInfo::getDefaultMappingAllVGPR(const MachineInstr &MI) const {
const MachineFunction &MF = *MI.getParent()->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
SmallVector<const ValueMapping*, 8> OpdsMapping(MI.getNumOperands());
for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
unsigned Size = getSizeInBits(MI.getOperand(I).getReg(), MRI, *TRI);
OpdsMapping[I] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size);
}
return getInstructionMapping(1, 1, getOperandsMapping(OpdsMapping),
MI.getNumOperands());
}
const RegisterBankInfo::InstructionMapping &
AMDGPURegisterBankInfo::getInstrMappingForLoad(const MachineInstr &MI) const {
const MachineFunction &MF = *MI.getParent()->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
SmallVector<const ValueMapping*, 8> OpdsMapping(MI.getNumOperands());
unsigned Size = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
unsigned PtrSize = getSizeInBits(MI.getOperand(1).getReg(), MRI, *TRI);
const ValueMapping *ValMapping;
const ValueMapping *PtrMapping;
if (isInstrUniform(MI)) {
// We have a uniform instruction so we want to use an SMRD load
ValMapping = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size);
PtrMapping = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, PtrSize);
} else {
ValMapping = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size);
// FIXME: What would happen if we used SGPRRegBankID here?
PtrMapping = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, PtrSize);
}
OpdsMapping[0] = ValMapping;
OpdsMapping[1] = PtrMapping;
const RegisterBankInfo::InstructionMapping &Mapping = getInstructionMapping(
1, 1, getOperandsMapping(OpdsMapping), MI.getNumOperands());
return Mapping;
// FIXME: Do we want to add a mapping for FLAT load, or should we just
// handle that during instruction selection?
}
unsigned
AMDGPURegisterBankInfo::getRegBankID(unsigned Reg,
const MachineRegisterInfo &MRI,
const TargetRegisterInfo &TRI,
unsigned Default) const {
const RegisterBank *Bank = getRegBank(Reg, MRI, TRI);
return Bank ? Bank->getID() : Default;
}
///
/// This function must return a legal mapping, because
/// AMDGPURegisterBankInfo::getInstrAlternativeMappings() is not called
/// in RegBankSelect::Mode::Fast. Any mapping that would cause a
/// VGPR to SGPR generated is illegal.
///
const RegisterBankInfo::InstructionMapping &
AMDGPURegisterBankInfo::getInstrMapping(const MachineInstr &MI) const {
const MachineFunction &MF = *MI.getParent()->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
if (MI.isRegSequence()) {
// If any input is a VGPR, the result must be a VGPR. The default handling
// assumes any copy between banks is legal.
unsigned BankID = AMDGPU::SGPRRegBankID;
for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
auto OpBank = getRegBankID(MI.getOperand(I).getReg(), MRI, *TRI);
// It doesn't make sense to use vcc or scc banks here, so just ignore
// them.
if (OpBank != AMDGPU::SGPRRegBankID) {
BankID = AMDGPU::VGPRRegBankID;
break;
}
}
unsigned Size = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
const ValueMapping &ValMap = getValueMapping(0, Size, getRegBank(BankID));
return getInstructionMapping(
1, /*Cost*/ 1,
/*OperandsMapping*/ getOperandsMapping({&ValMap}), 1);
}
// The default handling is broken and doesn't handle illegal SGPR->VGPR copies
// properly.
//
// TODO: There are additional exec masking dependencies to analyze.
if (MI.getOpcode() == TargetOpcode::G_PHI) {
// TODO: Generate proper invalid bank enum.
int ResultBank = -1;
for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
unsigned Reg = MI.getOperand(I).getReg();
const RegisterBank *Bank = getRegBank(Reg, MRI, *TRI);
// FIXME: Assuming VGPR for any undetermined inputs.
if (!Bank || Bank->getID() == AMDGPU::VGPRRegBankID) {
ResultBank = AMDGPU::VGPRRegBankID;
break;
}
unsigned OpBank = Bank->getID();
// scc, scc -> sgpr
if (OpBank == AMDGPU::SCCRegBankID) {
// There's only one SCC register, so a phi requires copying to SGPR.
OpBank = AMDGPU::SGPRRegBankID;
} else if (OpBank == AMDGPU::VCCRegBankID) {
// vcc, vcc -> vcc
// vcc, sgpr -> vgpr
if (ResultBank != -1 && ResultBank != AMDGPU::VCCRegBankID) {
ResultBank = AMDGPU::VGPRRegBankID;
break;
}
}
ResultBank = OpBank;
}
assert(ResultBank != -1);
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
const ValueMapping &ValMap =
getValueMapping(0, Size, getRegBank(ResultBank));
return getInstructionMapping(
1, /*Cost*/ 1,
/*OperandsMapping*/ getOperandsMapping({&ValMap}), 1);
}
const RegisterBankInfo::InstructionMapping &Mapping = getInstrMappingImpl(MI);
if (Mapping.isValid())
return Mapping;
SmallVector<const ValueMapping*, 8> OpdsMapping(MI.getNumOperands());
switch (MI.getOpcode()) {
default:
return getInvalidInstructionMapping();
case AMDGPU::G_AND:
case AMDGPU::G_OR:
case AMDGPU::G_XOR: {
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
if (Size == 1) {
OpdsMapping[0] = OpdsMapping[1] =
OpdsMapping[2] = AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, Size);
break;
}
if (Size == 64) {
if (isSALUMapping(MI)) {
OpdsMapping[0] = getValueMappingSGPR64Only(AMDGPU::SGPRRegBankID, Size);
OpdsMapping[1] = OpdsMapping[2] = OpdsMapping[0];
} else {
OpdsMapping[0] = getValueMappingSGPR64Only(AMDGPU::VGPRRegBankID, Size);
unsigned Bank1 = getRegBankID(MI.getOperand(1).getReg(), MRI, *TRI/*, DefaultBankID*/);
OpdsMapping[1] = AMDGPU::getValueMapping(Bank1, Size);
unsigned Bank2 = getRegBankID(MI.getOperand(2).getReg(), MRI, *TRI/*, DefaultBankID*/);
OpdsMapping[2] = AMDGPU::getValueMapping(Bank2, Size);
}
break;
}
LLVM_FALLTHROUGH;
}
case AMDGPU::G_GEP:
case AMDGPU::G_ADD:
case AMDGPU::G_SUB:
case AMDGPU::G_MUL:
case AMDGPU::G_SHL:
case AMDGPU::G_LSHR:
case AMDGPU::G_ASHR:
case AMDGPU::G_UADDO:
case AMDGPU::G_SADDO:
case AMDGPU::G_USUBO:
case AMDGPU::G_SSUBO:
case AMDGPU::G_UADDE:
case AMDGPU::G_SADDE:
case AMDGPU::G_USUBE:
case AMDGPU::G_SSUBE:
case AMDGPU::G_UMULH:
case AMDGPU::G_SMULH:
if (isSALUMapping(MI))
return getDefaultMappingSOP(MI);
LLVM_FALLTHROUGH;
case AMDGPU::G_SMIN:
case AMDGPU::G_SMAX:
case AMDGPU::G_UMIN:
case AMDGPU::G_UMAX:
// TODO: min/max can be scalar, but requires expanding as a compare and
// select.
case AMDGPU::G_FADD:
case AMDGPU::G_FSUB:
case AMDGPU::G_FPTOSI:
case AMDGPU::G_FPTOUI:
case AMDGPU::G_FMUL:
case AMDGPU::G_FMA:
case AMDGPU::G_FSQRT:
case AMDGPU::G_SITOFP:
case AMDGPU::G_UITOFP:
case AMDGPU::G_FPTRUNC:
case AMDGPU::G_FPEXT:
case AMDGPU::G_FEXP2:
case AMDGPU::G_FLOG2:
case AMDGPU::G_INTRINSIC_TRUNC:
case AMDGPU::G_INTRINSIC_ROUND:
return getDefaultMappingVOP(MI);
case AMDGPU::G_IMPLICIT_DEF: {
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
OpdsMapping[0] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size);
break;
}
case AMDGPU::G_FCONSTANT:
case AMDGPU::G_CONSTANT:
case AMDGPU::G_FRAME_INDEX:
case AMDGPU::G_BLOCK_ADDR: {
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
OpdsMapping[0] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size);
break;
}
case AMDGPU::G_INSERT: {
unsigned BankID = isSALUMapping(MI) ? AMDGPU::SGPRRegBankID :
AMDGPU::VGPRRegBankID;
unsigned DstSize = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
unsigned SrcSize = getSizeInBits(MI.getOperand(1).getReg(), MRI, *TRI);
unsigned EltSize = getSizeInBits(MI.getOperand(2).getReg(), MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(BankID, DstSize);
OpdsMapping[1] = AMDGPU::getValueMapping(BankID, SrcSize);
OpdsMapping[2] = AMDGPU::getValueMapping(BankID, EltSize);
OpdsMapping[3] = nullptr;
break;
}
case AMDGPU::G_EXTRACT: {
unsigned BankID = getRegBankID(MI.getOperand(1).getReg(), MRI, *TRI);
unsigned DstSize = getSizeInBits(MI.getOperand(0).getReg(), MRI, *TRI);
unsigned SrcSize = getSizeInBits(MI.getOperand(1).getReg(), MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(BankID, DstSize);
OpdsMapping[1] = AMDGPU::getValueMapping(BankID, SrcSize);
OpdsMapping[2] = nullptr;
break;
}
case AMDGPU::G_MERGE_VALUES: {
unsigned Bank = isSALUMapping(MI) ?
AMDGPU::SGPRRegBankID : AMDGPU::VGPRRegBankID;
unsigned DstSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
unsigned SrcSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
OpdsMapping[0] = AMDGPU::getValueMapping(Bank, DstSize);
// Op1 and Dst should use the same register bank.
for (unsigned i = 1, e = MI.getNumOperands(); i != e; ++i)
OpdsMapping[i] = AMDGPU::getValueMapping(Bank, SrcSize);
break;
}
case AMDGPU::G_BITCAST:
case AMDGPU::G_INTTOPTR:
case AMDGPU::G_PTRTOINT:
case AMDGPU::G_CTLZ:
case AMDGPU::G_CTLZ_ZERO_UNDEF:
case AMDGPU::G_CTTZ:
case AMDGPU::G_CTTZ_ZERO_UNDEF:
case AMDGPU::G_CTPOP:
case AMDGPU::G_BSWAP:
case AMDGPU::G_FABS:
case AMDGPU::G_FNEG: {
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
unsigned BankID = getRegBankID(MI.getOperand(1).getReg(), MRI, *TRI);
OpdsMapping[0] = OpdsMapping[1] = AMDGPU::getValueMapping(BankID, Size);
break;
}
case AMDGPU::G_TRUNC: {
unsigned Dst = MI.getOperand(0).getReg();
unsigned Src = MI.getOperand(1).getReg();
unsigned Bank = getRegBankID(Src, MRI, *TRI);
unsigned DstSize = getSizeInBits(Dst, MRI, *TRI);
unsigned SrcSize = getSizeInBits(Src, MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(Bank, DstSize);
OpdsMapping[1] = AMDGPU::getValueMapping(Bank, SrcSize);
break;
}
case AMDGPU::G_ZEXT:
case AMDGPU::G_SEXT:
case AMDGPU::G_ANYEXT: {
unsigned Dst = MI.getOperand(0).getReg();
unsigned Src = MI.getOperand(1).getReg();
unsigned DstSize = getSizeInBits(Dst, MRI, *TRI);
unsigned SrcSize = getSizeInBits(Src, MRI, *TRI);
unsigned SrcBank = getRegBankID(Src, MRI, *TRI,
SrcSize == 1 ? AMDGPU::SGPRRegBankID :
AMDGPU::VGPRRegBankID);
unsigned DstBank = SrcBank;
if (SrcSize == 1) {
if (SrcBank == AMDGPU::SGPRRegBankID)
DstBank = AMDGPU::VGPRRegBankID;
else
DstBank = AMDGPU::SGPRRegBankID;
}
OpdsMapping[0] = AMDGPU::getValueMapping(DstBank, DstSize);
OpdsMapping[1] = AMDGPU::getValueMapping(SrcBank, SrcSize);
break;
}
case AMDGPU::G_FCMP: {
unsigned Size = MRI.getType(MI.getOperand(2).getReg()).getSizeInBits();
unsigned Op2Bank = getRegBankID(MI.getOperand(2).getReg(), MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, 1);
OpdsMapping[1] = nullptr; // Predicate Operand.
OpdsMapping[2] = AMDGPU::getValueMapping(Op2Bank, Size);
OpdsMapping[3] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size);
break;
}
case AMDGPU::G_STORE: {
assert(MI.getOperand(0).isReg());
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
// FIXME: We need to specify a different reg bank once scalar stores
// are supported.
const ValueMapping *ValMapping =
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size);
// FIXME: Depending on the type of store, the pointer could be in
// the SGPR Reg bank.
// FIXME: Pointer size should be based on the address space.
const ValueMapping *PtrMapping =
AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 64);
OpdsMapping[0] = ValMapping;
OpdsMapping[1] = PtrMapping;
break;
}
case AMDGPU::G_ICMP: {
unsigned Size = MRI.getType(MI.getOperand(2).getReg()).getSizeInBits();
unsigned Op2Bank = getRegBankID(MI.getOperand(2).getReg(), MRI, *TRI);
unsigned Op3Bank = getRegBankID(MI.getOperand(3).getReg(), MRI, *TRI);
unsigned Op0Bank = Op2Bank == AMDGPU::SGPRRegBankID &&
Op3Bank == AMDGPU::SGPRRegBankID ?
AMDGPU::SCCRegBankID : AMDGPU::VCCRegBankID;
OpdsMapping[0] = AMDGPU::getValueMapping(Op0Bank, 1);
OpdsMapping[1] = nullptr; // Predicate Operand.
OpdsMapping[2] = AMDGPU::getValueMapping(Op2Bank, Size);
OpdsMapping[3] = AMDGPU::getValueMapping(Op3Bank, Size);
break;
}
case AMDGPU::G_EXTRACT_VECTOR_ELT: {
unsigned OutputBankID = isSALUMapping(MI) ?
AMDGPU::SGPRRegBankID : AMDGPU::VGPRRegBankID;
unsigned SrcSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
unsigned IdxSize = MRI.getType(MI.getOperand(2).getReg()).getSizeInBits();
unsigned IdxBank = getRegBankID(MI.getOperand(2).getReg(), MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(OutputBankID, SrcSize);
OpdsMapping[1] = AMDGPU::getValueMapping(OutputBankID, SrcSize);
// The index can be either if the source vector is VGPR.
OpdsMapping[2] = AMDGPU::getValueMapping(IdxBank, IdxSize);
break;
}
case AMDGPU::G_INSERT_VECTOR_ELT: {
unsigned OutputBankID = isSALUMapping(MI) ?
AMDGPU::SGPRRegBankID : AMDGPU::VGPRRegBankID;
unsigned VecSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
unsigned InsertSize = MRI.getType(MI.getOperand(2).getReg()).getSizeInBits();
unsigned IdxSize = MRI.getType(MI.getOperand(3).getReg()).getSizeInBits();
unsigned InsertEltBank = getRegBankID(MI.getOperand(2).getReg(), MRI, *TRI);
unsigned IdxBank = getRegBankID(MI.getOperand(3).getReg(), MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(OutputBankID, VecSize);
OpdsMapping[1] = AMDGPU::getValueMapping(OutputBankID, VecSize);
OpdsMapping[2] = AMDGPU::getValueMapping(InsertEltBank, InsertSize);
// The index can be either if the source vector is VGPR.
OpdsMapping[3] = AMDGPU::getValueMapping(IdxBank, IdxSize);
break;
}
case AMDGPU::G_UNMERGE_VALUES: {
unsigned Bank = isSALUMapping(MI) ? AMDGPU::SGPRRegBankID :
AMDGPU::VGPRRegBankID;
// Op1 and Dst should use the same register bank.
// FIXME: Shouldn't this be the default? Why do we need to handle this?
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
unsigned Size = getSizeInBits(MI.getOperand(i).getReg(), MRI, *TRI);
OpdsMapping[i] = AMDGPU::getValueMapping(Bank, Size);
}
break;
}
case AMDGPU::G_INTRINSIC: {
switch (MI.getOperand(MI.getNumExplicitDefs()).getIntrinsicID()) {
default:
return getInvalidInstructionMapping();
case Intrinsic::maxnum:
case Intrinsic::minnum:
case Intrinsic::amdgcn_cvt_pkrtz:
return getDefaultMappingVOP(MI);
case Intrinsic::amdgcn_kernarg_segment_ptr: {
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
OpdsMapping[0] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size);
break;
}
case Intrinsic::amdgcn_wqm_vote: {
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
OpdsMapping[0] = OpdsMapping[2]
= AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size);
break;
}
case Intrinsic::amdgcn_s_buffer_load: {
// FIXME: This should be moved to G_INTRINSIC_W_SIDE_EFFECTS
unsigned RSrc = MI.getOperand(2).getReg(); // SGPR
unsigned Offset = MI.getOperand(3).getReg(); // SGPR/imm
unsigned Size0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
unsigned Size2 = MRI.getType(RSrc).getSizeInBits();
unsigned Size3 = MRI.getType(Offset).getSizeInBits();
unsigned RSrcBank = getRegBankID(RSrc, MRI, *TRI);
unsigned OffsetBank = getRegBankID(Offset, MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, Size0);
OpdsMapping[1] = nullptr; // intrinsic id
// Lie and claim everything is legal, even though some need to be
// SGPRs. applyMapping will have to deal with it as a waterfall loop.
OpdsMapping[2] = AMDGPU::getValueMapping(RSrcBank, Size2); // rsrc
OpdsMapping[3] = AMDGPU::getValueMapping(OffsetBank, Size3);
OpdsMapping[4] = nullptr;
break;
}
case Intrinsic::amdgcn_div_scale: {
unsigned Dst0Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
unsigned Dst1Size = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
OpdsMapping[0] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Dst0Size);
OpdsMapping[1] = AMDGPU::getValueMapping(AMDGPU::VCCRegBankID, Dst1Size);
unsigned SrcSize = MRI.getType(MI.getOperand(3).getReg()).getSizeInBits();
OpdsMapping[3] = AMDGPU::getValueMapping(
getRegBankID(MI.getOperand(3).getReg(), MRI, *TRI), SrcSize);
OpdsMapping[4] = AMDGPU::getValueMapping(
getRegBankID(MI.getOperand(4).getReg(), MRI, *TRI), SrcSize);
break;
}
}
break;
}
case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
switch (MI.getOperand(MI.getNumExplicitDefs()).getIntrinsicID()) {
default:
return getInvalidInstructionMapping();
case Intrinsic::amdgcn_exp_compr:
OpdsMapping[0] = nullptr; // IntrinsicID
// FIXME: These are immediate values which can't be read from registers.
OpdsMapping[1] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
OpdsMapping[2] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
// FIXME: Could we support packed types here?
OpdsMapping[3] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 32);
OpdsMapping[4] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 32);
// FIXME: These are immediate values which can't be read from registers.
OpdsMapping[5] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
OpdsMapping[6] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
break;
case Intrinsic::amdgcn_exp:
OpdsMapping[0] = nullptr; // IntrinsicID
// FIXME: These are immediate values which can't be read from registers.
OpdsMapping[1] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
OpdsMapping[2] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
// FIXME: Could we support packed types here?
OpdsMapping[3] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 32);
OpdsMapping[4] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 32);
OpdsMapping[5] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 32);
OpdsMapping[6] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, 32);
// FIXME: These are immediate values which can't be read from registers.
OpdsMapping[7] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
OpdsMapping[8] = AMDGPU::getValueMapping(AMDGPU::SGPRRegBankID, 32);
break;
case Intrinsic::amdgcn_buffer_load: {
unsigned RSrc = MI.getOperand(2).getReg(); // SGPR
unsigned VIndex = MI.getOperand(3).getReg(); // VGPR
unsigned Offset = MI.getOperand(4).getReg(); // SGPR/VGPR/imm
unsigned Size0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
unsigned Size2 = MRI.getType(RSrc).getSizeInBits();
unsigned Size3 = MRI.getType(VIndex).getSizeInBits();
unsigned Size4 = MRI.getType(Offset).getSizeInBits();
unsigned RSrcBank = getRegBankID(RSrc, MRI, *TRI);
unsigned OffsetBank = getRegBankID(Offset, MRI, *TRI);
OpdsMapping[0] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size0);
OpdsMapping[1] = nullptr; // intrinsic id
// Lie and claim everything is legal, even though some need to be
// SGPRs. applyMapping will have to deal with it as a waterfall loop.
OpdsMapping[2] = AMDGPU::getValueMapping(RSrcBank, Size2); // rsrc
OpdsMapping[3] = AMDGPU::getValueMapping(AMDGPU::VGPRRegBankID, Size3);
OpdsMapping[4] = AMDGPU::getValueMapping(OffsetBank, Size4);
OpdsMapping[5] = nullptr;
OpdsMapping[6] = nullptr;
break;
}
}
break;
}
case AMDGPU::G_SELECT: {
unsigned Size = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
unsigned Op1Bank = getRegBankID(MI.getOperand(1).getReg(), MRI, *TRI,
AMDGPU::SGPRRegBankID);
unsigned Op2Bank = getRegBankID(MI.getOperand(2).getReg(), MRI, *TRI);
unsigned Op3Bank = getRegBankID(MI.getOperand(3).getReg(), MRI, *TRI);
bool SGPRSrcs = Op1Bank == AMDGPU::SCCRegBankID &&
Op2Bank == AMDGPU::SGPRRegBankID &&
Op3Bank == AMDGPU::SGPRRegBankID;
unsigned Bank = SGPRSrcs ? AMDGPU::SGPRRegBankID : AMDGPU::VGPRRegBankID;
Op1Bank = SGPRSrcs ? AMDGPU::SCCRegBankID : AMDGPU::VCCRegBankID;
if (Size == 64) {
OpdsMapping[0] = AMDGPU::getValueMappingSGPR64Only(Bank, Size);
OpdsMapping[1] = AMDGPU::getValueMapping(Op1Bank, 1);
OpdsMapping[2] = AMDGPU::getValueMappingSGPR64Only(Bank, Size);
OpdsMapping[3] = AMDGPU::getValueMappingSGPR64Only(Bank, Size);
} else {
OpdsMapping[0] = AMDGPU::getValueMapping(Bank, Size);
OpdsMapping[1] = AMDGPU::getValueMapping(Op1Bank, 1);
OpdsMapping[2] = AMDGPU::getValueMapping(Bank, Size);
OpdsMapping[3] = AMDGPU::getValueMapping(Bank, Size);
}
break;
}
case AMDGPU::G_LOAD:
return getInstrMappingForLoad(MI);
case AMDGPU::G_ATOMICRMW_XCHG:
case AMDGPU::G_ATOMICRMW_ADD:
case AMDGPU::G_ATOMICRMW_SUB:
case AMDGPU::G_ATOMICRMW_AND:
case AMDGPU::G_ATOMICRMW_OR:
case AMDGPU::G_ATOMICRMW_XOR:
case AMDGPU::G_ATOMICRMW_MAX:
case AMDGPU::G_ATOMICRMW_MIN:
case AMDGPU::G_ATOMICRMW_UMAX:
case AMDGPU::G_ATOMICRMW_UMIN:
case AMDGPU::G_ATOMIC_CMPXCHG: {
return getDefaultMappingAllVGPR(MI);
}
case AMDGPU::G_BRCOND: {
unsigned Bank = getRegBankID(MI.getOperand(0).getReg(), MRI, *TRI,
AMDGPU::SGPRRegBankID);
assert(MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() == 1);
if (Bank != AMDGPU::SCCRegBankID)
Bank = AMDGPU::VCCRegBankID;
OpdsMapping[0] = AMDGPU::getValueMapping(Bank, 1);
break;
}
}
return getInstructionMapping(/*ID*/1, /*Cost*/1,
getOperandsMapping(OpdsMapping),
MI.getNumOperands());
}
| 24,528 |
2,592 | <gh_stars>1000+
import os.path
import logging
try:
from pkg_resources import resource_exists, resource_stream
except ImportError:
def resource_exists(*args, **kwargs):
return False
def resource_stream(*args, **kwargs):
return None
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger('glad.files')
def open_local(name, *args, **kwargs):
# use pkg_resources when available, makes it work in zipped modules
# or other environments
if resource_exists(__name__, name):
logger.info('opening \'%s\' from packaged resource', name)
return resource_stream(__name__, name)
# fallback to filesystem
logger.info('opening \'%s\' from packaged path', name)
local_path = os.path.normpath(os.path.join(BASE_PATH, os.path.join(name)))
if not local_path.startswith(BASE_PATH):
raise ValueError
return open(local_path, *args, **kwargs)
| 348 |
488 | <reponame>maurizioabba/rose
// t0480.cc
// expanding on t0478.cc and t0479.cc, trying to exercise various
// possibilities for rewriting -> dependind on templateness and
// presence of operator->
struct A {
int x;
};
struct B {
A* operator->();
};
struct C {
B operator-> ();
};
template <class T>
struct D {
T operator-> ();
};
// ------------------------
// not dependent, no operator ->
template <class T>
int f1(T t, A *a)
{
return a->x;
}
// instantiation
template int f1(int, A*);
// ------------------------
// dependent
template <class T>
int f2(T t)
{
return t->x;
}
// instantiate it such that operator -> is not used
template int f2(A *t);
// instantiate, and *do* use operator ->
template int f2(B t);
// instantiate and use operator-> twice
template int f2(C t);
// ------------------------
// more complicated
template <class T>
int f3(D<T> d)
{
return d->x;
}
template int f3(D<A*> d);
template int f3(D<B> d);
template int f3(D<C> d);
| 348 |
403 | package com.codedisaster.steamworks;
public class SteamControllerDigitalActionHandle extends SteamNativeHandle {
SteamControllerDigitalActionHandle(long handle) {
super(handle);
}
}
| 50 |
310 | {
"name": "Outlets To Go 300 Travel",
"description": "A universal AC power adapter with USB ports.",
"url": "http://www.monsterproducts.com/productdisplay.asp?pin=6592"
} | 56 |
310 | <filename>gear/hardware/v/veo-2-am-264tr.json
{
"name": "VEO 2 AM-264TR",
"description": "A portable monopod.",
"url": "https://www.vanguardworld.us/photo_video_us/veo-2-am-264tr.html"
}
| 85 |
353 | #include <ntw/info/memory.hpp>
#include <ntw/ob/process.hpp>
#define CATCH_CONFIG_MAIN
#define WIN32_NO_STATUS
#include <catch2/catch.hpp>
#pragma comment(lib, "ntdll.lib")
TEST_CASE("enumerating memory::basic_info")
{
std::size_t iterations = 0;
auto mem = ntw::ob::process_ref{}.query_mem<ntw::memory::basic_info>(0ull);
while(true) {
REQUIRE((mem || iterations > 16));
if(!mem)
break;
++iterations;
mem = ntw::ob::process_ref{}.query_mem<ntw::memory::basic_info>(mem->end());
}
} | 257 |
487 | /*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _FRONTENDS_P4_INLINING_H_
#define _FRONTENDS_P4_INLINING_H_
#include "lib/ordered_map.h"
#include "ir/ir.h"
#include "frontends/common/resolveReferences/referenceMap.h"
#include "frontends/p4/typeChecking/typeChecker.h"
#include "frontends/p4/evaluator/evaluator.h"
#include "frontends/p4/evaluator/substituteParameters.h"
#include "frontends/p4/unusedDeclarations.h"
#include "commonInlining.h"
// These are various data structures needed by the parser/parser and control/control inliners.
// This only works correctly after local variable initializers have been removed,
// and after the SideEffectOrdering pass has been executed.
namespace P4 {
/// Describes information about a caller-callee pair
struct CallInfo : public IHasDbPrint {
const IR::IContainer* caller;
const IR::IContainer* callee;
const IR::Declaration_Instance* instantiation; // callee instantiation
// Each instantiation may be invoked multiple times.
std::set<const IR::MethodCallStatement*> invocations; // all invocations within the caller
CallInfo(const IR::IContainer* caller, const IR::IContainer* callee,
const IR::Declaration_Instance* instantiation) :
caller(caller), callee(callee), instantiation(instantiation)
{ CHECK_NULL(caller); CHECK_NULL(callee); CHECK_NULL(instantiation); }
void addInvocation(const IR::MethodCallStatement* statement)
{ invocations.emplace(statement); }
void dbprint(std::ostream& out) const
{ out << "Inline " << callee << " into " << caller <<
" with " << invocations.size() << " invocations"; }
};
class SymRenameMap {
std::map<const IR::IDeclaration*, cstring> internalName;
std::map<const IR::IDeclaration*, cstring> externalName;
public:
void setNewName(const IR::IDeclaration* decl, cstring name, cstring extName) {
CHECK_NULL(decl);
BUG_CHECK(!name.isNullOrEmpty() && !extName.isNullOrEmpty(), "Empty name");
LOG3("setNewName " << dbp(decl) << " to " << name);
if (internalName.find(decl) != internalName.end())
BUG("%1%: already renamed", decl);
internalName.emplace(decl, name);
externalName.emplace(decl, extName);
}
cstring getName(const IR::IDeclaration* decl) const {
CHECK_NULL(decl);
BUG_CHECK(internalName.find(decl) != internalName.end(), "%1%: no new name", decl);
auto result = ::get(internalName, decl);
return result;
}
cstring getExtName(const IR::IDeclaration* decl) const {
CHECK_NULL(decl);
BUG_CHECK(externalName.find(decl) != externalName.end(), "%1%: no external name", decl);
auto result = ::get(externalName, decl);
return result;
}
bool isRenamed(const IR::IDeclaration* decl) const {
CHECK_NULL(decl);
return internalName.find(decl) != internalName.end();
}
};
struct PerInstanceSubstitutions {
ParameterSubstitution paramSubst;
TypeVariableSubstitution tvs;
SymRenameMap renameMap;
PerInstanceSubstitutions() = default;
PerInstanceSubstitutions(const PerInstanceSubstitutions &other) :
paramSubst(other.paramSubst),
tvs(other.tvs),
renameMap(other.renameMap) {}
template<class T>
const T* rename(ReferenceMap* refMap, const IR::Node* node);
};
/// Summarizes all inline operations to be performed.
struct InlineSummary : public IHasDbPrint {
/// Various substitutions that must be applied for each instance
struct PerCaller { // information for each caller
/**
* Pair identifying all the invocations of the subparser which can use the same
* inlined states because the path after returning from the subparser is identical
* for all such invocations.
*
* Invocations are characterized by:
* - Pointer to the apply method call statement (comparing apply method call statement
* ensures that the same instance is invoked and same arguments are passed to the call)
* - Pointer to the transition statement expression which has to be the name of
* the state (select expression is not allowed)
*
* Additional conditions which need to be met:
* - there is no other statement between the invocation of the subparser and
* the transition statement
* - transition statement has to be the name of the state (select expression is
* not allowed)
*
* @attention
* Note that local variables declared in states calling subparser and passed to
* the subparser as arguments need to be eliminated before Inline pass.
* Currently this condition is met as passes UniqueNames and MoveDeclarations are
* called before Inline pass in FrontEnd.
* Otherwise (if this condition was not met) there could be different variables
* with the same names passed as arguments to the apply method and additional
* checks would have to be introduced to avoid optimization in such case.
*
* @see field invocationToState
*/
typedef std::pair<const IR::MethodCallStatement*,
const IR::PathExpression*> InlinedInvocationInfo;
/**
* Hash for InlinedInvocationInfo used as a key for unordered_map
*
* @see field invocationToState
*/
struct key_hash {
std::size_t operator() (const InlinedInvocationInfo &k) const {
std::ostringstream oss;
std::get<0>(k)->dbprint(oss);
std::get<1>(k)->dbprint(oss);
return std::hash<std::string>{}(oss.str());
}
};
/**
* Binary equality predicate for InlinedInvocationInfo used as a key for unordered_map
*
* @see field invocationToState
*/
struct key_equal {
bool operator() (const InlinedInvocationInfo &v0,
const InlinedInvocationInfo &v1) const {
return std::get<0>(v0)->equiv(*std::get<0>(v1)) &&
std::get<1>(v0)->equiv(*std::get<1>(v1));
}
};
/// For each instance (key) the container that is intantiated.
std::map<const IR::Declaration_Instance*, const IR::IContainer*> declToCallee;
/// For each instance (key) we must apply a bunch of substitutions
std::map<const IR::Declaration_Instance*, PerInstanceSubstitutions*> substitutions;
/// For each invocation (key) call the instance that is invoked.
std::map<const IR::MethodCallStatement*, const IR::Declaration_Instance*> callToInstance;
/**
* For each distinct invocation of the subparser identified by InlinedInvocationInfo
* we store the ID of the next caller parser state which is a new state replacing
* the start state of the callee parser (subparser).
* Transition to this state is used in case there is another subparser invocation
* which has the equivalent InlinedInvocationInfo.
*
* Subparser invocations are considered to be equivalent when following conditions
* are met (which means that the path in the parse graph is the same after returning
* from subparser call):
* - apply method call statements of the invocations are equivalent (which means that
* the same subparser instance is invoked and the same arguments are passed to
* the apply method)
* - there is no statement between apply method call statement and transition statement
* - transition statement is a name of the state (not a select expression)
* - name of the state in transition statement is the same
*
*
* Example of the optimization
*
* Parser and subparser before Inline pass:
* @code{.p4}
* parser Subparser(packet_in packet, inout data_t hdr) {
* state start {
* hdr.f = 8w42;
* transition accept;
* }
* }
* parser ParserImpl(packet_in packet, out headers hdr, inout metadata meta,
* inout standard_metadata_t standard_metadata) {
* @name("p") Subparser() p_0;
* state start {
* transition select(standard_metadata.ingress_port) {
* 9w0: p0;
* default: p1;
* }
* }
* state p0 {
* p_0.apply(packet, hdr.h1);
* transition accept;
* }
* state p1 {
* p_0.apply(packet, hdr.h1);
* transition accept;
* }
* }
* @endcode
*
* Parser after Inline pass without optimization:
* @code{.p4}
* parser ParserImpl(packet_in packet, out headers hdr, inout metadata meta, inout standard_metadata_t standard_metadata) {
* state start {
* transition select(standard_metadata.ingress_port) {
* 9w0: p0;
* default: p1;
* }
* }
* state p0 {
* transition Subparser_start;
* }
* state Subparser_start {
* hdr.h1.f = 8w42;
* transition p0_0;
* }
* state p0_0 {
* transition accept;
* }
* state p1 {
* transition Subparser_start_0;
* }
* state Subparser_start_0 {
* hdr.h1.f = 8w42;
* transition p1_0;
* }
* state p1_0 {
* transition accept;
* }
* }
* @endcode
*
* Parser after Inline pass with optimization:
* @code{.p4}
* parser ParserImpl(packet_in packet, out headers hdr, inout metadata meta, inout standard_metadata_t standard_metadata) {
* state start {
* transition select(standard_metadata.ingress_port) {
* 9w0: p0;
* default: p1;
* }
* }
* state p0 {
* transition Subparser_start;
* }
* state Subparser_start {
* hdr.h1.f = 8w42;
* transition p0_0;
* }
* state p0_0 {
* transition accept;
* }
* state p1 {
* transition Subparser_start;
* }
* }
* @endcode
*
* @attention
* This field is used only when the optimization of parser inlining is enabled,
* otherwise it is not used.
* The optimization is disabled by default.
* The optimization can be enabled using command line option
* --parser-inline-opt.
*/
std::unordered_map<const InlinedInvocationInfo, const IR::ID, key_hash, key_equal>
invocationToState;
/// @returns nullptr if there isn't exactly one caller,
/// otherwise the single caller of this instance.
const IR::MethodCallStatement* uniqueCaller(
const IR::Declaration_Instance* instance) const {
const IR::MethodCallStatement* call = nullptr;
for (auto m : callToInstance) {
if (m.second == instance) {
if (call == nullptr)
call = m.first;
else
return nullptr;
}
}
return call;
}
};
std::map<const IR::IContainer*, PerCaller> callerToWork;
void add(const CallInfo *cci) {
callerToWork[cci->caller].declToCallee[cci->instantiation] = cci->callee;
for (auto mcs : cci->invocations)
callerToWork[cci->caller].callToInstance[mcs] = cci->instantiation;
}
void dbprint(std::ostream& out) const
{ out << "Inline " << callerToWork.size() << " call sites"; }
};
// Inling information constructed here.
class InlineList {
// We use an ordered map to make the iterator deterministic
ordered_map<const IR::Declaration_Instance*, CallInfo*> inlineMap;
std::vector<CallInfo*> toInline; // sorted in order of inlining
const bool allowMultipleCalls = true;
public:
void addInstantiation(const IR::IContainer* caller, const IR::IContainer* callee,
const IR::Declaration_Instance* instantiation) {
CHECK_NULL(caller); CHECK_NULL(callee); CHECK_NULL(instantiation);
LOG3("Inline instantiation " << dbp(instantiation));
auto inst = new CallInfo(caller, callee, instantiation);
inlineMap[instantiation] = inst;
}
size_t size() const {
return inlineMap.size();
}
void addInvocation(const IR::Declaration_Instance* instance,
const IR::MethodCallStatement* statement) {
CHECK_NULL(instance); CHECK_NULL(statement);
LOG3("Inline invocation " << dbp(instance) << " at " << dbp(statement));
auto info = inlineMap[instance];
BUG_CHECK(info, "Could not locate instance %1% invoked by %2%", instance, statement);
info->addInvocation(statement);
}
void replace(const IR::IContainer* container, const IR::IContainer* replacement) {
CHECK_NULL(container); CHECK_NULL(replacement);
LOG3("Replacing " << dbp(container) << " with " << dbp(replacement));
for (auto e : toInline) {
if (e->callee == container)
e->callee = replacement;
if (e->caller == container)
e->caller = replacement;
}
}
void analyze();
InlineSummary* next();
};
/// Must be run after an evaluator; uses the blocks to discover caller/callee relationships.
class DiscoverInlining : public Inspector {
InlineList* inlineList; // output: result is here
ReferenceMap* refMap; // input
TypeMap* typeMap; // input
IHasBlock* evaluator; // used to obtain the toplevel block
IR::ToplevelBlock* toplevel;
public:
bool allowParsers = true;
bool allowControls = true;
DiscoverInlining(InlineList* inlineList, ReferenceMap* refMap,
TypeMap* typeMap, IHasBlock* evaluator) :
inlineList(inlineList), refMap(refMap), typeMap(typeMap),
evaluator(evaluator), toplevel(nullptr) {
CHECK_NULL(inlineList); CHECK_NULL(refMap); CHECK_NULL(typeMap); CHECK_NULL(evaluator);
setName("DiscoverInlining"); visitDagOnce = false;
}
Visitor::profile_t init_apply(const IR::Node* node) override {
toplevel = evaluator->getToplevelBlock();
CHECK_NULL(toplevel);
return Inspector::init_apply(node); }
void visit_all(const IR::Block* block);
bool preorder(const IR::Block* block) override
{ visit_all(block); return false; }
bool preorder(const IR::ControlBlock* block) override;
bool preorder(const IR::ParserBlock* block) override;
void postorder(const IR::MethodCallStatement* statement) override;
// We don't care to visit the program, we just visit the blocks.
bool preorder(const IR::P4Program*) override
{ visit_all(toplevel); return false; }
};
/// Performs actual inlining work
class GeneralInliner : public AbstractInliner<InlineList, InlineSummary> {
ReferenceMap* refMap;
TypeMap* typeMap;
InlineSummary::PerCaller* workToDo;
bool optimizeParserInlining;
public:
explicit GeneralInliner(bool isv1, bool _optimizeParserInlining) :
refMap(new ReferenceMap()), typeMap(new TypeMap()), workToDo(nullptr),
optimizeParserInlining(_optimizeParserInlining) {
setName("GeneralInliner");
refMap->setIsV1(isv1);
visitDagOnce = false;
}
// controlled visiting order
const IR::Node* preorder(IR::MethodCallStatement* statement) override;
/** Build the substitutions needed for args and locals of the thing being inlined.
* P4Block here should be either P4Control or P4Parser.
* P4BlockType should be either Type_Control or Type_Parser to match the P4Block.
*/
template<class P4Block, class P4BlockType>
void inline_subst(P4Block *caller,
IR::IndexedVector<IR::Declaration> P4Block::*blockLocals,
const P4BlockType *P4Block::*blockType);
const IR::Node* preorder(IR::P4Control* caller) override;
const IR::Node* preorder(IR::P4Parser* caller) override;
const IR::Node* preorder(IR::ParserState* state) override;
Visitor::profile_t init_apply(const IR::Node* node) override;
};
/// Performs one round of inlining bottoms-up
class InlinePass : public PassManager {
InlineList toInline;
public:
InlinePass(ReferenceMap* refMap, TypeMap* typeMap, EvaluatorPass* evaluator,
bool optimizeParserInlining)
: PassManager({
new TypeChecking(refMap, typeMap),
new DiscoverInlining(&toInline, refMap, typeMap, evaluator),
new InlineDriver<InlineList, InlineSummary>(&toInline, new GeneralInliner(refMap->isV1(),
optimizeParserInlining)),
new RemoveAllUnusedDeclarations(refMap) }) { setName("InlinePass"); }
};
/**
Performs inlining as many times as necessary. Most frequently once
will be enough. Multiple iterations are necessary only when instances are
passed as arguments using constructor arguments.
*/
class Inline : public PassRepeated {
static std::set<cstring> noPropagateAnnotations;
public:
Inline(ReferenceMap* refMap, TypeMap* typeMap, EvaluatorPass* evaluator,
bool optimizeParserInlining)
: PassManager({
new InlinePass(refMap, typeMap, evaluator, optimizeParserInlining),
// After inlining the output of the evaluator changes, so
// we have to run it again
evaluator }) { setName("Inline"); }
/// Do not propagate annotation \p name during inlining
static void setAnnotationNoPropagate(cstring name) {
noPropagateAnnotations.emplace(name);
}
/// Is annotation \p name excluded from inline propagation?
static bool isAnnotationNoPropagate(cstring name) {
return noPropagateAnnotations.count(name);
}
};
} // namespace P4
#endif /* _FRONTENDS_P4_INLINING_H_ */
| 7,941 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.jsf.navigation.graph.layout;
import org.netbeans.modules.web.jsf.navigation.graph.*;
import java.awt.*;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.netbeans.api.visual.model.ObjectSceneEvent;
import org.netbeans.api.visual.model.ObjectSceneEventType;
import org.netbeans.api.visual.model.ObjectSceneListener;
import org.netbeans.api.visual.model.ObjectState;
import org.netbeans.api.visual.widget.Scene.SceneListener;
import org.netbeans.api.visual.widget.Widget;
import org.netbeans.modules.web.jsf.navigation.Page;
/**
* @author <NAME>
*/
// TODO - perfomance - scalability problem
public final class FreePlaceNodesLayouter {
public FreePlaceNodesLayouter(PageFlowScene scene) {
this(scene, false);
}
public static final void performLayout(PageFlowScene scene) {
final FreePlaceNodesLayouter layout = new FreePlaceNodesLayouter(scene, true);
final Collection<Page> pages = scene.getNodes();
for( Page page: pages){
final Widget widget = scene.findWidget(page);
widget.setPreferredLocation(null);
}
scene.validate(); /* to make sure the nodes are set in a different place*/
layout.layoutNodesLocations(scene, scene.getNodes());
scene.validate();
}
PageFlowSceneListener pfsl = new PageFlowSceneListener();
PageFlowObjectSceneListener pfosl = new PageFlowObjectSceneListener();
public void registerListeners(PageFlowScene scene) {
scene.addSceneListener(pfsl);
scene.addObjectSceneListener(pfosl, ObjectSceneEventType.OBJECT_ADDED);
}
public void unregisterListeners(PageFlowScene scene ) {
scene.removeSceneListener(pfsl);
scene.removeObjectSceneListener(pfosl, ObjectSceneEventType.OBJECT_ADDED);
}
final PageFlowScene scene;
private FreePlaceNodesLayouter(PageFlowScene scene, boolean isOneTimeUse){
this.scene = scene;
if( !isOneTimeUse){
registerListeners(scene);
}
}
public FreePlaceNodesLayouter( PageFlowScene scene, Rectangle visibleRectangle ){
this(scene);
}
private final Map<String,Point> positions = new HashMap<String,Point> ();
public void layoutNodesLocations( PageFlowScene scene, Collection<Page> nodes) {
final Collection<Page> allNodes = scene.getNodes();
for( Page node : nodes ) {
final Widget nodeWidget = scene.findWidget(node);
if( nodeWidget == null ) {
return;
}
if ( nodeWidget.getPreferredLocation() != null ) {
/* If the getPreferredLocation has already been set by something else. */
/* The unique ID for a node is it's display name defined by: node.getDisplayName() */
positions.put(node.getDisplayName(), nodeWidget.getPreferredLocation());
} else {
Point point = positions.get(node.getDisplayName());
if ( point == null ) {
point = getNewComponentLocation(scene, positions, allNodes);
}
positions.put(node.getDisplayName(), point);
nodeWidget.setPreferredLocation(point);
}
}
}
public void addNode( Page node ) {
nodesAdded.add(node);
}
private final int SEP_X = 250;
private final int SEP_Y = 150;
private Point getNewComponentLocation(PageFlowScene scene, Map positions, Collection<Page> nodes) {
for (int a = 0; ; a++) {
for (int b = 0; b <= a; b++) {
final int x = SEP_Y + SEP_X * (a - b);
final int y = SEP_Y * (1 + b);
if (isThereEmptyPlace(scene, positions, nodes, x, y)) {
return new Point(x, y);
}
}
}
}
private boolean isThereEmptyPlace(PageFlowScene scene, Map positions, Collection<Page> nodes, int x, int y) {
final Rectangle rectangle = new Rectangle(x, y, 100, 150);
if (nodes != null) {
for( Page node : nodes) {
Point location = (Point) positions.get(node.getDisplayName());
if (location == null) {
location = scene.findWidget(node).getLocation();
}
if (location != null && rectangle.contains(location)) {
return false;
}
final Rectangle bounds = scene.findWidget(node).getBounds();
if (bounds != null && rectangle.contains(bounds)) {
return false;
}
}
}
return true;
}
private static final UnsupportedOperationException uoe = new UnsupportedOperationException("Not supported yet");
private final Collection<Page> nodesAdded = new HashSet<Page>();
private class PageFlowObjectSceneListener implements ObjectSceneListener{
public void objectAdded(ObjectSceneEvent event, Object addedObject) {
if( ((PageFlowScene)event.getObjectScene()).isNode(addedObject) ) {
nodesAdded.add((Page)addedObject);
}
}
public void objectRemoved(ObjectSceneEvent event, Object removedObject) {
throw uoe;
}
public void objectStateChanged(ObjectSceneEvent event,
Object changedObject,
ObjectState prevState,
ObjectState newState) {
throw uoe;
}
public void selectionChanged(ObjectSceneEvent event,
Set<Object> prevSelection,
Set<Object> newSelection) {
throw uoe;
}
public void highlightingChanged(ObjectSceneEvent event,
Set<Object> prevHighlighting,
Set<Object> newHighlighting) {
throw uoe;
}
public void hoverChanged(ObjectSceneEvent event,
Object prevHoveredObject,
Object newHoveredObject) {
throw uoe;
}
public void focusChanged(ObjectSceneEvent event,
Object prevFocusedObject,
Object newFocusedObject) {
throw uoe;
}
}
/* Once validated is called all the nodes have been drawn. Bounds and location
* can then be determineded. Set the final location and validate automatically
* gets called one last time.
*/
private class PageFlowSceneListener implements SceneListener {
public void sceneRepaint() {
}
public void sceneValidating() {
}
public void sceneValidated() {
if( !nodesAdded.isEmpty() ) {
layoutNodesLocations(scene, nodesAdded);
nodesAdded.clear();
}
}
};
}
| 3,374 |
1,799 | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/kernels/cuda/mul_compute.h"
#include <gtest/gtest.h>
#include <memory>
#include <utility>
#include <vector>
#include "lite/api/test/test_helper.h"
#include "lite/utils/float16.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace cuda {
class MulTest : public ::testing::Test {
protected:
MulTest()
: m_(2),
k_(3),
n_(4),
x_shape_({m_, k_}),
y_shape_({k_, n_}),
out_shape_({m_, n_}) {
x_gpu_.Resize(lite::DDim(x_shape_));
x_ref_.Resize(lite::DDim(x_shape_));
y_gpu_.Resize(lite::DDim(y_shape_));
y_ref_.Resize(lite::DDim(y_shape_));
auto x_ref_data = x_ref_.mutable_data<float>();
auto y_ref_data = y_ref_.mutable_data<float>();
// prepare input
for (int64_t i = 0; i < x_ref_.numel(); i++) {
x_ref_data[i] = static_cast<float>(i % 10 * 0.2);
}
for (int64_t i = 0; i < y_ref_.numel(); i++) {
y_ref_data[i] = static_cast<float>(i % 10 * 0.2);
}
out_ref_.Resize(lite::DDim(out_shape_));
out_cpu_.Resize(lite::DDim(out_shape_));
out_gpu_.Resize(lite::DDim(out_shape_));
RunBaseLine(&x_ref_, &y_ref_, &out_ref_);
InitParamAndContext();
}
void InitParamAndContext() {
ctx_.reset(new KernelContext);
cudaStreamCreate(&stream_);
auto& context = ctx_->As<CUDAContext>();
context.SetExecStream(stream_);
param_.x = &x_gpu_;
param_.y = &y_gpu_;
param_.output = &out_gpu_;
}
void InitFloatInput() {
x_gpu_.Assign<float, lite::DDim, TARGET(kCUDA)>(x_ref_.data<float>(),
x_gpu_.dims());
y_gpu_.Assign<float, lite::DDim, TARGET(kCUDA)>(y_ref_.data<float>(),
y_gpu_.dims());
}
void InitHalfInput() {
x_half_.Resize(lite::DDim(x_ref_.dims()));
auto x_half_data = x_half_.mutable_data<half>();
for (int64_t i = 0; i < x_half_.numel(); i++) {
x_half_data[i] = half(lite::float16(x_ref_.data<float>()[i]));
}
x_gpu_.Assign<half, lite::DDim, TARGET(kCUDA)>(x_half_data, x_gpu_.dims());
y_half_.Resize(y_ref_.dims());
auto y_half_data = y_half_.mutable_data<half>();
for (int64_t i = 0; i < y_half_.numel(); i++) {
y_half_data[i] = half(lite::float16(y_ref_.data<float>()[i]));
}
y_gpu_.Assign<half, lite::DDim, TARGET(kCUDA)>(y_half_data, y_gpu_.dims());
}
void RunBaseLine(const lite::Tensor* x,
const lite::Tensor* w,
lite::Tensor* out) {
const float* data_in = x->data<float>();
const float* weights = w->data<float>();
float* data_out = out->mutable_data<float>();
int out_rows = x->dims()[0];
int in_cols = x->numel() / out_rows;
int out_cols = w->numel() / in_cols;
int index_out;
for (int i = 0; i < out_rows; i++) {
for (int j = 0; j < out_cols; j++) {
index_out = i * out_cols + j;
data_out[index_out] = 0;
for (int k = 0; k < in_cols; k++) {
data_out[index_out] +=
data_in[i * in_cols + k] * weights[k * out_cols + j];
}
}
}
}
int m_, k_, n_;
std::vector<int64_t> x_shape_, y_shape_, out_shape_;
lite::Tensor x_ref_, y_ref_, out_ref_;
lite::Tensor x_gpu_, y_gpu_;
lite::Tensor x_half_, y_half_;
lite::Tensor out_cpu_, out_gpu_;
operators::MulParam param_;
std::unique_ptr<KernelContext> ctx_;
cudaStream_t stream_;
};
TEST_F(MulTest, TestFP32) {
InitFloatInput();
MulCompute<float, PRECISION(kFloat)> mul_kernel;
mul_kernel.SetParam(param_);
mul_kernel.SetContext(std::move(ctx_));
for (int i = 0; i < FLAGS_warmup; ++i) {
mul_kernel.Launch();
cudaDeviceSynchronize();
}
auto start = GetCurrentUS();
mul_kernel.PrepareForRun();
for (int i = 0; i < FLAGS_repeats; ++i) {
mul_kernel.Run();
}
cudaDeviceSynchronize();
auto duration = (GetCurrentUS() - start) / 1000.0;
LOG(INFO) << "fp32, warmup: " << FLAGS_warmup
<< ", repeats: " << FLAGS_repeats << ", spend "
<< duration / FLAGS_repeats << " ms in average.";
CopySync<TARGET(kCUDA)>(out_cpu_.mutable_data<float>(),
out_gpu_.data<float>(),
sizeof(float) * out_gpu_.numel(),
IoDirection::DtoH);
for (int i = 0; i < out_gpu_.numel(); ++i) {
float res = out_cpu_.data<float>()[i];
float ref = out_ref_.data<float>()[i];
EXPECT_NEAR(fabs(res - ref) / (ref + 1e-5), 0., 1e-4);
}
}
TEST_F(MulTest, TestFP16) {
InitHalfInput();
MulCompute<half, PRECISION(kFP16)> mul_kernel;
mul_kernel.SetParam(param_);
mul_kernel.SetContext(std::move(ctx_));
for (int i = 0; i < FLAGS_warmup; ++i) {
mul_kernel.Launch();
cudaDeviceSynchronize();
}
auto start = GetCurrentUS();
mul_kernel.PrepareForRun();
for (int i = 0; i < FLAGS_repeats; ++i) {
mul_kernel.Run();
}
cudaDeviceSynchronize();
auto duration = (GetCurrentUS() - start) / 1000.0;
LOG(INFO) << "fp16, warmup: " << FLAGS_warmup
<< ", repeats: " << FLAGS_repeats << ", spend "
<< duration / FLAGS_repeats << " ms in average.";
const half* out_gpu_data = out_gpu_.data<half>();
half* out_cpu_data = out_cpu_.mutable_data<half>();
CopySync<TARGET(kCUDA)>(out_cpu_data,
out_gpu_data,
sizeof(half) * out_gpu_.numel(),
IoDirection::DtoH);
for (int i = 0; i < out_cpu_.numel(); ++i) {
float res = static_cast<float>(lite::float16(out_cpu_data[i]));
float ref = out_ref_.data<float>()[i];
EXPECT_NEAR(fabs(res - ref) / (ref + 1e-5), 0., 1e-2);
}
}
} // namespace cuda
} // namespace kernels
} // namespace lite
} // namespace paddle
| 2,974 |
931 | <reponame>jahnvisrivastava100/CompetitiveProgrammingQuestionBank<filename>CodeVita Problems/count pairs.c
#include<stdio.h>
#include<stdlib.h>
int binarySearch(int arr[], int n, int k)
{
int start = 0;
int end = n-1;
while(start<=end)
{
int mid = (start+end)/2;
if(arr[mid]==k)
return mid;
else if(arr[mid]<k)
start = mid + 1;
else if(arr[mid]>k)
end = mid - 1;
}
return 0;
}
//6 3
//5 5 7 9 15 2
int main()
{
int n, k, happyCounter=0;
scanf("%d %d", &n,&k);
int arr[n];
for(int arr_ind=0;arr_ind<n;arr_ind++)
scanf("%d", &arr[arr_ind]);
for(int arr_ind=0;arr_ind<n;arr_ind++)
{
for(int range=arr[arr_ind]-k;range<=arr[arr_ind]+k;range++)
{
if(binarySearch(arr, n, range))
{
happyCounter++;
break;
}
}
}
printf("%d", happyCounter);
return 0;
}
| 527 |
12,824 | import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface NotNull {
}
| 54 |
332 | /*
* Copyright 2014-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.xd.dirt.modules.metadata;
import static org.springframework.xd.dirt.modules.metadata.FileSinkOptionsMetadata.Mode.APPEND;
import static org.springframework.xd.module.options.spi.ModulePlaceholders.XD_STREAM_NAME;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.util.StringUtils;
import org.springframework.xd.module.options.spi.ModuleOption;
import org.springframework.xd.module.options.spi.ProfileNamesProvider;
/**
*
* Holds options to the 'file' sink module.
*
* @author <NAME>
* @author <NAME>
*/
public class FileSinkOptionsMetadata implements ProfileNamesProvider {
private static final String USE_SPEL_PROFILE = "use-expression";
private static final String USE_LITERAL_STRING_PROFILE = "use-string";
private boolean binary = false;
private String charset = "UTF-8";
private String dir = "/tmp/xd/output/";
private String name = XD_STREAM_NAME;
private String suffix = "out";
private Mode mode = APPEND;
private String nameExpression;
private String dirExpression;
@NotNull
public Mode getMode() {
return mode;
}
@ModuleOption("what to do if the file already exists")
public void setMode(Mode mode) {
this.mode = mode;
}
/**
* Return dot + suffix if suffix is set, or the empty string otherwise.
*/
public String getExtensionWithDot() {
return StringUtils.hasText(suffix) ? "." + suffix.trim() : "";
}
@ModuleOption("filename extension to use")
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getName() {
return name;
}
@ModuleOption("filename pattern to use")
public void setName(String name) {
this.name = name;
}
@NotBlank
public String getDir() {
return dir;
}
@ModuleOption("the directory in which files will be created")
public void setDir(String dir) {
this.dir = dir;
}
public boolean isBinary() {
return binary;
}
@ModuleOption("if false, will append a newline character at the end of each line")
public void setBinary(boolean binary) {
this.binary = binary;
}
@ModuleOption("the charset to use when writing a String payload")
public void setCharset(String charset) {
this.charset = charset;
}
@NotBlank
public String getCharset() {
return charset;
}
public String getNameExpression() {
return nameExpression;
}
@ModuleOption("spring expression used to define filename")
public void setNameExpression(String nameExpression) {
this.nameExpression = nameExpression;
}
public String getDirExpression() {
return dirExpression;
}
@ModuleOption("spring expression used to define directory name")
public void setDirExpression(String dirExpression) {
this.dirExpression = dirExpression;
}
public static enum Mode {
APPEND, REPLACE, FAIL, IGNORE;
}
@Override
public String[] profilesToActivate() {
return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE }
: new String[] { USE_LITERAL_STRING_PROFILE };
}
}
| 1,135 |
1,338 | /*
* Copyright 2018, Haiku, Inc. All rights reserved.
* Based on Demumble; Copyright 2016-2018, <NAME>.
* https://github.com/nico/demumble/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include "Demangler.h"
static void print_help(FILE* out)
{
fprintf(out,
"usage: haikuc++filt [options] [symbols...]\n"
"\n"
"if symbols are unspecified, reads from stdin.\n"
"\n"
"options:\n"
" -m only print mangled names that were demangled,"
"omit other output\n"
" -u use unbuffered output\n"
" --no-gcc2 ignore GCC 2-style symbols\n");
}
static bool starts_with(const char* s, const char* prefix)
{
return strncmp(s, prefix, strlen(prefix)) == 0;
}
static void print_demangled(const char* s)
{
const char* cxa_in = s;
if (starts_with(s, "__Z") || starts_with(s, "____Z"))
cxa_in += 1;
printf("%s", Demangler::Demangle(cxa_in).String());
}
static bool is_mangle_char_posix(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_';
}
static bool look_for_itanium_prefix(char** str, char* end)
{
char* s = *str;
s += strcspn(s, "_?");
if (s == end)
return false;
// Itanium symbols start with 1-4 underscores followed by Z.
// strnstr() is BSD, so use a small local buffer and strstr().
const int N = 5; // == strlen("____Z")
char prefix[N + 1];
strncpy(prefix, s, N);
prefix[N] = '\0';
if (strstr(prefix, "_Z")) {
*str = s;
return true;
}
return false;
}
static bool look_for_gcc2_symbol(char** str, char* end)
{
// search '__' starting from the end, don't accept them at the start
char* s = *str;
size_t pos = (end - s) - 1;
char* mangled = NULL;
while (pos > 1) {
if (s[pos] == '_') {
if (s[pos - 1] == '_') {
mangled = s + pos + 1;
break;
} else
pos--;
}
pos--;
}
// if we've found a symbol, go backwards to its beginning
while (mangled != NULL && mangled > (s + 1)
&& is_mangle_char_posix(mangled[-1])) {
mangled--;
}
if (mangled != NULL)
*str = mangled;
return mangled != NULL;
}
static char buf[8192];
int main(int argc, char* argv[])
{
enum { kPrintAll, kPrintMatching } print_mode = kPrintAll;
bool noGCC2 = false;
while (argc > 1 && argv[1][0] == '-') {
if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
print_help(stdout);
return 0;
} else if (strcmp(argv[1], "-m") == 0) {
print_mode = kPrintMatching;
} else if (strcmp(argv[1], "--no-gcc2") == 0) {
noGCC2 = true;
} else if (strcmp(argv[1], "-u") == 0) {
setbuf(stdout, NULL);
} else if (strcmp(argv[1], "--") == 0) {
--argc;
++argv;
break;
} else {
fprintf(stderr, "c++filt: unrecognized option `%s'\n", argv[1]);
print_help(stderr);
return 1;
}
--argc;
++argv;
}
for (int i = 1; i < argc; ++i) {
print_demangled(argv[i]);
printf("\n");
}
if (argc != 1)
return 0;
// Read stdin instead.
// By default, don't demangle types. Mangled function names are unlikely
// to appear in text for since they start with _Z (or ___Z) or ?? / ?$ / ?@.
// But type manglings can be regular words ("Pi" is "int*").
// (For command-line args, do try to demangle types though.)
while (fgets(buf, sizeof(buf), stdin)) {
bool need_separator = false;
char* cur = buf;
char* end = cur + strlen(cur);
while (cur != end) {
if (print_mode == kPrintMatching && need_separator)
printf("\n");
need_separator = false;
// Check if we have a symbol, and then for how long it is.
size_t n_sym = 0;
char* real_cur = cur;
if (look_for_itanium_prefix(&real_cur, end) ||
(!noGCC2 && look_for_gcc2_symbol(&real_cur, end))) {
// Print all the stuff before the symbol.
if (print_mode == kPrintAll)
printf("%.*s", static_cast<int>(real_cur - cur), cur);
cur = real_cur;
while (cur + n_sym != end && is_mangle_char_posix(cur[n_sym]))
++n_sym;
} else {
// No symbols found in this block; skip it.
printf("%s", cur);
cur = end;
continue;
}
if (n_sym == 0) {
++cur;
continue;
}
char tmp = cur[n_sym];
cur[n_sym] = '\0';
print_demangled(cur);
need_separator = true;
cur[n_sym] = tmp;
cur += n_sym;
}
}
}
| 2,039 |
3,102 | #include <B/B.h>
| 10 |
626 | /*
* Copyright 2018, OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opencensus.trace.internal;
import io.opencensus.common.Internal;
import io.opencensus.internal.Utils;
/**
* Helper class to convert/cast between for {@link io.opencensus.trace.MessageEvent} and {@link
* io.opencensus.trace.NetworkEvent}.
*/
@Internal
@SuppressWarnings("deprecation")
public final class BaseMessageEventUtils {
/**
* Cast or convert a {@link io.opencensus.trace.BaseMessageEvent} to {@link
* io.opencensus.trace.MessageEvent}.
*
* <p>Warning: if the input is a {@code io.opencensus.trace.NetworkEvent} and contains {@code
* kernelTimestamp} information, this information will be dropped.
*
* @param event the {@code BaseMessageEvent} that is being cast or converted.
* @return a {@code MessageEvent} representation of the input.
*/
public static io.opencensus.trace.MessageEvent asMessageEvent(
io.opencensus.trace.BaseMessageEvent event) {
Utils.checkNotNull(event, "event");
if (event instanceof io.opencensus.trace.MessageEvent) {
return (io.opencensus.trace.MessageEvent) event;
}
io.opencensus.trace.NetworkEvent networkEvent = (io.opencensus.trace.NetworkEvent) event;
io.opencensus.trace.MessageEvent.Type type =
(networkEvent.getType() == io.opencensus.trace.NetworkEvent.Type.RECV)
? io.opencensus.trace.MessageEvent.Type.RECEIVED
: io.opencensus.trace.MessageEvent.Type.SENT;
return io.opencensus.trace.MessageEvent.builder(type, networkEvent.getMessageId())
.setUncompressedMessageSize(networkEvent.getUncompressedMessageSize())
.setCompressedMessageSize(networkEvent.getCompressedMessageSize())
.build();
}
/**
* Cast or convert a {@link io.opencensus.trace.BaseMessageEvent} to {@link
* io.opencensus.trace.NetworkEvent}.
*
* @param event the {@code BaseMessageEvent} that is being cast or converted.
* @return a {@code io.opencensus.trace.NetworkEvent} representation of the input.
*/
public static io.opencensus.trace.NetworkEvent asNetworkEvent(
io.opencensus.trace.BaseMessageEvent event) {
Utils.checkNotNull(event, "event");
if (event instanceof io.opencensus.trace.NetworkEvent) {
return (io.opencensus.trace.NetworkEvent) event;
}
io.opencensus.trace.MessageEvent messageEvent = (io.opencensus.trace.MessageEvent) event;
io.opencensus.trace.NetworkEvent.Type type =
(messageEvent.getType() == io.opencensus.trace.MessageEvent.Type.RECEIVED)
? io.opencensus.trace.NetworkEvent.Type.RECV
: io.opencensus.trace.NetworkEvent.Type.SENT;
return io.opencensus.trace.NetworkEvent.builder(type, messageEvent.getMessageId())
.setUncompressedMessageSize(messageEvent.getUncompressedMessageSize())
.setCompressedMessageSize(messageEvent.getCompressedMessageSize())
.build();
}
private BaseMessageEventUtils() {}
}
| 1,189 |
2,504 | <reponame>nefeithu/behaviac
// ---------------------------------------------------------------------
// THIS FILE IS AUTO-GENERATED BY BEHAVIAC DESIGNER, SO PLEASE DON'T MODIFY IT BY YOURSELF!
// ---------------------------------------------------------------------
#ifndef _BEHAVIAC_GENERATED_BEHAVIORS_H_
#define _BEHAVIAC_GENERATED_BEHAVIORS_H_
#include "../types/behaviac_types.h"
namespace behaviac
{
// Source file: performance/Performance
class DecoratorLoop_bt_performance_Performance_node1 : public DecoratorLoop
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(DecoratorLoop_bt_performance_Performance_node1, DecoratorLoop);
DecoratorLoop_bt_performance_Performance_node1()
{
m_bDecorateWhenChildEnds = true;
m_bDoneWithinFrame = false;
}
protected:
virtual int GetCount(Agent* pAgent) const
{
BEHAVIAC_UNUSED_VAR(pAgent);
return 10;
}
};
class Condition_bt_performance_Performance_node5 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_performance_Performance_node5, Condition);
Condition_bt_performance_Performance_node5()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
float& opl = ((CPerformanceAgent*)pAgent)->DistanceToEnemy;
BEHAVIAC_ASSERT(behaviac::MakeVariableId("par_SmallDisance") == 4142645218u);
float& opr = (float&)pAgent->GetVariable<float >(4142645218u);
bool op = PrivateDetails::LessEqual(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Condition_bt_performance_Performance_node6 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_performance_Performance_node6, Condition);
Condition_bt_performance_Performance_node6()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
float& opl = ((CPerformanceAgent*)pAgent)->HP;
BEHAVIAC_ASSERT(behaviac::MakeVariableId("par_HealthThreshold") == 1146605254u);
float& opr = (float&)pAgent->GetVariable<float >(1146605254u);
bool op = PrivateDetails::LessEqual(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Action_bt_performance_Performance_node7 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_performance_Performance_node7, Action);
Action_bt_performance_Performance_node7()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((CPerformanceAgent*)pAgent)->RunAway();
return result;
}
};
class Precondition_bt_performance_Performance_attach3 : public Precondition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Precondition_bt_performance_Performance_attach3, Precondition);
Precondition_bt_performance_Performance_attach3()
{
this->SetPhase(Precondition::E_ENTER);
this->SetIsAnd(true);
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
EBTStatus result = BT_SUCCESS;
float& opl = ((CPerformanceAgent*)pAgent)->DistanceToEnemy;
BEHAVIAC_ASSERT(behaviac::MakeVariableId("par_BigDistance") == 1778440178u);
float& opr2 = (float&)pAgent->GetVariable<float >(1778440178u);
bool op = PrivateDetails::Greater(opl, opr2);
if (!op)
result = BT_FAILURE;
return result;
}
};
class Action_bt_performance_Performance_node19 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_performance_Performance_node19, Action);
Action_bt_performance_Performance_node19()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
((CPerformanceAgent*)pAgent)->Fire();
return BT_SUCCESS;
}
};
class Parallel_bt_performance_Performance_node22 : public Parallel
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Parallel_bt_performance_Performance_node22, Parallel);
Parallel_bt_performance_Performance_node22()
{
m_failPolicy = FAIL_ON_ONE;
m_succeedPolicy = SUCCEED_ON_ALL;
m_exitPolicy = EXIT_ABORT_RUNNINGSIBLINGS;
m_childFinishPolicy = CHILDFINISH_LOOP;
}
protected:
};
class Condition_bt_performance_Performance_node16 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_performance_Performance_node16, Condition);
Condition_bt_performance_Performance_node16()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
float& opl = ((CPerformanceAgent*)pAgent)->DistanceToEnemy;
BEHAVIAC_ASSERT(behaviac::MakeVariableId("par_SmallDisance") == 4142645218u);
float& opr = (float&)pAgent->GetVariable<float >(4142645218u);
bool op = PrivateDetails::Greater(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Condition_bt_performance_Performance_node9 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_performance_Performance_node9, Condition);
Condition_bt_performance_Performance_node9()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
float& opl = ((CPerformanceAgent*)pAgent)->Hungry;
BEHAVIAC_ASSERT(behaviac::MakeVariableId("par_HungryThreshold") == 825091127u);
float& opr = (float&)pAgent->GetVariable<float >(825091127u);
bool op = PrivateDetails::GreaterEqual(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Condition_bt_performance_Performance_node13 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_performance_Performance_node13, Condition);
Condition_bt_performance_Performance_node13()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
float& opl = ((CPerformanceAgent*)pAgent)->Food;
float opr = 0;
bool op = PrivateDetails::Equal(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Action_bt_performance_Performance_node14 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_performance_Performance_node14, Action);
Action_bt_performance_Performance_node14()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((CPerformanceAgent*)pAgent)->SearchForFood();
return result;
}
};
class Action_bt_performance_Performance_node15 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_performance_Performance_node15, Action);
Action_bt_performance_Performance_node15()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((CPerformanceAgent*)pAgent)->Eat();
return result;
}
};
class Parallel_bt_performance_Performance_node20 : public Parallel
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Parallel_bt_performance_Performance_node20, Parallel);
Parallel_bt_performance_Performance_node20()
{
m_failPolicy = FAIL_ON_ONE;
m_succeedPolicy = SUCCEED_ON_ALL;
m_exitPolicy = EXIT_ABORT_RUNNINGSIBLINGS;
m_childFinishPolicy = CHILDFINISH_LOOP;
}
protected:
};
class Condition_bt_performance_Performance_node8 : public Condition
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Condition_bt_performance_Performance_node8, Condition);
Condition_bt_performance_Performance_node8()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
float& opl = ((CPerformanceAgent*)pAgent)->DistanceToEnemy;
BEHAVIAC_ASSERT(behaviac::MakeVariableId("par_SmallDisance") == 4142645218u);
float& opr = (float&)pAgent->GetVariable<float >(4142645218u);
bool op = PrivateDetails::Greater(opl, opr);
return op ? BT_SUCCESS : BT_FAILURE;
}
};
class Action_bt_performance_Performance_node18 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_performance_Performance_node18, Action);
Action_bt_performance_Performance_node18()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((CPerformanceAgent*)pAgent)->Wander();
return result;
}
};
class Action_bt_performance_Performance_node4 : public Action
{
public:
BEHAVIAC_DECLARE_DYNAMIC_TYPE(Action_bt_performance_Performance_node4, Action);
Action_bt_performance_Performance_node4()
{
}
protected:
virtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
behaviac::EBTStatus result = ((CPerformanceAgent*)pAgent)->Fidget();
return result;
}
};
class bt_performance_Performance
{
public:
static bool Create(BehaviorTree* pBT)
{
pBT->SetClassNameString("BehaviorTree");
pBT->SetId((uint16_t)-1);
pBT->SetName("performance/Performance");
pBT->SetIsFSM(false);
#if !BEHAVIAC_RELEASE
pBT->SetAgentType("CPerformanceAgent");
#endif
// locals
pBT->AddLocal("CPerformanceAgent", "float", "par_HungryThreshold", "60");
pBT->AddLocal("CPerformanceAgent", "float", "par_BigDistance", "30");
pBT->AddLocal("CPerformanceAgent", "float", "par_SmallDisance", "10");
pBT->AddLocal("CPerformanceAgent", "float", "par_HealthThreshold", "20");
// children
{
DecoratorLoop_bt_performance_Performance_node1* node1 = BEHAVIAC_NEW DecoratorLoop_bt_performance_Performance_node1;
node1->SetClassNameString("DecoratorLoop");
node1->SetId(1);
#if !BEHAVIAC_RELEASE
node1->SetAgentType("CPerformanceAgent");
#endif
pBT->AddChild(node1);
{
Selector* node21 = BEHAVIAC_NEW Selector;
node21->SetClassNameString("Selector");
node21->SetId(21);
#if !BEHAVIAC_RELEASE
node21->SetAgentType("CPerformanceAgent");
#endif
node1->AddChild(node21);
{
Sequence* node0 = BEHAVIAC_NEW Sequence;
node0->SetClassNameString("Sequence");
node0->SetId(0);
#if !BEHAVIAC_RELEASE
node0->SetAgentType("CPerformanceAgent");
#endif
node21->AddChild(node0);
{
Condition_bt_performance_Performance_node5* node5 = BEHAVIAC_NEW Condition_bt_performance_Performance_node5;
node5->SetClassNameString("Condition");
node5->SetId(5);
#if !BEHAVIAC_RELEASE
node5->SetAgentType("CPerformanceAgent");
#endif
node0->AddChild(node5);
node0->SetHasEvents(node0->HasEvents() | node5->HasEvents());
}
{
Selector* node11 = BEHAVIAC_NEW Selector;
node11->SetClassNameString("Selector");
node11->SetId(11);
#if !BEHAVIAC_RELEASE
node11->SetAgentType("CPerformanceAgent");
#endif
node0->AddChild(node11);
{
Sequence* node2 = BEHAVIAC_NEW Sequence;
node2->SetClassNameString("Sequence");
node2->SetId(2);
#if !BEHAVIAC_RELEASE
node2->SetAgentType("CPerformanceAgent");
#endif
node11->AddChild(node2);
{
Condition_bt_performance_Performance_node6* node6 = BEHAVIAC_NEW Condition_bt_performance_Performance_node6;
node6->SetClassNameString("Condition");
node6->SetId(6);
#if !BEHAVIAC_RELEASE
node6->SetAgentType("CPerformanceAgent");
#endif
node2->AddChild(node6);
node2->SetHasEvents(node2->HasEvents() | node6->HasEvents());
}
{
Action_bt_performance_Performance_node7* node7 = BEHAVIAC_NEW Action_bt_performance_Performance_node7;
node7->SetClassNameString("Action");
node7->SetId(7);
#if !BEHAVIAC_RELEASE
node7->SetAgentType("CPerformanceAgent");
#endif
// attachments
{
Precondition_bt_performance_Performance_attach3* attach3 = BEHAVIAC_NEW Precondition_bt_performance_Performance_attach3;
attach3->SetClassNameString("Precondition");
attach3->SetId(3);
#if !BEHAVIAC_RELEASE
attach3->SetAgentType("CPerformanceAgent");
#endif
node7->Attach(attach3, true, false, false);
node7->SetHasEvents(node7->HasEvents() | (Event::DynamicCast(attach3) != 0));
}
node2->AddChild(node7);
node2->SetHasEvents(node2->HasEvents() | node7->HasEvents());
}
node11->SetHasEvents(node11->HasEvents() | node2->HasEvents());
}
{
Action_bt_performance_Performance_node19* node19 = BEHAVIAC_NEW Action_bt_performance_Performance_node19;
node19->SetClassNameString("Action");
node19->SetId(19);
#if !BEHAVIAC_RELEASE
node19->SetAgentType("CPerformanceAgent");
#endif
node11->AddChild(node19);
node11->SetHasEvents(node11->HasEvents() | node19->HasEvents());
}
node0->SetHasEvents(node0->HasEvents() | node11->HasEvents());
}
node21->SetHasEvents(node21->HasEvents() | node0->HasEvents());
}
{
Parallel_bt_performance_Performance_node22* node22 = BEHAVIAC_NEW Parallel_bt_performance_Performance_node22;
node22->SetClassNameString("Parallel");
node22->SetId(22);
#if !BEHAVIAC_RELEASE
node22->SetAgentType("CPerformanceAgent");
#endif
node21->AddChild(node22);
{
Condition_bt_performance_Performance_node16* node16 = BEHAVIAC_NEW Condition_bt_performance_Performance_node16;
node16->SetClassNameString("Condition");
node16->SetId(16);
#if !BEHAVIAC_RELEASE
node16->SetAgentType("CPerformanceAgent");
#endif
node22->AddChild(node16);
node22->SetHasEvents(node22->HasEvents() | node16->HasEvents());
}
{
Sequence* node23 = BEHAVIAC_NEW Sequence;
node23->SetClassNameString("Sequence");
node23->SetId(23);
#if !BEHAVIAC_RELEASE
node23->SetAgentType("CPerformanceAgent");
#endif
node22->AddChild(node23);
{
Condition_bt_performance_Performance_node9* node9 = BEHAVIAC_NEW Condition_bt_performance_Performance_node9;
node9->SetClassNameString("Condition");
node9->SetId(9);
#if !BEHAVIAC_RELEASE
node9->SetAgentType("CPerformanceAgent");
#endif
node23->AddChild(node9);
node23->SetHasEvents(node23->HasEvents() | node9->HasEvents());
}
{
Selector* node10 = BEHAVIAC_NEW Selector;
node10->SetClassNameString("Selector");
node10->SetId(10);
#if !BEHAVIAC_RELEASE
node10->SetAgentType("CPerformanceAgent");
#endif
node23->AddChild(node10);
{
Sequence* node12 = BEHAVIAC_NEW Sequence;
node12->SetClassNameString("Sequence");
node12->SetId(12);
#if !BEHAVIAC_RELEASE
node12->SetAgentType("CPerformanceAgent");
#endif
node10->AddChild(node12);
{
Condition_bt_performance_Performance_node13* node13 = BEHAVIAC_NEW Condition_bt_performance_Performance_node13;
node13->SetClassNameString("Condition");
node13->SetId(13);
#if !BEHAVIAC_RELEASE
node13->SetAgentType("CPerformanceAgent");
#endif
node12->AddChild(node13);
node12->SetHasEvents(node12->HasEvents() | node13->HasEvents());
}
{
Action_bt_performance_Performance_node14* node14 = BEHAVIAC_NEW Action_bt_performance_Performance_node14;
node14->SetClassNameString("Action");
node14->SetId(14);
#if !BEHAVIAC_RELEASE
node14->SetAgentType("CPerformanceAgent");
#endif
node12->AddChild(node14);
node12->SetHasEvents(node12->HasEvents() | node14->HasEvents());
}
node10->SetHasEvents(node10->HasEvents() | node12->HasEvents());
}
{
Action_bt_performance_Performance_node15* node15 = BEHAVIAC_NEW Action_bt_performance_Performance_node15;
node15->SetClassNameString("Action");
node15->SetId(15);
#if !BEHAVIAC_RELEASE
node15->SetAgentType("CPerformanceAgent");
#endif
node10->AddChild(node15);
node10->SetHasEvents(node10->HasEvents() | node15->HasEvents());
}
node23->SetHasEvents(node23->HasEvents() | node10->HasEvents());
}
node22->SetHasEvents(node22->HasEvents() | node23->HasEvents());
}
node21->SetHasEvents(node21->HasEvents() | node22->HasEvents());
}
{
Parallel_bt_performance_Performance_node20* node20 = BEHAVIAC_NEW Parallel_bt_performance_Performance_node20;
node20->SetClassNameString("Parallel");
node20->SetId(20);
#if !BEHAVIAC_RELEASE
node20->SetAgentType("CPerformanceAgent");
#endif
node21->AddChild(node20);
{
Condition_bt_performance_Performance_node8* node8 = BEHAVIAC_NEW Condition_bt_performance_Performance_node8;
node8->SetClassNameString("Condition");
node8->SetId(8);
#if !BEHAVIAC_RELEASE
node8->SetAgentType("CPerformanceAgent");
#endif
node20->AddChild(node8);
node20->SetHasEvents(node20->HasEvents() | node8->HasEvents());
}
{
Sequence* node17 = BEHAVIAC_NEW Sequence;
node17->SetClassNameString("Sequence");
node17->SetId(17);
#if !BEHAVIAC_RELEASE
node17->SetAgentType("CPerformanceAgent");
#endif
node20->AddChild(node17);
{
Action_bt_performance_Performance_node18* node18 = BEHAVIAC_NEW Action_bt_performance_Performance_node18;
node18->SetClassNameString("Action");
node18->SetId(18);
#if !BEHAVIAC_RELEASE
node18->SetAgentType("CPerformanceAgent");
#endif
node17->AddChild(node18);
node17->SetHasEvents(node17->HasEvents() | node18->HasEvents());
}
{
Action_bt_performance_Performance_node4* node4 = BEHAVIAC_NEW Action_bt_performance_Performance_node4;
node4->SetClassNameString("Action");
node4->SetId(4);
#if !BEHAVIAC_RELEASE
node4->SetAgentType("CPerformanceAgent");
#endif
node17->AddChild(node4);
node17->SetHasEvents(node17->HasEvents() | node4->HasEvents());
}
node20->SetHasEvents(node20->HasEvents() | node17->HasEvents());
}
node21->SetHasEvents(node21->HasEvents() | node20->HasEvents());
}
node1->SetHasEvents(node1->HasEvents() | node21->HasEvents());
}
pBT->SetHasEvents(pBT->HasEvents() | node1->HasEvents());
}
return true;
}
};
}
#endif // _BEHAVIAC_GENERATED_BEHAVIORS_H_
| 7,938 |
764 | <gh_stars>100-1000
{"symbol": "GMT","address": "0xb3Bd49E28f8F832b8d1E246106991e546c323502","overview":{"en": ""},"email": "<EMAIL>","website": "https://www.mercuryprotocol.com/","state": "NORMAL","links": {"blog": "https://medium.com/mercuryprotocol","twitter": "https://twitter.com/mercuryprotocol","telegram": "https://t.me/joinchat/G47gcA8f5EYFfEsILw7H2w","github": ""}} | 153 |
1,350 | <filename>sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/DataCenterResourceProperties.java<gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.cosmos.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Properties of a managed Cassandra data center. */
@Fluent
public final class DataCenterResourceProperties {
@JsonIgnore private final ClientLogger logger = new ClientLogger(DataCenterResourceProperties.class);
/*
* The status of the resource at the time the operation was called.
*/
@JsonProperty(value = "provisioningState")
private ManagedCassandraProvisioningState provisioningState;
/*
* The region this data center should be created in.
*/
@JsonProperty(value = "dataCenterLocation")
private String dataCenterLocation;
/*
* Resource id of a subnet the nodes in this data center should have their
* network interfaces connected to. The subnet must be in the same region
* specified in 'dataCenterLocation' and must be able to route to the
* subnet specified in the cluster's 'delegatedManagementSubnetId'
* property. This resource id will be of the form
* '/subscriptions/<subscription id>/resourceGroups/<resource
* group>/providers/Microsoft.Network/virtualNetworks/<virtual
* network>/subnets/<subnet>'.
*/
@JsonProperty(value = "delegatedSubnetId")
private String delegatedSubnetId;
/*
* The number of nodes the data center should have. This is the desired
* number. After it is set, it may take some time for the data center to be
* scaled to match. To monitor the number of nodes and their status, use
* the fetchNodeStatus method on the cluster.
*/
@JsonProperty(value = "nodeCount")
private Integer nodeCount;
/*
* IP addresses for seed nodes in this data center. This is for reference.
* Generally you will want to use the seedNodes property on the cluster,
* which aggregates the seed nodes from all data centers in the cluster.
*/
@JsonProperty(value = "seedNodes", access = JsonProperty.Access.WRITE_ONLY)
private List<SeedNode> seedNodes;
/*
* A fragment of a cassandra.yaml configuration file to be included in the
* cassandra.yaml for all nodes in this data center. The fragment should be
* Base64 encoded, and only a subset of keys are allowed.
*/
@JsonProperty(value = "base64EncodedCassandraYamlFragment")
private String base64EncodedCassandraYamlFragment;
/*
* Key uri to use for encryption of managed disks. Ensure the system
* assigned identity of the cluster has been assigned appropriate
* permissions(key get/wrap/unwrap permissions) on the key.
*/
@JsonProperty(value = "managedDiskCustomerKeyUri")
private String managedDiskCustomerKeyUri;
/*
* Indicates the Key Uri of the customer key to use for encryption of the
* backup storage account.
*/
@JsonProperty(value = "backupStorageCustomerKeyUri")
private String backupStorageCustomerKeyUri;
/*
* Virtual Machine SKU used for data centers. Default value is
* Standard_DS14_v2
*/
@JsonProperty(value = "sku")
private String sku;
/*
* Disk SKU used for data centers. Default value is P30.
*/
@JsonProperty(value = "diskSku")
private String diskSku;
/*
* Number of disk used for data centers. Default value is 4.
*/
@JsonProperty(value = "diskCapacity")
private Integer diskCapacity;
/*
* If the azure data center has Availability Zone support, apply it to the
* Virtual Machine ScaleSet that host the cassandra data center virtual
* machines.
*/
@JsonProperty(value = "availabilityZone")
private Boolean availabilityZone;
/**
* Get the provisioningState property: The status of the resource at the time the operation was called.
*
* @return the provisioningState value.
*/
public ManagedCassandraProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Set the provisioningState property: The status of the resource at the time the operation was called.
*
* @param provisioningState the provisioningState value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withProvisioningState(ManagedCassandraProvisioningState provisioningState) {
this.provisioningState = provisioningState;
return this;
}
/**
* Get the dataCenterLocation property: The region this data center should be created in.
*
* @return the dataCenterLocation value.
*/
public String dataCenterLocation() {
return this.dataCenterLocation;
}
/**
* Set the dataCenterLocation property: The region this data center should be created in.
*
* @param dataCenterLocation the dataCenterLocation value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withDataCenterLocation(String dataCenterLocation) {
this.dataCenterLocation = dataCenterLocation;
return this;
}
/**
* Get the delegatedSubnetId property: Resource id of a subnet the nodes in this data center should have their
* network interfaces connected to. The subnet must be in the same region specified in 'dataCenterLocation' and must
* be able to route to the subnet specified in the cluster's 'delegatedManagementSubnetId' property. This resource
* id will be of the form '/subscriptions/<subscription id>/resourceGroups/<resource
* group>/providers/Microsoft.Network/virtualNetworks/<virtual network>/subnets/<subnet>'.
*
* @return the delegatedSubnetId value.
*/
public String delegatedSubnetId() {
return this.delegatedSubnetId;
}
/**
* Set the delegatedSubnetId property: Resource id of a subnet the nodes in this data center should have their
* network interfaces connected to. The subnet must be in the same region specified in 'dataCenterLocation' and must
* be able to route to the subnet specified in the cluster's 'delegatedManagementSubnetId' property. This resource
* id will be of the form '/subscriptions/<subscription id>/resourceGroups/<resource
* group>/providers/Microsoft.Network/virtualNetworks/<virtual network>/subnets/<subnet>'.
*
* @param delegatedSubnetId the delegatedSubnetId value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withDelegatedSubnetId(String delegatedSubnetId) {
this.delegatedSubnetId = delegatedSubnetId;
return this;
}
/**
* Get the nodeCount property: The number of nodes the data center should have. This is the desired number. After it
* is set, it may take some time for the data center to be scaled to match. To monitor the number of nodes and their
* status, use the fetchNodeStatus method on the cluster.
*
* @return the nodeCount value.
*/
public Integer nodeCount() {
return this.nodeCount;
}
/**
* Set the nodeCount property: The number of nodes the data center should have. This is the desired number. After it
* is set, it may take some time for the data center to be scaled to match. To monitor the number of nodes and their
* status, use the fetchNodeStatus method on the cluster.
*
* @param nodeCount the nodeCount value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withNodeCount(Integer nodeCount) {
this.nodeCount = nodeCount;
return this;
}
/**
* Get the seedNodes property: IP addresses for seed nodes in this data center. This is for reference. Generally you
* will want to use the seedNodes property on the cluster, which aggregates the seed nodes from all data centers in
* the cluster.
*
* @return the seedNodes value.
*/
public List<SeedNode> seedNodes() {
return this.seedNodes;
}
/**
* Get the base64EncodedCassandraYamlFragment property: A fragment of a cassandra.yaml configuration file to be
* included in the cassandra.yaml for all nodes in this data center. The fragment should be Base64 encoded, and only
* a subset of keys are allowed.
*
* @return the base64EncodedCassandraYamlFragment value.
*/
public String base64EncodedCassandraYamlFragment() {
return this.base64EncodedCassandraYamlFragment;
}
/**
* Set the base64EncodedCassandraYamlFragment property: A fragment of a cassandra.yaml configuration file to be
* included in the cassandra.yaml for all nodes in this data center. The fragment should be Base64 encoded, and only
* a subset of keys are allowed.
*
* @param base64EncodedCassandraYamlFragment the base64EncodedCassandraYamlFragment value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withBase64EncodedCassandraYamlFragment(
String base64EncodedCassandraYamlFragment) {
this.base64EncodedCassandraYamlFragment = base64EncodedCassandraYamlFragment;
return this;
}
/**
* Get the managedDiskCustomerKeyUri property: Key uri to use for encryption of managed disks. Ensure the system
* assigned identity of the cluster has been assigned appropriate permissions(key get/wrap/unwrap permissions) on
* the key.
*
* @return the managedDiskCustomerKeyUri value.
*/
public String managedDiskCustomerKeyUri() {
return this.managedDiskCustomerKeyUri;
}
/**
* Set the managedDiskCustomerKeyUri property: Key uri to use for encryption of managed disks. Ensure the system
* assigned identity of the cluster has been assigned appropriate permissions(key get/wrap/unwrap permissions) on
* the key.
*
* @param managedDiskCustomerKeyUri the managedDiskCustomerKeyUri value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withManagedDiskCustomerKeyUri(String managedDiskCustomerKeyUri) {
this.managedDiskCustomerKeyUri = managedDiskCustomerKeyUri;
return this;
}
/**
* Get the backupStorageCustomerKeyUri property: Indicates the Key Uri of the customer key to use for encryption of
* the backup storage account.
*
* @return the backupStorageCustomerKeyUri value.
*/
public String backupStorageCustomerKeyUri() {
return this.backupStorageCustomerKeyUri;
}
/**
* Set the backupStorageCustomerKeyUri property: Indicates the Key Uri of the customer key to use for encryption of
* the backup storage account.
*
* @param backupStorageCustomerKeyUri the backupStorageCustomerKeyUri value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withBackupStorageCustomerKeyUri(String backupStorageCustomerKeyUri) {
this.backupStorageCustomerKeyUri = backupStorageCustomerKeyUri;
return this;
}
/**
* Get the sku property: Virtual Machine SKU used for data centers. Default value is Standard_DS14_v2.
*
* @return the sku value.
*/
public String sku() {
return this.sku;
}
/**
* Set the sku property: Virtual Machine SKU used for data centers. Default value is Standard_DS14_v2.
*
* @param sku the sku value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withSku(String sku) {
this.sku = sku;
return this;
}
/**
* Get the diskSku property: Disk SKU used for data centers. Default value is P30.
*
* @return the diskSku value.
*/
public String diskSku() {
return this.diskSku;
}
/**
* Set the diskSku property: Disk SKU used for data centers. Default value is P30.
*
* @param diskSku the diskSku value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withDiskSku(String diskSku) {
this.diskSku = diskSku;
return this;
}
/**
* Get the diskCapacity property: Number of disk used for data centers. Default value is 4.
*
* @return the diskCapacity value.
*/
public Integer diskCapacity() {
return this.diskCapacity;
}
/**
* Set the diskCapacity property: Number of disk used for data centers. Default value is 4.
*
* @param diskCapacity the diskCapacity value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withDiskCapacity(Integer diskCapacity) {
this.diskCapacity = diskCapacity;
return this;
}
/**
* Get the availabilityZone property: If the azure data center has Availability Zone support, apply it to the
* Virtual Machine ScaleSet that host the cassandra data center virtual machines.
*
* @return the availabilityZone value.
*/
public Boolean availabilityZone() {
return this.availabilityZone;
}
/**
* Set the availabilityZone property: If the azure data center has Availability Zone support, apply it to the
* Virtual Machine ScaleSet that host the cassandra data center virtual machines.
*
* @param availabilityZone the availabilityZone value to set.
* @return the DataCenterResourceProperties object itself.
*/
public DataCenterResourceProperties withAvailabilityZone(Boolean availabilityZone) {
this.availabilityZone = availabilityZone;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (seedNodes() != null) {
seedNodes().forEach(e -> e.validate());
}
}
}
| 4,827 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.