repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
zssherman/beam_block
|
beam_block/config/tests/test_dict_config.py
|
""" Unit Tests for Beam Block's config/dict_config.py module. """
import pyart
from numpy.testing import assert_almost_equal
import beam_block
from beam_block.config import dict_config
radar_bb = pyart.io.read(beam_block.testing.SAMPLE_RADAR_BLOCK_DATA_FILE)
radar_low_elev = pyart.io.read(
beam_block.testing.SAMPLE_RADAR_LOW_ELEV_FILE)
def test_pbb_to_dict():
""" Unit test for the dict_config.pbb_to_dict function. """
pbb_all = radar_bb.fields['partial_beam_block']['data']
pbb_dict = dict_config.pbb_to_dict(pbb_all)
assert 'standard_name' in pbb_dict
assert 'long_name' in pbb_dict
assert 'coordinates' in pbb_dict
assert 'data' in pbb_dict
assert 'units' in pbb_dict
assert 'comment' in pbb_dict
assert pbb_dict['data'].shape == (360, 360)
assert_almost_equal(pbb_dict['data'], pbb_all, 3)
def test_cbb_to_dict():
""" Unit test for the dict_config.cbb_to_dict function. """
cbb_all = radar_bb.fields['cumulative_beam_block']['data']
cbb_dict = dict_config.cbb_to_dict(cbb_all)
assert 'standard_name' in cbb_dict
assert 'long_name' in cbb_dict
assert 'coordinates' in cbb_dict
assert 'data' in cbb_dict
assert 'units' in cbb_dict
assert 'comment' in cbb_dict
assert cbb_dict['data'].shape == (360, 360)
assert_almost_equal(cbb_dict['data'], cbb_all, 3)
def test_pbb_flags_to_dict():
""" Unit test for the dict_config.pbb_flags_to_dict function. """
pbb_flags = radar_bb.fields['partial_beam_block_flags']['data']
pbb_flags_dict = dict_config.pbb_flags_to_dict(pbb_flags)
assert 'standard_name' in pbb_flags_dict
assert 'long_name' in pbb_flags_dict
assert 'data' in pbb_flags_dict
assert 'units' in pbb_flags_dict
assert 'notes' in pbb_flags_dict
assert pbb_flags_dict['data'].shape == (360, 360)
assert_almost_equal(pbb_flags_dict['data'], pbb_flags, 3)
def test_cbb_flags_to_dict():
""" Unit test for the dict_config.cbb_flags_to_dict function. """
cbb_flags = radar_bb.fields['cumulative_beam_block_flags']['data']
cbb_flags_dict = dict_config.cbb_flags_to_dict(cbb_flags)
assert 'standard_name' in cbb_flags_dict
assert 'long_name' in cbb_flags_dict
assert 'data' in cbb_flags_dict
assert 'units' in cbb_flags_dict
assert 'notes' in cbb_flags_dict
assert cbb_flags_dict['data'].shape == (360, 360)
assert_almost_equal(cbb_flags_dict['data'], cbb_flags, 3)
def test_lowest_el_not_blocked_to_dict():
""" Unit test for the dict_config.lowest_el_not_blocked_to_dict
function. """
low_el_not_blocked_all = radar_low_elev.fields[
'lowest_elev_not_blocked']['data']
low_el_not_blocked_dict = dict_config.lowest_el_not_blocked_to_dict(
low_el_not_blocked_all)
assert 'standard_name' in low_el_not_blocked_dict
assert 'long_name' in low_el_not_blocked_dict
assert 'data' in low_el_not_blocked_dict
assert 'units' in low_el_not_blocked_dict
assert 'comment' in low_el_not_blocked_dict
assert low_el_not_blocked_dict['data'].shape == (360, 360)
assert_almost_equal(
low_el_not_blocked_dict['data'], low_el_not_blocked_all, 3)
|
Syrupz-UO/VERDICT
|
tools/verdict-back-ends/verdict-bundle/verdict-attack-defense-collector/src/main/java/com/ge/verdict/attackdefensecollector/adtree/ADNot.java
|
<reponame>Syrupz-UO/VERDICT
package com.ge.verdict.attackdefensecollector.adtree;
import com.ge.verdict.attackdefensecollector.CutSetGenerator;
import com.ge.verdict.attackdefensecollector.IndentedStringBuilder;
import com.ge.verdict.attackdefensecollector.Prob;
import java.util.Objects;
import org.logicng.formulas.Formula;
import org.logicng.formulas.FormulaFactory;
/** A negation of an attack-defense tree. */
public class ADNot extends ADTree {
/** The child attack-defense tree. */
private ADTree adtree;
/**
* Constructs a NOT attack-defense tree.
*
* @param adtree the child attack-defense tree
*/
public ADNot(ADTree adtree) {
this.adtree = adtree;
}
public ADTree child() {
return adtree;
}
@Override
public ADTree crush() {
// In either case, make sure to recursively crush the child
// Double-not elimination
if (adtree instanceof ADNot) {
return ((ADNot) adtree).adtree.crush();
}
return new ADNot(adtree.crush());
}
@Override
public Prob compute() {
// Simply NOT the child's probability
return Prob.not(adtree.compute());
}
@Override
public void prettyPrint(IndentedStringBuilder builder) {
// NOT child
builder.append("NOT ");
adtree.prettyPrint(builder);
}
@Override
public Formula toLogicNg(FormulaFactory factory, CutSetGenerator.Cache cache) {
return factory.not(adtree.toLogicNg(factory, cache));
}
@Override
public boolean equals(Object other) {
return other instanceof ADNot && ((ADNot) other).adtree.equals(adtree);
}
@Override
public int hashCode() {
return Objects.hash(adtree);
}
}
|
Gabriel-Goncalves/trybe-exercises
|
modulo_1/bloco_7/dia_1/parteII/exercicio02.js
|
const longestWord = (stringWords) => {
let arrayWords = stringWords.split(" ");
let biggest = arrayWords[0];
let positionBiggest = 0;
for (let index = 0; index < arrayWords.length; index += 1) {
if (arrayWords[index].length > biggest.length) {
biggest = arrayWords[index];
positionBiggest = index;
}
}
return biggest;
};
console.log(
longestWord("Antônio foi no banheiro e não sabemos o que aconteceu")
);
|
GongYuanLearning/javaee
|
spring_core/spring_aop/src/main/java/com/example/service/PackageService.java
|
<filename>spring_core/spring_aop/src/main/java/com/example/service/PackageService.java<gh_stars>0
package com.example.service;
public interface PackageService {
boolean getPackage(String name);
boolean sendPackage(String name);
}
|
saaltone/SANNet
|
src/core/layer/feedforward/FeedforwardLayer.java
|
<filename>src/core/layer/feedforward/FeedforwardLayer.java
/*
* SANNet Neural Network Framework
* Copyright (C) 2018 - 2021 <NAME>
*/
package core.layer.feedforward;
import core.layer.WeightSet;
import core.network.NeuralNetworkException;
import core.activation.ActivationFunction;
import core.layer.AbstractExecutionLayer;
import utils.configurable.DynamicParam;
import utils.configurable.DynamicParamException;
import utils.matrix.*;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashSet;
/**
* Implements non-recurrent feedforward layer.<br>
*
*/
public class FeedforwardLayer extends AbstractExecutionLayer {
/**
* Parameter name types for feedforward layer.
* - regulateDirectWeights: true if (direct) weights are regulated otherwise false. Default value true.<br>
* - splitOutputAtPosition: splits output at specific position.<br>
*
*/
private final static String paramNameTypes = "(regulateDirectWeights:BOOLEAN), " +
"(splitOutputAtPosition:INT)";
/**
* Class that defines weight set for layer.
*
*/
protected class FeedforwardWeightSet implements WeightSet, Serializable {
@Serial
private static final long serialVersionUID = 7859757124635021579L;
/**
* Weight matrix.
*
*/
private final Matrix weight;
/**
* Bias matrix.
*
*/
private final Matrix bias;
/**
* Set of weights.
*
*/
private final HashSet<Matrix> weights = new HashSet<>();
/**
* Constructor for weight set
*
* @param initialization weight initialization function.
* @param previousLayerWidth width of previous layer.
* @param layerWidth width of current layer.
* @param regulateDirectWeights if true direct weights are regulated.
*/
FeedforwardWeightSet(Initialization initialization, int previousLayerWidth, int layerWidth, boolean regulateDirectWeights) {
weight = new DMatrix(layerWidth, previousLayerWidth, initialization, "Weight");
bias = new DMatrix(layerWidth, 1, "bias");
weights.add(weight);
weights.add(bias);
registerWeight(weight, regulateDirectWeights, true);
registerWeight(bias, false, false);
}
/**
* Returns set of weights.
*
* @return set of weights.
*/
public HashSet<Matrix> getWeights() {
return weights;
}
/**
* Reinitializes weights.
*
*/
public void reinitialize() {
weight.initialize(initialization);
bias.reset();
}
/**
* Returns number of parameters.
*
* @return number of parameters.
*/
public int getNumberOfParameters() {
int numberOfParameters = 0;
for (Matrix weight : weights) numberOfParameters += weight.size();
return numberOfParameters;
}
}
/**
* Weight set.
*
*/
protected FeedforwardWeightSet weightSet;
/**
* Activation function for feedforward layer.
*
*/
protected final ActivationFunction activationFunction;
/**
* True if weights are regulated otherwise weights are not regulated.
*
*/
private boolean regulateDirectWeights;
/**
* Splits output at given position.
*
*/
private int splitOutputAtPosition;
/**
* Input matrix for procedure construction.
*
*/
private Matrix input;
/**
* Constructor for feedforward layer.
*
* @param layerIndex layer Index.
* @param activationFunction activation function used.
* @param initialization initialization function for weight.
* @param params parameters for feedforward layer.
* @throws NeuralNetworkException throws exception if setting of activation function fails.
* @throws DynamicParamException throws exception if parameter (params) setting fails.
* @throws MatrixException throws exception if custom function is attempted to be created with this constructor.
*/
public FeedforwardLayer(int layerIndex, ActivationFunction activationFunction, Initialization initialization, String params) throws NeuralNetworkException, DynamicParamException, MatrixException {
super (layerIndex, initialization, params);
this.activationFunction = activationFunction != null ? activationFunction : new ActivationFunction(UnaryFunctionType.RELU);
}
/**
* Initializes default params.
*
*/
public void initializeDefaultParams() {
super.initializeDefaultParams();
regulateDirectWeights = true;
splitOutputAtPosition = -1;
}
/**
* Returns parameters used for feedforward layer.
*
* @return parameters used for feedforward layer.
*/
public String getParamDefs() {
return super.getParamDefs() + ", " + FeedforwardLayer.paramNameTypes;
}
/**
* Sets parameters used for feedforward layer.<br>
* <br>
* Supported parameters are:<br>
* - regulateDirectWeights: true if (direct) weights are regulated otherwise false. Default value true.<br>
* - splitOutputAtPosition: splits output at specific position.<br>
*
* @param params parameters used for feedforward layer.
* @throws DynamicParamException throws exception if parameter (params) setting fails.
* @throws NeuralNetworkException throws exception if minimum layer dimensions are not met.
*/
public void setParams(DynamicParam params) throws DynamicParamException, NeuralNetworkException {
super.setParams(params);
if (params.hasParam("regulateDirectWeights")) regulateDirectWeights = params.getValueAsBoolean("regulateDirectWeights");
if (params.hasParam("splitOutputAtPosition")) splitOutputAtPosition = params.getValueAsInteger("splitOutputAtPosition");
}
/**
* Checks if layer is recurrent layer type.
*
* @return always false.
*/
public boolean isRecurrentLayer() { return false; }
/**
* Checks if layer works with recurrent layers.
*
* @return if true layer works with recurrent layers otherwise false.
*/
public boolean worksWithRecurrentLayer() {
return true;
}
/**
* Checks if layer is convolutional layer type.
*
* @return always false.
*/
public boolean isConvolutionalLayer() { return false; }
/**
* Returns if direct weights are regulated.
*
* @return true if direct weights are regulated otherwise false.
*/
protected boolean getRegulateDirectWeights() {
return regulateDirectWeights;
}
/**
* Returns weight set.
*
* @return weight set.
*/
protected WeightSet getWeightSet() {
return weightSet;
}
/**
* Initializes neural network layer weights.
*
*/
public void initializeWeights() {
weightSet = new FeedforwardWeightSet(initialization, getPreviousLayerWidth(), super.getLayerWidth(), regulateDirectWeights);
}
/**
* Returns input matrices for procedure construction.
*
* @param resetPreviousInput if true resets also previous input.
* @return input matrix for procedure construction.
* @throws MatrixException throws exception if matrix operation fails.
*/
public MMatrix getInputMatrices(boolean resetPreviousInput) throws MatrixException {
input = new DMatrix(getPreviousLayerWidth(), 1, Initialization.ONE, "Input");
if (getPreviousLayer().isBidirectional()) input = input.split(getPreviousLayerWidth() / 2, true);
return new MMatrix(input);
}
/**
* Builds forward procedure and implicitly builds backward procedure.
*
* @return output of forward procedure.
* @throws MatrixException throws exception if matrix operation fails.
*/
public MMatrix getForwardProcedure() throws MatrixException {
Matrix output = weightSet.weight.dot(input);
output = output.add(weightSet.bias);
if (splitOutputAtPosition == -1) output = output.apply(activationFunction);
else {
Matrix result = output.split(splitOutputAtPosition, true);
output.apply(result, activationFunction);
output = result;
}
output.setName("Output");
MMatrix outputs = new MMatrix(1, "Output");
outputs.put(0, output);
return outputs;
}
/**
* Returns matrices for which gradient is not calculated.
*
* @return matrices for which gradient is not calculated.
*/
protected HashSet<Matrix> getStopGradients() {
return new HashSet<>();
}
/**
* Returns constant matrices.
*
* @return constant matrices.
*/
protected HashSet<Matrix> getConstantMatrices() {
return new HashSet<>();
}
/**
* Returns number of truncated steps for gradient calculation. -1 means no truncation.
*
* @return number of truncated steps.
*/
protected int getTruncateSteps() {
return -1;
}
/**
* Returns layer details as string.
*
* @return layer details as string.
*/
protected String getLayerDetailsByName() {
return "Activation function: " + activationFunction.getName();
}
}
|
nwy140/TheWYGameDevelopmentFramework
|
WyFramework/Docs/html/dir_df9ef7e4299d5f4b8ec3a91d5783dd72.js
|
var dir_df9ef7e4299d5f4b8ec3a91d5783dd72 =
[
[ "Info.cs", "_info_8cs.html", [
[ "MechanicsAs", "class_m_d_a_1_1_mechanics_as.html", "class_m_d_a_1_1_mechanics_as" ]
] ]
];
|
gavin2lee/incubator-gl
|
docs/sourcecodes/OpenBridge-passos-ui/ob-monitor-web/src/main/java/com/harmazing/openbridge/alarm/service/impl/TemplateServiceImpl.java
|
<filename>docs/sourcecodes/OpenBridge-passos-ui/ob-monitor-web/src/main/java/com/harmazing/openbridge/alarm/service/impl/TemplateServiceImpl.java
package com.harmazing.openbridge.alarm.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.harmazing.framework.common.Page;
import com.harmazing.framework.util.StringUtil;
import com.harmazing.openbridge.alarm.dao.GroupMapper;
import com.harmazing.openbridge.alarm.dao.GroupTemplateMapper;
import com.harmazing.openbridge.alarm.dao.TemplateMapper;
import com.harmazing.openbridge.alarm.model.Template;
import com.harmazing.openbridge.alarm.model.vo.SysUserDTO;
import com.harmazing.openbridge.alarm.model.vo.TemplateEditDTO;
import com.harmazing.openbridge.alarm.model.vo.TemplateIndexDTO;
import com.harmazing.openbridge.alarm.service.ITemplateService;
/**
* Created by 李杨 [<EMAIL>] on 2016/8/3 17:35.
*/
@Service
@Transactional
public class TemplateServiceImpl implements ITemplateService {
@Autowired
private GroupMapper groupMapper;
@Autowired
private TemplateMapper templateMapper;
@Autowired
private GroupTemplateMapper groupTemplateMapper;
@Override
public List<Template> findAll() {
return templateMapper.findAll();
}
@Override
public List<TemplateIndexDTO> findAllDTO() {
return templateMapper.findAllDTO();
}
@Override
public Template findById(long id) {
return templateMapper.findById(id);
}
@Override
public void deleteById(long id){
templateMapper.deleteById(id);
groupTemplateMapper.deleteByTplId(id);
}
@Override
public Template insert(Template template){
if(StringUtil.isNull(template.getTplName())){
throw new RuntimeException("策略名不能为空!");
}
int sysTeam = templateMapper.getTplCountByName(template.getTplName(),template.getId());
if(sysTeam > 0){
throw new RuntimeException("已存在策略名,请修改!");
}
templateMapper.insert(template);
return template;
}
public int updateTplNameById(String tplName,long id){
if(StringUtil.isNull(tplName)){
throw new RuntimeException("策略名不能为空!");
}
int sysTeam = templateMapper.getTplCountByName(tplName,id);
if(sysTeam > 0){
throw new RuntimeException("已存在策略名,请修改!");
}
return templateMapper.updateTplNameById(tplName,id);
}
public int updateActionIdById(long actionId,long id){
return templateMapper.updateActionIdById(actionId,id);
}
@Override
public TemplateEditDTO findDtoById(long id){
return templateMapper.findDtoById(id);
}
public List<TemplateIndexDTO> findByGroupId(long id){
return templateMapper.findByGroupId(id);
}
@Override
@Transactional(readOnly = true)
public Page<Map<String, Object>> Page(Map<String, Object> params) {
Page<Map<String, Object>> xpage = Page.create(params);
xpage.setRecordCount(templateMapper.PageRecordCount(params));
xpage.addAll(templateMapper.Page(params));
return xpage;
}
@Override
public List<SysUserDTO> findUserByTid(long id) {
return templateMapper.findUserByTid(id);
}
@Override
public List<TemplateEditDTO> findDtoByGroupId(long id) {
return templateMapper.findDtoByGroupId(id);
}
@Override
public Page<TemplateEditDTO> findDtoPageByGroupId(long id, int pageNo, int pageSize) {
Page<TemplateEditDTO> page=new Page<TemplateEditDTO>(pageNo, pageSize);
page.addAll(templateMapper.findDtoPageByGroupId(id, page.getStart(), page.getPageSize()));
page.setRecordCount(templateMapper.getDToPageCountByGroupId(id));
return page;
}
public Template findByTplName(String tplName) {
return templateMapper.findByTplName(tplName);
}
}
|
tulinkry/teaching-sources-pa1-2016
|
02/square.c
|
<filename>02/square.c
#include <stdio.h>
/**
* Program na základní vstup a výstup.
*
* Program načte dvě celá čísla symbolizující strany dvou čtverců.
* Ověří, že první čtverec je větší než druhý a následně vypíše
* kolikrát se menší čtverec vejde do většího.
*/
int main ( void )
{
int firstSquare, secondSquare;
if ( ! ( scanf ( "%d %d", &firstSquare, &secondSquare ) == 2 &&
firstSquare >= secondSquare ) )
{
printf ( "Nespravny vstup.\n" );
return 3;
}
firstSquare *= firstSquare;
secondSquare *= secondSquare;
printf ( "M v V ~ %fx\n", ((double) firstSquare) / secondSquare );
return 0;
}
|
harfol/harthb
|
application/src/main/java/org/thingsboard/server/service/install/migrate/TsLatestMigrateService.java
|
package org.thingsboard.server.service.install.migrate;
public interface TsLatestMigrateService {
void migrate() throws Exception;
}
|
CarlLindblad/rsimulator
|
rsimulator-proxy/src/main/java/com/github/bjuvensjo/rsimulator/proxy/config/ProxyModule.java
|
<gh_stars>0
package com.github.bjuvensjo.rsimulator.proxy.config;
import java.io.File;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
/**
* CoreModule holds Guice configurations.
*
* @author <NAME>
*/
public class ProxyModule extends AbstractModule {
private Logger log = LoggerFactory.getLogger(ProxyModule.class);
/*
* (non-Javadoc)
*
* @see com.google.inject.AbstractModule#configure()
*/
@Override
protected void configure() {
// ***** Properties *****
URL resource = getClass().getResource("/URIMapper.txt");
if (resource == null) {
log.debug("No /URIMapper.txt resource exists.");
} else {
bind(File.class).annotatedWith(Names.named("uri-mappings")).toInstance(
new File(resource.getFile()));
}
}
}
|
stages-integrations/subversion-library
|
src/main/java/de/methodpark/subversion/xml/AbstractSaxExpression.java
|
/**
* Copyright © 2013-2018 shadowhunt (<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 de.methodpark.subversion.xml;
import java.util.Arrays;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.xml.sax.Attributes;
public abstract class AbstractSaxExpression<V> implements SaxExpression<V> {
private static final SaxExpression<?>[] NO_CHILDREN = new SaxExpression[0];
private static boolean doesElementMatch(final QName element, final String nameSpaceUri, final String localName) {
return doesNameSpaceUriMatch(element, nameSpaceUri) && doesLocalNameMatch(element, localName);
}
private static boolean doesLocalNameMatch(final QName element, final String localName) {
final String pLocalName = element.getLocalPart();
// * = any localName
return "*".equals(pLocalName) || pLocalName.equals(localName);
}
private static boolean doesNameSpaceUriMatch(final QName element, final String nameSpaceUri) {
final String pNameSpaceUri = element.getNamespaceURI();
// XMLConstants.NULL_NS_URI = any nameSpace
return XMLConstants.NULL_NS_URI.equals(pNameSpaceUri) || (pNameSpaceUri.equals(nameSpaceUri));
}
protected final SaxExpression<?>[] children;
private final QName[] path;
private int position = 0;
protected AbstractSaxExpression(final QName... path) {
this(path, NO_CHILDREN);
}
protected AbstractSaxExpression(final QName[] path, final SaxExpression<?>... children) {
this.path = Arrays.copyOf(path, path.length);
this.children = children;
}
@Override
public void clear() {
// nothing to do
}
@Override
public final void end(final String nameSpaceUri, final String localName, final int depth, final String text) {
if ((depth > position) || ((position - 1) >= path.length)) {
final int childDepth = depth - position;
for (final SaxExpression<?> child : children) {
child.end(nameSpaceUri, localName, childDepth, text);
}
return;
}
if (!doesElementMatch(path[position - 1], nameSpaceUri, localName)) {
return;
}
if (position == path.length) {
processEnd(nameSpaceUri, localName, text);
}
position--;
}
protected void processEnd(final String nameSpaceUri, final String localName, final String text) {
// nothing to do
}
protected void processStart(final String nameSpaceUri, final String localName, final Attributes attributes) {
// nothing to do
}
@Override
public final void reset() {
position = 0;
for (final SaxExpression<?> child : children) {
child.reset();
}
}
public void resetHandler() {
for (final SaxExpression<?> child : children) {
((AbstractSaxExpression<?>) child).resetHandler();
}
}
@Override
public final void start(final String nameSpaceUri, final String localName, final int depth, final Attributes attributes) {
if ((depth > position) || (position >= path.length)) {
final int childDepth = depth - position;
for (final SaxExpression<?> child : children) {
child.start(nameSpaceUri, localName, childDepth, attributes);
}
return;
}
if (!doesElementMatch(path[position], nameSpaceUri, localName)) {
return;
}
position++;
if (position == path.length) {
resetHandler();
processStart(nameSpaceUri, localName, attributes);
}
}
}
|
Pacien/ninja
|
js/helper-classes/RDGE/src/core/script/fx/ssao.js
|
/* <copyright>
Copyright (c) 2012, Motorola Mobility LLC.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Motorola Mobility LLC nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</copyright> */
var RDGE = RDGE || {};
RDGE.fx = RDGE.fx || {};
/**
* Implements SSAO.
* See http://www.gamedev.net/page/resources/_/reference/programming/140/lighting-and-shading/a-simple-and-practical-approach-to-ssao-r2753
* @param v2ScreenSize - size of the viewport in window coordinates
*/
RDGE.fx.fxSSAO = function (enHRDepth) {
function renderInitSSAO(quad) {
quad.shader = RDGE.createShader(RDGE.globals.gl, 'ssao_vshader', enHRDepth ? 'ssaohr_fshader' : 'ssao_fshader', ["vert", "texcoord"]);
quad.renderObj = new RDGE.RenderObject(quad.shader);
var quadBuf = getScreenAlignedQuad();
quad.vertBuffer = quadBuf.vertexObject;
quad.uvBuffer = quadBuf.texCoordObject;
quad.renderObj.addTexture("sColMap", 0, RDGE.UNIFORMTYPE.TEXTURE2D);
quad.renderObj.addTexture("sNormDepthMap", 1, RDGE.UNIFORMTYPE.TEXTURE2D);
quad.renderObj.addTexture("sRandMap", 2, RDGE.UNIFORMTYPE.TEXTURE2D);
if (enHRDepth)
quad.renderObj.addTexture("sHRDepthMap", 3, RDGE.UNIFORMTYPE.TEXTURE2D);
quad.renderObj.addBuffers(quad.vertBuffer, RDGE.globals.gl.ARRAY_BUFFER, 3, 0, RDGE.globals.gl.FLOAT);
quad.renderObj.addBuffers(quad.uvBuffer, RDGE.globals.gl.ARRAY_BUFFER, 2, 2, RDGE.globals.gl.FLOAT);
};
// Load random normal texture
this.randTexture = createTexture(RDGE.globals.gl, RDGE.globals.engine._assetPath + "images/random_normal.png");
RDGE.globals.gl.bindTexture(RDGE.globals.gl.TEXTURE_2D, this.randTexture);
RDGE.globals.gl.texParameteri(RDGE.globals.gl.TEXTURE_2D, RDGE.globals.gl.TEXTURE_MIN_FILTER, RDGE.globals.gl.LINEAR);
RDGE.globals.gl.texParameteri(RDGE.globals.gl.TEXTURE_2D, RDGE.globals.gl.TEXTURE_WRAP_S, RDGE.globals.gl.REPEAT);
RDGE.globals.gl.texParameteri(RDGE.globals.gl.TEXTURE_2D, RDGE.globals.gl.TEXTURE_WRAP_T, RDGE.globals.gl.REPEAT);
// Whether or not to use a high res depth texture
this.enHRDepth = enHRDepth;
// Quad for full screen pass
this.ssaoQuad = new RDGE.ScreenQuad(null);
this.ssaoQuad.initialize(renderInitSSAO);
// Set up uniforms
var activeCam = g_cameraManager.getActiveCamera();
this.v3FrustumFLT = activeCam.getFTR();
this.ssaoQuad.renderObj.addUniform("u_frustumFLT", this.v3FrustumFLT, RDGE.UNIFORMTYPE.FLOAT3);
this.v4ArtVals = [1.0, 1.0, 1.0, 1.0];
this.ssaoQuad.renderObj.addUniform("u_artVals", this.v4ArtVals, RDGE.UNIFORMTYPE.FLOAT4);
this.fRandMapSize = 64.0;
this.ssaoQuad.renderObj.addUniform("u_randMapSize", this.fRandMapSize, RDGE.UNIFORMTYPE.FLOAT);
this.v2ScreenSize = [1024, 1024];
this.ssaoQuad.renderObj.addUniform("u_screenSize", this.v2ScreenSize, RDGE.UNIFORMTYPE.FLOAT2);
};
/**
* Contributes SSAO to the passed offscreen surface, rendering to another surface.
* See http://www.gamedev.net/page/resources/_/reference/programming/140/lighting-and-shading/a-simple-and-practical-approach-to-ssao-r2753
* @param srcTexColor - color surface of rendered scene
* @param srcTexNormDepth - screenspace normal+depth surface for scene; {nx, ny, nz, depth}
* @param dstRenderTarget - where to put the result of SSAO
* @param sampleRadius -
* @param intensity -
* @param distScale -
* @param bias -
*/
RDGE.fx.fxSSAO.prototype.doSSAO = function (srcTexColor, srcTexNormDepth, srcTexHRDepth, dstRenderTarget, sampleRadius, intensity, distScale, bias) {
// Set art params and other uniforms
this.v4ArtVals[0] = sampleRadius;
this.v4ArtVals[1] = intensity;
this.v4ArtVals[2] = distScale;
this.v4ArtVals[3] = bias;
this.v2ScreenSize[0] = dstRenderTarget ? dstRenderTarget.frameBuffer.width : RDGE.globals.width;
this.v2ScreenSize[1] = dstRenderTarget ? dstRenderTarget.frameBuffer.height : RDGE.globals.height;
// Do ssao
RDGE.globals.gl.bindFramebuffer(RDGE.globals.gl.FRAMEBUFFER, dstRenderTarget ? dstRenderTarget.frameBuffer : null);
// gl.viewport(0, 0, 99999, 99999);
RDGE.globals.gl.clear(RDGE.globals.gl.COLOR_BUFFER_BIT);
RDGE.globals.gl.disable(RDGE.globals.gl.DEPTH_TEST);
RDGE.globals.gl.useProgram(this.ssaoQuad.shader);
this.ssaoQuad.renderObj.bindBuffers();
this.ssaoQuad.renderObj.bindTextures();
this.ssaoQuad.renderObj.bindUniforms();
RDGE.globals.gl.activeTexture(RDGE.globals.gl.TEXTURE0);
RDGE.globals.gl.bindTexture(RDGE.globals.gl.TEXTURE_2D, srcTexColor);
RDGE.globals.gl.activeTexture(RDGE.globals.gl.TEXTURE1);
RDGE.globals.gl.bindTexture(RDGE.globals.gl.TEXTURE_2D, srcTexNormDepth);
RDGE.globals.gl.activeTexture(RDGE.globals.gl.TEXTURE2);
RDGE.globals.gl.bindTexture(RDGE.globals.gl.TEXTURE_2D, this.randTexture);
if (this.enHRDepth) {
RDGE.globals.gl.activeTexture(RDGE.globals.gl.TEXTURE3);
RDGE.globals.gl.bindTexture(RDGE.globals.gl.TEXTURE_2D, srcTexHRDepth);
}
RDGE.globals.gl.activeTexture(RDGE.globals.gl.TEXTURE0);
RDGE.globals.gl.drawArrays(RDGE.globals.gl.TRIANGLES, 0, 6);
RDGE.globals.gl.enable(RDGE.globals.gl.DEPTH_TEST);
RDGE.globals.gl.useProgram(null);
return dstRenderTarget;
};
|
Nguyenkhanh98/React-Nestjs-Graphql
|
client/src/constants/list.js
|
export default {
menu: [
{
id: '1', path: '/dashboard', icon: 'home', label: 'Home', parent: '0',
},
{
id: '2', path: '', icon: 'envelope', label: 'Mailbox', parent: '0',
},
{
id: '3', path: '/app/inbox', icon: 'inbox', label: 'Inbox', parent: '2',
},
{
id: '7', path: '/app/compose', icon: 'at', label: 'Compose', parent: '2',
},
{
id: '4', path: '/app/permissions', icon: 'lock', label: 'Permissions', parent: '6',
},
{
id: '5', path: '/app/contacts', icon: 'address-book', label: 'Contacts', parent: '6',
},
{
id: '6', path: '', icon: 'pie-chart', label: 'User', parent: '0',
},
{
id: '7', path: '/app/profile', icon: 'user', label: 'Profile', parent: '6',
},
],
navMenu: [
{ path: '/app/profile', label: 'Profile' },
{ path: '/app/contacts', label: 'Contacts' },
{ path: '/app/inbox', label: 'Mailbox' },
{ divider: true },
{ path: '/login', label: 'Logout' },
],
};
|
INSO-TUWien/Binocular
|
lib/core/provider/travis-ci.js
|
<reponame>INSO-TUWien/Binocular
'use strict';
const _ = require('lodash');
const rp = require('request-promise');
const urlJoin = require('url-join');
const log = require('debug')('travis-ci');
const Paginator = require('../../paginator.js');
const escapeUtils = require('querystring').escape;
class TravisCI {
constructor(options) {
this.baseUrl = options.baseUrl;
this.tokens = options.tokens;
this.requestTimeout = options.requestTimeout;
this.currentBranch = options.branch;
this.count = 0;
this.stopping = false;
}
getProject(projectId) {
log('getProject(%o)', projectId);
return this.request(`/repo/${escapeUtils(projectId)}`).then(resp => resp.body);
}
getNotes(projectId, issueId) {
log('getNotes(%o, %o)', projectId, issueId);
return this.paginatedRequest(`/repo/${escapeUtils(projectId)}/request/${issueId}/messages`);
}
getPipelines(projectId) {
log('getPipelines(%o)', projectId);
return this.paginatedRequest(`/repo/${escapeUtils(projectId)}/builds`, {
qs: {
branch: {
name: this.currentBranch
}
}
});
}
getPipeline(projectId, pipelineId) {
log('getPipeline(%o, %o)', projectId, pipelineId);
return this.request(`/build/${pipelineId}`).then(resp => resp.body);
}
getPipelineJobs(projectId, pipelineId) {
log('getPipelineJobs(%o,%o)', projectId, pipelineId);
return this.request(`/build/${pipelineId}/jobs`).then(resp => resp.body.jobs || []);
}
isStopping() {
return this.stopping;
}
stop() {
this.stopping = true;
}
request(path, options) {
const header = {
'Travis-API-Version': 3
};
if (this.tokens.access) {
header.Authorization = `token ${this.tokens.access}`;
}
const query = {};
if (this.tokens.travis) {
query.token = this.tokens.travis;
}
const rpOptions = _.defaults(
{
uri: urlJoin(this.baseUrl, path),
json: true,
headers: header,
resolveWithFullResponse: true,
timeout: this.requestTimeout || 3000,
qs: _.defaults(query, (options || {}).qs)
},
options
);
return rp(rpOptions);
}
paginatedRequest(path, options) {
options = _.defaults({}, options);
return new Paginator(
(page, per_page) => {
if (this.stopping) {
return Promise.resolve({
body: _.merge(
{
'@pagination': {
count: this.count
}
},
{ builds: [] }
)
});
}
return this.request(path, {
qs: _.defaults({ offset: (page - 1) * per_page, limit: per_page }, (options || {}).qs)
});
},
resp => resp.body.builds || [],
resp => (this.count = parseInt(resp.body['@pagination'].count, 10))
);
}
}
module.exports = TravisCI;
|
TeWu/GamesBox
|
app/javascript/games/components/create_form.js
|
import React, { Component } from 'react'
import { Checkbox } from 'utils/form_fields'
import { game_session_path, private_game_session_path } from 'config/reverse_routes'
import { generateRandomId } from 'utils/random'
class CreateForm extends Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(e) {
e.preventDefault()
const isPrivate = e.target.elements["game-session-private"].checked
const pathGen = isPrivate ? private_game_session_path : game_session_path
this.props.history.push(pathGen(this.props.game, generateRandomId(7)))
}
render() {
return (
<form class="create-game-session" onSubmit={this.handleSubmit}>
<input type="submit" value={`Create new ${this.props.game.name} game session`} />
<Checkbox id="game-session-private" label="private" />
</form>
)
}
}
export default CreateForm
|
untgames/funner
|
extern/wcecompat/include/new.h
|
<reponame>untgames/funner<filename>extern/wcecompat/include/new.h
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
/***
*new.h - declarations and definitions for C++ memory allocation functions
*
*
*Purpose:
* Contains the declarations for C++ memory allocation functions.
*
* [Public]
*
****/
#if _MSC_VER > 1000 /*IFSTRIP=IGN*/
#pragma once
#endif
#ifndef _INC_NEW
#define _INC_NEW
#ifdef __cplusplus
#ifndef _MSC_EXTENSIONS
#include <new>
#endif
#if !defined(_WIN32)
#error ERROR: Only Win32 target supported!
#endif
/* Define _CRTIMP */
#ifndef _CRTIMP
#ifdef CRTDLL
#define _CRTIMP __declspec(dllexport)
#else /* ndef CRTDLL */
#ifdef _DLL
#define _CRTIMP __declspec(dllimport)
#else /* ndef _DLL */
#define _CRTIMP
#endif /* _DLL */
#endif /* CRTDLL */
#endif /* _CRTIMP */
/* Define __cdecl for non-Microsoft compilers */
#if ( !defined(_MSC_VER) && !defined(__cdecl) )
#define __cdecl
#endif
/* types and structures */
#ifndef _SIZE_T_DEFINED
#ifdef _WIN64
typedef unsigned __int64 size_t;
#else
typedef unsigned int size_t;
#endif
#define _SIZE_T_DEFINED
#endif
#ifdef _MSC_EXTENSIONS
typedef void (__cdecl * new_handler) ();
_CRTIMP new_handler __cdecl set_new_handler(new_handler);
#endif
#ifndef __PLACEMENT_NEW_INLINE
#define __PLACEMENT_NEW_INLINE
inline void *__cdecl operator new(size_t, void *_P)
{return (_P); }
#if _MSC_VER >= 1200 /*IFSTRIP=IGN*/
inline void __cdecl operator delete(void *, void *)
{return; }
#endif
#endif
/*
* new mode flag -- when set, makes malloc() behave like new()
*/
_CRTIMP int __cdecl _query_new_mode( void );
_CRTIMP int __cdecl _set_new_mode( int );
#ifndef _PNH_DEFINED
typedef int (__cdecl * _PNH)( size_t );
#define _PNH_DEFINED
#endif
_CRTIMP _PNH __cdecl _query_new_handler( void );
_CRTIMP _PNH __cdecl _set_new_handler( _PNH );
#endif /* __cplusplus */
#endif /* _INC_NEW */
|
Seyijo/youFarm
|
frontend/src/App.js
|
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { toast } from "react-toastify";
import "./App.scss";
const loading = () => (
<div className="animated fadeIn pt-3 text-center">Loading...</div>
);
// Containers
const AdminDashboard = React.lazy(() =>
import("./components/admin/CommonLayouts/DefaultLayout")
);
const UserDashboard = React.lazy(() =>
import("./components/user/CommonLayouts/DefaultLayout")
);
// Pages
const AdminLogin = React.lazy(() => import("./components/admin/Login/Login"));
const UserLogin = React.lazy(() => import("./components/user/Login/Login"));
const Register = React.lazy(() =>
import("./components/user/Register/Register")
);
const Page404 = React.lazy(() => import("./components/misc/Page404"));
toast.configure();
class App extends Component {
render() {
return (
<BrowserRouter>
<React.Suspense fallback={loading()}>
<Switch>
<Route
exact
path="/"
name="Home"
render={(props) => <UserLogin {...props} />}
/>
<Route
exact
path="/login"
name="Login Page"
render={(props) => <UserLogin {...props} />}
/>
<Route
exact
path="/admin/login"
name="Admin Login Page"
render={(props) => <AdminLogin {...props} />}
/>
<Route
exact
path="/register"
name="Register Page"
render={(props) => <Register {...props} />}
/>
<Route
path="/admin"
name="Dashboard"
render={(props) => <AdminDashboard {...props} />}
/>
<Route
path="/user"
name="Dashboard"
render={(props) => <UserDashboard {...props} />}
/>
<Route
path="*"
name="Page Not Found"
render={(props) => <Page404 {...props} />}
/>
</Switch>
</React.Suspense>
</BrowserRouter>
);
}
}
export default App;
|
FuyaoLi2017/leetcode
|
String/leetcode_809_ExpressiveWord.java
|
/*
Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii". In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
For some given string S, a query word is stretchy if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more.
For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has size less than 3. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If S = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = S.
Given a list of query words, return the number of words that are stretchy.
Example:
Input:
S = "heeellooo"
words = ["hello", "hi", "helo"]
Output: 1
Explanation:
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.
Notes:
0 <= len(S) <= 100.
0 <= len(words) <= 100.
0 <= len(words[i]) <= 100.
S and all words in words consist only of lowercase letters
*/
class Solution {
public int expressiveWords(String S, String[] words) {
int res = 0;
for (String W : words) if (check(S, W)) res++;
return res;
}
public boolean check(String S, String W) {
int n = S.length(), m = W.length(), i = 0, j = 0;
for (int i2 = 0, j2 = 0; i < n && j < m; i = i2, j = j2) {
if (S.charAt(i) != W.charAt(j)) return false;
// 复杂文件简单化, 脱去过程看结果, 用2对pointer跟踪变化
while (i2 < n && S.charAt(i2) == S.charAt(i)) i2++;
while (j2 < m && W.charAt(j2) == W.charAt(j)) j2++;
if (i2 - i != j2 - j && i2 - i < Math.max(3, j2 - j)) return false;
}
return i == n && j == m;
}
}
|
HazouPH/android_dalvik
|
vm/compiler/codegen/x86/lightcg/NcgAot.h
|
/*
* Copyright (C) 2010-2013 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.
*/
#ifndef _DALVIK_NCG_AOT
#define _DALVIK_NCG_AOT
int ncgAppGetEIP();
int get_eip_API();
int invokeInterpreter(bool fromApp);
int invokeNcg(bool fromApp);
int jumpToInterpNoChain();
int jumpToInterpPunt();
int jumpToExceptionThrown(int exceptionNum);
void callFuncPtr(int funcPtr, const char* funcName);
/** @brief generate a "call imm32"*/
void callFuncPtrImm(int funcPtr);
int call_helper_API(const char* helperName);
int load_imm_global_data_API(const char* dataName,
OpndSize size,
int reg, bool isPhysical);
int load_global_data_API(const char* dataName,
OpndSize size,
int reg, bool isPhysical);
int load_sd_global_data_API(const char* dataName,
int reg, bool isPhysical);
int load_fp_stack_global_data_API(const char* dataName,
OpndSize size);
#endif
|
divlaksh/questionnaire-new
|
node_modules/@progress/kendo-angular-grid/dist/es/rendering/details/details.service.js
|
import * as tslib_1 from "tslib";
import { Injectable } from '@angular/core';
import { ExpandStateService } from '../../common/expand-state.service';
import { DetailExpandEvent } from './detail-expand-event';
import { DetailCollapseEvent } from './detail-collapse-event';
/**
* @hidden
*/
var DetailsService = /** @class */ (function (_super) {
tslib_1.__extends(DetailsService, _super);
function DetailsService() {
return _super.call(this, true) || this;
}
DetailsService.prototype.emitEvent = function (args) {
var eventArg = new (args.expand ? DetailExpandEvent : DetailCollapseEvent)(args);
this.changes.next(eventArg);
return eventArg.isDefaultPrevented();
};
DetailsService.decorators = [
{ type: Injectable },
];
/** @nocollapse */
DetailsService.ctorParameters = function () { return []; };
return DetailsService;
}(ExpandStateService));
export { DetailsService };
|
SleepySanjinLi/main
|
src/test/java/seedu/address/model/calendarevent/UniqueCalendarEventListTest.java
|
<reponame>SleepySanjinLi/main
package seedu.address.model.calendarevent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_LECTURE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_VENUE_TUTORIAL;
import static seedu.address.testutil.TypicalEvents.CS2103_LECTURE;
import static seedu.address.testutil.TypicalEvents.TUTORIAL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.address.model.calendarevent.exceptions.CalendarEventNotFoundException;
import seedu.address.model.calendarevent.exceptions.DuplicateCalendarEventException;
import seedu.address.testutil.CalendarEventBuilder;
public class UniqueCalendarEventListTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private final UniqueCalendarEventList uniqueCalendarEventList = new UniqueCalendarEventList();
@Test
public void contains_nullPerson_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
uniqueCalendarEventList.contains(null);
}
@Test
public void contains_personNotInList_returnsFalse() {
assertFalse(uniqueCalendarEventList.contains(CS2103_LECTURE));
}
@Test
public void contains_personInList_returnsTrue() {
uniqueCalendarEventList.add(CS2103_LECTURE);
assertTrue(uniqueCalendarEventList.contains(CS2103_LECTURE));
}
@Test
public void contains_personWithSameIdentityFieldsInList_returnsTrue() {
uniqueCalendarEventList.add(CS2103_LECTURE);
CalendarEvent editedLecture =
new CalendarEventBuilder(CS2103_LECTURE).withTags(VALID_TAG_LECTURE)
.build();
assertTrue(uniqueCalendarEventList.contains(editedLecture));
}
@Test
public void add_nullPerson_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
uniqueCalendarEventList.add(null);
}
@Test
public void add_duplicatePerson_throwsDuplicatePersonException() {
uniqueCalendarEventList.add(CS2103_LECTURE);
thrown.expect(DuplicateCalendarEventException.class);
uniqueCalendarEventList.add(CS2103_LECTURE);
}
@Test
public void setPerson_nullTargetPerson_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
uniqueCalendarEventList.setCalendarEvent(null, CS2103_LECTURE);
}
@Test
public void setPerson_nullEditedPerson_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
uniqueCalendarEventList.setCalendarEvent(CS2103_LECTURE, null);
}
@Test
public void setPerson_targetPersonNotInList_throwsPersonNotFoundException() {
thrown.expect(CalendarEventNotFoundException.class);
uniqueCalendarEventList.setCalendarEvent(CS2103_LECTURE, CS2103_LECTURE);
}
@Test
public void setPerson_editedPersonIsSamePerson_success() {
uniqueCalendarEventList.add(CS2103_LECTURE);
uniqueCalendarEventList.setCalendarEvent(CS2103_LECTURE, CS2103_LECTURE);
UniqueCalendarEventList expectedUniqueCalendarEventList = new UniqueCalendarEventList();
expectedUniqueCalendarEventList.add(CS2103_LECTURE);
assertEquals(expectedUniqueCalendarEventList, uniqueCalendarEventList);
}
@Test
public void setPerson_editedPersonHasSameIdentity_success() {
uniqueCalendarEventList.add(CS2103_LECTURE);
CalendarEvent editedAlice =
new CalendarEventBuilder(CS2103_LECTURE).withVenue(VALID_VENUE_TUTORIAL).withTags(VALID_TAG_LECTURE)
.build();
uniqueCalendarEventList.setCalendarEvent(CS2103_LECTURE, editedAlice);
UniqueCalendarEventList expectedUniqueCalendarEventList = new UniqueCalendarEventList();
expectedUniqueCalendarEventList.add(editedAlice);
assertEquals(expectedUniqueCalendarEventList, uniqueCalendarEventList);
}
@Test
public void setPerson_editedPersonHasDifferentIdentity_success() {
uniqueCalendarEventList.add(CS2103_LECTURE);
uniqueCalendarEventList.setCalendarEvent(CS2103_LECTURE, TUTORIAL);
UniqueCalendarEventList expectedUniqueCalendarEventList = new UniqueCalendarEventList();
expectedUniqueCalendarEventList.add(TUTORIAL);
assertEquals(expectedUniqueCalendarEventList, uniqueCalendarEventList);
}
@Test
public void setPerson_editedPersonHasNonUniqueIdentity_throwsDuplicatePersonException() {
uniqueCalendarEventList.add(CS2103_LECTURE);
uniqueCalendarEventList.add(TUTORIAL);
thrown.expect(DuplicateCalendarEventException.class);
uniqueCalendarEventList.setCalendarEvent(CS2103_LECTURE, TUTORIAL);
}
@Test
public void remove_nullPerson_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
uniqueCalendarEventList.remove(null);
}
@Test
public void remove_personDoesNotExist_throwsPersonNotFoundException() {
thrown.expect(CalendarEventNotFoundException.class);
uniqueCalendarEventList.remove(CS2103_LECTURE);
}
@Test
public void remove_existingPerson_removesPerson() {
uniqueCalendarEventList.add(CS2103_LECTURE);
uniqueCalendarEventList.remove(CS2103_LECTURE);
UniqueCalendarEventList expectedUniqueCalendarEventList = new UniqueCalendarEventList();
assertEquals(expectedUniqueCalendarEventList, uniqueCalendarEventList);
}
@Test
public void setPersons_nullUniquePersonList_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
uniqueCalendarEventList.setCalendarEvents((UniqueCalendarEventList) null);
}
@Test
public void setPersons_uniquePersonList_replacesOwnListWithProvidedUniquePersonList() {
uniqueCalendarEventList.add(CS2103_LECTURE);
UniqueCalendarEventList expectedUniqueCalendarEventList = new UniqueCalendarEventList();
expectedUniqueCalendarEventList.add(TUTORIAL);
uniqueCalendarEventList.setCalendarEvents(expectedUniqueCalendarEventList);
assertEquals(expectedUniqueCalendarEventList, uniqueCalendarEventList);
}
@Test
public void setPersons_nullList_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
uniqueCalendarEventList.setCalendarEvents((List<CalendarEvent>) null);
}
@Test
public void setPersons_list_replacesOwnListWithProvidedList() {
uniqueCalendarEventList.add(CS2103_LECTURE);
List<CalendarEvent> calendarEventList = Collections.singletonList(TUTORIAL);
uniqueCalendarEventList.setCalendarEvents(calendarEventList);
UniqueCalendarEventList expectedUniqueCalendarEventList = new UniqueCalendarEventList();
expectedUniqueCalendarEventList.add(TUTORIAL);
assertEquals(expectedUniqueCalendarEventList, uniqueCalendarEventList);
}
@Test
public void setPersons_listWithDuplicatePersons_throwsDuplicatePersonException() {
List<CalendarEvent> listWithDuplicateCalendarEvents = Arrays.asList(CS2103_LECTURE, CS2103_LECTURE);
thrown.expect(DuplicateCalendarEventException.class);
uniqueCalendarEventList.setCalendarEvents(listWithDuplicateCalendarEvents);
}
@Test
public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() {
thrown.expect(UnsupportedOperationException.class);
uniqueCalendarEventList.asUnmodifiableObservableList().remove(0);
}
}
|
ruchikav95/Binder
|
client/src/view/auth/styles/Wrapper.js
|
<reponame>ruchikav95/Binder<gh_stars>1-10
import styled from 'styled-components';
const Wrapper = styled.div`
width: 100%;
min-height: 100vh;
height: 100vh;
display: flex;
justify-content: flex-end;
align-items: center;
position: relative;
background-size: contain;
&:before {
content: '';
width: 100%;
height: 100%;
display: flex;
background-color: rgba(0, 0, 0, 0.2);
position: absolute;
z-index: 1;
top: 0;
}
`;
export default Wrapper;
|
vegastristan1/nodegame-v7.1.0
|
node_modules/nodegame-widgets/lib/Widgets.js
|
/**
* # Widgets
* Copyright(c) 2021 <NAME>
* MIT Licensed
*
* Helper class to interact with nodeGame widgets
*
* http://nodegame.org
*/
(function(window, node) {
"use strict";
// ## Widgets constructor
function Widgets() {
var that;
/**
* ### Widgets.widgets
*
* Container of currently registered widgets
*
* @see Widgets.register
*/
this.widgets = {};
/**
* ### Widgets.instances
*
* Container of appended widget instances
*
* @see Widgets.append
* @see Widgets.lastAppended
*/
this.instances = [];
/**
* ### Widgets.lastAppended
*
* Reference to lastAppended widget
*
* @see Widgets.append
*/
this.lastAppended = null;
/**
* ### Widgets.docked
*
* List of docked widgets
*/
this.docked = [];
/**
* ### Widgets.dockedHidden
*
* List of hidden docked widgets (cause not enough space on page)
*/
this.dockedHidden = [];
/**
* ### Widgets.boxSelector
*
* A box selector widget containing hidden docked widgets
*/
this.boxSelector = null;
/**
* ### Widgets.collapseTarget
*
* Collapsed widgets are by default moved inside element
*/
this.collapseTarget = null;
that = this;
node.registerSetup('widgets', function(conf) {
var name, root, collapseTarget;
if (!conf) return;
// Add new widgets.
if (conf.widgets) {
for (name in conf.widgets) {
if (conf.widgets.hasOwnProperty(name)) {
that.register(name, conf.widgets[name]);
}
}
}
// Destroy all existing widgets.
if (conf.destroyAll) that.destroyAll();
// Append existing widgets.
if (conf.append) {
for (name in conf.append) {
if (conf.append.hasOwnProperty(name)) {
// Determine root.
root = conf.append[name].root;
if ('function' === typeof root) {
root = root();
}
else if ('string' === typeof root) {
root = W.getElementById(root);
}
if (!root) root = W.getScreen();
if (!root) {
node.warn('setup widgets: could not find a root ' +
'for widget ' + name + '. Requested: ' +
conf.append[name].root);
}
else {
that.append(name, root, conf.append[name]);
}
}
}
}
if (conf.collapseTarget) {
if ('function' === typeof conf.collapseTarget) {
collapseTarget = conf.collapseTarget();
}
else if ('string' === typeof conf.collapseTarget) {
collapseTarget = W.getElementById(conf.collapseTarget);
}
else if (J.isElement(conf.collapseTarget)) {
collapseTarget = conf.collapseTarget;
}
if (!collapseTarget) {
node.warn('setup widgets: could not find collapse target.');
}
else {
that.collapseTarget = collapseTarget;
}
}
return conf;
});
// Garbage collection.
node.on('FRAME_LOADED', function() {
node.widgets.garbageCollection();
});
node.info('node-widgets: loading');
}
// ## Widgets methods
/**
* ### Widgets.register
*
* Registers a new widget in the collection
*
* A name and a prototype class must be provided. All properties
* that are present in `node.Widget`, but missing in the prototype
* are added.
*
* Registered widgets can be loaded with Widgets.get or Widgets.append.
*
* @param {string} name The id under which to register the widget
* @param {function} w The widget to add
*
* @return {object|boolean} The registered widget,
* or FALSE if an error occurs
*/
Widgets.prototype.register = function(name, w) {
if ('string' !== typeof name) {
throw new TypeError('Widgets.register: name must be string. ' +
'Found: ' + name);
}
if ('function' !== typeof w) {
throw new TypeError('Widgets.register: w must be function.' +
'Found: ' + w);
}
if ('undefined' === typeof w.sounds) w.sounds = {};
if ('undefined' === typeof w.texts) w.texts = {};
// Add default properties to widget prototype.
J.mixout(w.prototype, new node.Widget());
this.widgets[name] = w;
return this.widgets[name];
};
/**
* ### Widgets.get
*
* Retrieves, instantiates and returns the specified widget
*
* Performs the following checkings:
*
* - dependencies, as specified by widget prototype, must exist
* - id, if specified in options, must be string
*
* and throws an error if conditions are not met.
*
* Adds the following properties to the widget object:
*
* - title: as specified by the user or as found in the prototype
* - footer: as specified by the user or as found in the prototype
* - context: as specified by the user or as found in the prototype
* - className: as specified by the user or as found in the prototype
* - id: user-defined id
* - wid: random unique widget id
* - hooks: object containing event listeners
* - disabled: boolean flag indicating the widget state, set to FALSE
* - highlighted: boolean flag indicating whether the panelDiv is
* highlighted, set to FALSE
* - collapsible: boolean flag, TRUE if the widget can be collapsed
* and a button to hide body is added to the header
* - collapsed: boolan flag, TRUE if widget is collapsed (body hidden)
* - closable: boolean flag, TRUE if the widget can be closed (destroyed)
*
* Calls the `listeners` method of the widget. Any event listener
* registered here will be automatically removed when the widget
* is destroyed. !Important: it will erase previously recorded changes
* by the event listener. If `options.listeners` is equal to false, the
* listeners method is skipped.
*
* A `.destroy` method is added to the widget that perform the
* following operations:
*
* - removes the widget from DOM (if it was appended),
* - removes listeners defined during the creation,
* - and remove the widget from Widget.instances,
* - invoke the event 'destroyed'.
*
*
* Finally, a reference to the widget is added in `Widgets.instances`.
*
* @param {string} widgetName The name of the widget to load
* @param {object} options Optional. Configuration options, will be
* mixed out with attributes in the `defaults` property
* of the widget prototype.
*
* @return {object} widget The requested widget
*
* @see Widgets.append
* @see Widgets.instances
*/
Widgets.prototype.get = function(widgetName, options) {
var WidgetPrototype, widget, changes, tmp;
if ('string' !== typeof widgetName) {
throw new TypeError('Widgets.get: widgetName must be string.' +
'Found: ' + widgetName);
}
if (!options) {
options = {};
}
else if ('object' !== typeof options) {
throw new TypeError('Widgets.get: ' + widgetName + ' options ' +
'must be object or undefined. Found: ' +
options);
}
if (options.storeRef === false) {
if (options.docked === true) {
throw new TypeError('Widgets.get: ' + widgetName +
'options.storeRef cannot be false ' +
'if options.docked is true.');
}
}
WidgetPrototype = J.getNestedValue(widgetName, this.widgets);
if (!WidgetPrototype) {
throw new Error('Widgets.get: ' + widgetName + ' not found');
}
node.info('creating widget ' + widgetName +
' v.' + WidgetPrototype.version);
if (!this.checkDependencies(WidgetPrototype)) {
throw new Error('Widgets.get: ' + widgetName + ' has unmet ' +
'dependencies');
}
// Create widget.
widget = new WidgetPrototype(options);
// Set ID.
tmp = options.id;
if ('undefined' !== typeof tmp) {
if ('number' === typeof tmp) tmp += '';
if ('string' === typeof tmp) {
if ('undefined' !== typeof options.idPrefix) {
if ('string' === typeof options.idPrefix &&
'number' !== typeof options.idPrefix) {
tmp = options.idPrefix + tmp;
}
else {
throw new TypeError('Widgets.get: options.idPrefix ' +
'must be string, number or ' +
'undefined. Found: ' +
options.idPrefix);
}
}
widget.id = tmp;
}
else {
throw new TypeError('Widgets.get: options.id must be ' +
'string, number or undefined. Found: ' +
tmp);
}
}
// Assign step id as widget id, if widget step and no custom id.
else if (options.widgetStep) {
widget.id = node.game.getStepId();
}
// Set prototype values or options values.
if ('undefined' !== typeof options.title) {
widget.title = options.title;
}
else if ('undefined' !== typeof WidgetPrototype.title) {
widget.title = WidgetPrototype.title;
}
else {
widget.title = ' ';
}
widget.panel = 'undefined' === typeof options.panel ?
WidgetPrototype.panel : options.panel;
widget.footer = 'undefined' === typeof options.footer ?
WidgetPrototype.footer : options.footer;
widget.className = WidgetPrototype.className;
if (J.isArray(options.className)) {
widget.className += ' ' + options.className.join(' ');
}
else if ('string' === typeof options.className) {
widget.className += ' ' + options.className;
}
else if ('undefined' !== typeof options.className) {
throw new TypeError('Widgets.get: className must be array, ' +
'string, or undefined. Found: ' +
options.className);
}
widget.context = 'undefined' === typeof options.context ?
WidgetPrototype.context : options.context;
widget.sounds = 'undefined' === typeof options.sounds ?
WidgetPrototype.sounds : options.sounds;
widget.texts = 'undefined' === typeof options.texts ?
WidgetPrototype.texts : options.texts;
widget.collapsible = options.collapsible || false;
widget.closable = options.closable || false;
widget.collapseTarget =
options.collapseTarget || this.collapseTarget || null;
widget.info = options.info || false;
widget.hooks = {
hidden: [],
shown: [],
collapsed: [],
uncollapsed: [],
disabled: [],
enabled: [],
destroyed: [],
highlighted: [],
unhighlighted: []
};
// By default destroy widget on exit step.
widget.destroyOnExit = options.destroyOnExit !== false;
// Required widgets require action from user, otherwise they will
// block node.done().
if (options.required ||
options.requiredChoice ||
'undefined' !== typeof options.correctChoice) {
// Flag required is undefined, if not set to false explicitely.
widget.required = true;
}
// Fixed properties.
// Widget Name.
widget.widgetName = widgetName;
// Add random unique widget id.
widget.wid = '' + J.randomInt(0,10000000000000000000);
// UI properties.
widget.disabled = null;
widget.highlighted = null;
widget.collapsed = null;
widget.hidden = null;
widget.docked = null;
// Properties that will modify the UI of the widget once appended.
if (options.disabled) widget._disabled = true;
if (options.highlighted) widget._highlighted = true;
if (options.collapsed) widget._collapsed = true;
if (options.hidden) widget._hidden = true;
if (options.docked) widget._docked = true;
// Call init.
widget.init(options);
// Call listeners.
if (options.listeners !== false) {
// TODO: future versions should pass the right event listener
// to the listeners method. However, the problem is that it
// does not have `on.data` methods, those are aliases.
// if ('undefined' === typeof options.listeners) {
// ee = node.getCurrentEventEmitter();
// }
// else if ('string' === typeof options.listeners) {
// if (options.listeners !== 'game' &&
// options.listeners !== 'stage' &&
// options.listeners !== 'step') {
//
// throw new Error('Widget.get: widget ' + widgetName +
// ' has invalid value for option ' +
// 'listeners: ' + options.listeners);
// }
// ee = node.events[options.listeners];
// }
// else {
// throw new Error('Widget.get: widget ' + widgetName +
// ' options.listeners must be false, string ' +
// 'or undefined. Found: ' + options.listeners);
// }
// Start recording changes.
node.events.setRecordChanges(true);
widget.listeners.call(widget);
// Get registered listeners, clear changes, and stop recording.
changes = node.events.getChanges(true);
node.events.setRecordChanges(false);
}
// If any listener was added or removed, the original situation will
// be restored when the widget is destroyed.
// The widget is also automatically removed from parent.
widget.destroy = function() {
var i, len, ee, eeName;
(function() {
try {
// Remove the widget's div from its parent.
if (widget.panelDiv && widget.panelDiv.parentNode) {
widget.panelDiv.parentNode.removeChild(widget.panelDiv);
}
}
catch(e) {
node.warn(widgetName + '.destroy: error caught: ' + e);
}
})();
if (changes) {
for (eeName in changes) {
if (changes.hasOwnProperty(eeName)) {
ee = changes[eeName];
i = -1, len = ee.added.length;
for ( ; ++i < len ; ) {
node.events.ee[eeName].off(ee.added[i].type,
ee.added[i].listener);
}
i = -1, len = changes[eeName].removed.length;
for ( ; ++i < len ; ) {
node.events.ee[eeName].on(ee.removed[i].type,
ee.removed[i].listener);
}
}
}
}
// Remove widget from current instances, if found.
if (widget.storeRef !== false) {
i = -1, len = node.widgets.instances.length;
for ( ; ++i < len ; ) {
if (node.widgets.instances[i].wid === widget.wid) {
node.widgets.instances.splice(i,1);
break;
}
}
// Remove from lastAppended.
if (node.widgets.lastAppended &&
node.widgets.lastAppended.wid === this.wid) {
node.warn('node.widgets.lastAppended destroyed.');
node.widgets.lastAppended = null;
}
}
// Remove from docked or adjust frame height.
if (this.docked) closeDocked(widget.wid, false);
else if (node.window) node.window.adjustFrameHeight(undefined, 120);
// In case the widget is stored somewhere else, set destroyed.
this.destroyed = true;
this.emit('destroyed');
};
// Store widget instance (e.g., used for destruction).
if (options.storeRef !== false) this.instances.push(widget);
else widget.storeRef = false;
return widget;
};
/**
* ### Widgets.append
*
* Appends a widget to the specified root element
*
* If no root element is specified the widget is append to the global root.
*
* The first parameter can be string representing the name of the widget or
* a valid widget already loaded, for example through Widgets.get.
* In the latter case, dependencies are checked, and it returns FALSE if
* conditions are not met.
*
* @param {string|object} w The name of the widget to load or a loaded
* widget object
* @param {object|string} root Optional. The HTML element (or its id) under
* which the widget will be appended. Default: `document.body` of the
* frame (if one is defined) or of the page
* @param {options} options Optional. Configuration options to be passed
* to the widget
*
* @return {object|boolean} The requested widget, or FALSE is an error
* occurs
*
* @see Widgets.get
*/
Widgets.prototype.append = function(w, root, options) {
var tmp;
if ('string' !== typeof w && 'object' !== typeof w) {
throw new TypeError('Widgets.append: w must be string or object. ' +
'Found: ' + w);
}
// If no root is defined, use the body element of the main frame,
// if none is found, use the document.body.
if (!root) {
root = W.getFrameDocument();
if (root) root = root.body;
if (!root) root = document.body;
}
else if ('string' === typeof root) {
tmp = W.gid(root);
if (!tmp) {
throw new Error('Widgets.append: element with id "' + root +
'" not found');
}
root = tmp;
}
if (!J.isElement(root)) {
throw new TypeError('Widgets.append: root must be HTMLElement, ' +
'string or undefined. Found: ' + root);
}
if (options && 'object' !== typeof options) {
throw new TypeError('Widgets.append: options must be object or ' +
'undefined. Found: ' + options);
}
// Init default values.
options = options || {};
if ('undefined' === typeof options.panel) {
if (root === W.getHeader()) options.panel = false;
}
// Check if it is a object (new widget).
// If it is a string is the name of an existing widget.
// In this case a dependencies check is done.
if ('string' === typeof w) w = this.get(w, options);
// Add panelDiv (with or without panel).
tmp = options.panel === false ? true : w.panel === false;
if (options.bootstrap5) {
// Bootstrap 5
tmp = {
className: tmp ? [ 'ng_widget', 'no-panel', w.className ] :
[ 'ng_widget', 'card', w.className ]
};
}
else {
// Bootstrap 3
tmp = {
className: tmp ? [ 'ng_widget', 'no-panel', w.className ] :
[ 'ng_widget', 'panel', 'panel-default', w.className ]
};
}
// Dock it.
if (options.docked || w._docked) {
tmp.className.push('docked');
this.docked.push(w);
w.docked = true;
}
// Add div inside widget.
w.panelDiv = W.get('div', tmp);
// Optionally add title (and div).
if (options.title !== false && w.title) {
if (options.bootstrap5) {
// Bootstrap 5.
tmp = options.panel === false ?
'no-panel-heading' : 'card-header';
}
else {
// Bootstrap 3.
tmp = options.panel === false ?
'no-panel-heading' : 'panel-heading';
}
w.setTitle(w.title, { className: tmp });
}
// Add body (with or without panel).
if (options.bootstrap5) {
// Bootstrap 5.
tmp = options.panel !== false ? 'card-body' : 'no-panel-body';
}
else {
// Bootstrap 3.
tmp = options.panel !== false ? 'panel-body' : 'no-panel-body';
}
w.bodyDiv = W.append('div', w.panelDiv, { className: tmp });
// Optionally add footer.
if (w.footer) {
if (options.bootstrap5) {
// Bootstrap 5.
tmp = options.panel === false ?
'no-panel-heading' : 'card-footer';
}
else {
// Bootstrap 3.
tmp = options.panel === false ?
'no-panel-heading' : 'panel-heading';
}
w.setFooter(w.footer);
}
// Optionally set context.
if (w.context) w.setContext(w.context);
// Adapt UI 1: visibility.
if (options.hidden || w._hidden) w.hide();
if (options.collapsed || w._collapsed) w.collapse();
// Append.
root.appendChild(w.panelDiv);
w.originalRoot = root;
w.append();
// Adapt UI 2: changes to elements. Needs to be after append, because
// some elements needs to be created by append and then disabled.
if (options.highlighted || w._highlighted) w.highlight();
if (options.disabled || w._disabled) w.disable();
if (w.docked) {
// Make sure the distance from the right side is correct.
setRightStyle(w);
}
else if (!w.isHidden() && !w.isCollapsed()) {
W.adjustFrameHeight(undefined, 150);
}
// Store reference of last appended widget (.get method set storeRef).
if (w.storeRef !== false) this.lastAppended = w;
return w;
};
Widgets.prototype.add = function(w, root, options) {
console.log('***Widgets.add is deprecated. Use ' +
'Widgets.append instead.***');
return this.append(w, root, options);
};
/**
* ### Widgets.isWidget
*
* Returns TRUE if the object is a widget-like
*
* @param {object} w The object to test
* @param {boolean} strict If TRUE, it checks if object is an
* instance of the Widget class. If FALSE, it just have to
* implement some of its methods (append and getValues).
*
* @return {boolean} TRUE, if the widget was found and destroyed.
*
* @see Widgets.get
*
* @api experimental
*/
Widgets.prototype.isWidget = function(w, strict) {
if (strict) return w instanceof node.Widget;
return ('object' === typeof w &&
'function' === typeof w.append &&
'function' === typeof w.getValues &&
// Used by widgets.append
'function' === typeof w.isHidden &&
'function' === typeof w.isCollapsed
);
};
/**
* ### Widgets.destroyAll
*
* Removes all widgets that have been created through Widgets.get
*
* @see Widgets.instances
*/
Widgets.prototype.destroyAll = function() {
var i, len;
i = -1, len = this.instances.length;
// Nested widgets can be destroyed by previous calls to destroy,
// and each call to destroy modify the array of instances.
for ( ; ++i < len ; ) {
this.instances[0].destroy();
}
this.lastAppended = null;
if (this.instances.length) {
node.warn('node.widgets.destroyAll: some widgets could ' +
'not be destroyed.');
}
};
/**
* ### Widgets.checkDependencies
*
* Checks if all the dependencies are already loaded
*
* Dependencies are searched for in the following objects:
*
* - window
* - node
* - this.widgets
* - node.window
*
* TODO: Check for version and other constraints.
*
* @param {object} w The widget to check
* @param {boolean} quiet Optional. If TRUE, no warning will be raised.
* Default: FALSE
* @return {boolean} TRUE, if all dependencies are met
*/
Widgets.prototype.checkDependencies = function(w, quiet) {
var parents, d, lib, found, i;
if (!w.dependencies) return true;
parents = [window, node, this.widgets, node.window];
d = w.dependencies;
for (lib in d) {
if (d.hasOwnProperty(lib)) {
found = false;
for (i = 0; i < parents.length; i++) {
if (J.getNestedValue(lib, parents[i])) {
found = true;
break;
}
}
if (!found) {
if (!quiet) checkDepErrMsg(w, lib);
return false;
}
}
}
return true;
};
/**
* ### Widgets.garbageCollection
*
* Destroys previously appended widgets nowehere to be found on page
*
* @return {array} res List of destroyed widgets
*/
Widgets.prototype.garbageCollection = (function() {
// Some IE were missing .contains, so we fallback gracefully.
function contains(target, widget) {
var parentNode;
if (target.contains) return target.contains(widget.panelDiv);
parentNode = widget.panelDiv.parentNode;
while (parentNode != null) {
if (parentNode == target) return true;
parentNode = parentNode.parentNode;
}
return false;
}
return function() {
var w, i, fd, res;
res = [];
fd = W.getFrameDocument();
w = node.widgets.instances;
for (i = 0; i < w.length; i++) {
// Check if widget is not on page any more.
if (w[i].isAppended() &&
(fd && !contains(fd, w[i])) &&
!contains(document.body, w[i])) {
res.push(w[i]);
w[i].destroy();
i--;
}
}
return res;
};
})();
/**
* ### Widgets.isActionRequired
*
* Returns TRUE, if any widget currently requires user action
*
* Loops trough all widgets that have the `required` flag.
*
* @param {object} opts Optional. Options to pass to Widget.getValues.
* Default: { markAttempt: false, highlight: false };
*
* @return {boolean} TRUE, if any widget requires action
*
* @see Widget.isActionRequired
*/
Widgets.prototype.isActionRequired = function(opts) {
var w, i, lastErrored, res;
w = node.widgets.instances;
res = false;
for (i = 0; i < w.length; i++) {
if (w[i].required) {
if (w[i].isActionRequired(opts)) {
res = true;
lastErrored = w[i];
}
}
}
// Scroll to error.
if (lastErrored && opts.highlight &&
'function' === typeof lastErrored.bodyDiv.scrollIntoView) {
lastErrored.bodyDiv.scrollIntoView({ behavior: 'smooth' });
}
return res;
};
// ## Helper functions
// ### checkDepErrMsg
//
// Prints out an error message for a dependency not met.
//
// @param {Widget} w The widget
// @param {string} d The dependency
function checkDepErrMsg(w, d) {
var name = w.name || w.id;
node.err(d + ' not found. ' + name + ' cannot be loaded');
}
// ### closeDocked
//
// Shifts docked widgets on page and remove a widget from the docked list
//
// @param {string} wid The widget id
// @param {boolean} remove TRUE, if widget should be removed from
// docked list. Default: FALSE.
//
// @return {boolean} TRUE if a widget with given wid was found
//
// @see BoxSelector
function closeDocked(wid, hide) {
var d, i, len, width, closed;
d = node.widgets.docked;
len = d.length;
for (i = 0; i < len; i++) {
if (width) {
d[i].panelDiv.style.right =
(getPxNum(d[i].panelDiv.style.right) - width) + 'px';
}
else if (d[i].wid === wid) {
width = d[i].dockedOffsetWidth;
// Remove from docked list.
closed = node.widgets.docked.splice(i, 1)[0];
if (hide) {
node.widgets.dockedHidden.push(closed);
closed.hide();
if (!node.widgets.boxSelector) {
node.widgets.boxSelector =
node.widgets.append('BoxSelector', document.body, {
className: 'docked-left',
getId: function(i) { return i.wid; },
getDescr: function(i) { return i.title; },
onclick: function(i, id) {
i.show();
// First add back to docked list,
// then set right style.
node.widgets.docked.push(i);
setRightStyle(i);
this.removeItem(id);
if (this.items.length === 0) {
this.destroy();
node.widgets.boxSelector = null;
}
},
});
}
node.widgets.boxSelector.addItem(closed);
}
// Decrement len and i.
len--;
i--;
}
}
return !!width;
}
// ### setRightStyle
//
// Sets the right property of the panelDiv of a docked widget
//
// May close docked widgets to make space to this one.
//
// @param {Widget} w The widget
function setRightStyle(w) {
var dockedMargin, safeMargin;
var lastDocked, right, ws, tmp;
safeMargin = 200;
dockedMargin = 20;
ws = node.widgets;
right = 0;
// The widget w has been already added to the docked list.
if (ws.docked.length > 1) {
lastDocked = ws.docked[(ws.docked.length - 2)];
right = getPxNum(lastDocked.panelDiv.style.right);
right += lastDocked.panelDiv.offsetWidth;
}
right += dockedMargin;
w.panelDiv.style.right = (right + "px");
// Check if there is enough space on page?
tmp = 0;
right += w.panelDiv.offsetWidth + safeMargin;
while (ws.docked.length > 1 &&
right > window.innerWidth &&
tmp < (ws.docked.length - 1)) {
// Make some space...
closeDocked(ws.docked[tmp].wid, true);
tmp++;
}
// Store final offsetWidth in widget, because we need it after
// it is destroyed.
w.dockedOffsetWidth = w.panelDiv.offsetWidth + dockedMargin;
}
// ### getPxNum
//
// Returns the numeric value of string containg 'px' at the end, e.g. 20px.
//
// @param {string} The value of a css property containing 'px' at the end
//
// @return {number} The numeric value of the css property
function getPxNum(str) {
return parseInt(str.substring(0, str.length - 2), 10);
}
// Expose Widgets to the global object.
node.widgets = new Widgets();
})(
// Widgets works only in the browser environment.
('undefined' !== typeof window) ? window : module.parent.exports.window,
('undefined' !== typeof window) ? window.node : module.parent.exports.node
);
|
liyanyanli/hch
|
vendor/github.com/astaxie/beego/orm/models_utils.go
|
// Copyright 2014 beego Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package orm
import (
"database/sql"
"fmt"
"reflect"
"strings"
"time"
)
// get reflect.Type name with package path.
func getFullName(typ reflect.Type) string {
return typ.PkgPath() + "." + typ.Name()
}
// get table name. method, or field name. auto snaked.
func getTableName(val reflect.Value) string {
ind := reflect.Indirect(val)
fun := val.MethodByName("TableName")
if fun.IsValid() {
vals := fun.Call([]reflect.Value{})
if len(vals) > 0 {
val := vals[0]
if val.Kind() == reflect.String {
return val.String()
}
}
}
return snakeString(ind.Type().Name())
}
// get table engine, mysiam or innodb.
func getTableEngine(val reflect.Value) string {
fun := val.MethodByName("TableEngine")
if fun.IsValid() {
vals := fun.Call([]reflect.Value{})
if len(vals) > 0 {
val := vals[0]
if val.Kind() == reflect.String {
return val.String()
}
}
}
return ""
}
// get table index from method.
func getTableIndex(val reflect.Value) [][]string {
fun := val.MethodByName("TableIndex")
if fun.IsValid() {
vals := fun.Call([]reflect.Value{})
if len(vals) > 0 {
val := vals[0]
if val.CanInterface() {
if d, ok := val.Interface().([][]string); ok {
return d
}
}
}
}
return nil
}
// get table unique from method
func getTableUnique(val reflect.Value) [][]string {
fun := val.MethodByName("TableUnique")
if fun.IsValid() {
vals := fun.Call([]reflect.Value{})
if len(vals) > 0 {
val := vals[0]
if val.CanInterface() {
if d, ok := val.Interface().([][]string); ok {
return d
}
}
}
}
return nil
}
// get snaked column name
func getColumnName(ft int, addrField reflect.Value, sf reflect.StructField, col string) string {
column := col
if col == "" {
column = snakeString(sf.Name)
}
switch ft {
case RelForeignKey, RelOneToOne:
if len(col) == 0 {
column = column + "_id"
}
case RelManyToMany, RelReverseMany, RelReverseOne:
column = sf.Name
}
return column
}
// return field type as type constant from reflect.Value
func getFieldType(val reflect.Value) (ft int, err error) {
switch val.Type() {
case reflect.TypeOf(new(int8)):
ft = TypeBitField
case reflect.TypeOf(new(int16)):
ft = TypeSmallIntegerField
case reflect.TypeOf(new(int32)),
reflect.TypeOf(new(int)):
ft = TypeIntegerField
case reflect.TypeOf(new(int64)):
ft = TypeBigIntegerField
case reflect.TypeOf(new(uint8)):
ft = TypePositiveBitField
case reflect.TypeOf(new(uint16)):
ft = TypePositiveSmallIntegerField
case reflect.TypeOf(new(uint32)),
reflect.TypeOf(new(uint)):
ft = TypePositiveIntegerField
case reflect.TypeOf(new(uint64)):
ft = TypePositiveBigIntegerField
case reflect.TypeOf(new(float32)),
reflect.TypeOf(new(float64)):
ft = TypeFloatField
case reflect.TypeOf(new(bool)):
ft = TypeBooleanField
case reflect.TypeOf(new(string)):
ft = TypeCharField
default:
elm := reflect.Indirect(val)
switch elm.Kind() {
case reflect.Int8:
ft = TypeBitField
case reflect.Int16:
ft = TypeSmallIntegerField
case reflect.Int32, reflect.Int:
ft = TypeIntegerField
case reflect.Int64:
ft = TypeBigIntegerField
case reflect.Uint8:
ft = TypePositiveBitField
case reflect.Uint16:
ft = TypePositiveSmallIntegerField
case reflect.Uint32, reflect.Uint:
ft = TypePositiveIntegerField
case reflect.Uint64:
ft = TypePositiveBigIntegerField
case reflect.Float32, reflect.Float64:
ft = TypeFloatField
case reflect.Bool:
ft = TypeBooleanField
case reflect.String:
ft = TypeCharField
default:
if elm.Interface() == nil {
panic(fmt.Errorf("%s is nil pointer, may be miss setting tag", val))
}
switch elm.Interface().(type) {
case sql.NullInt64:
ft = TypeBigIntegerField
case sql.NullFloat64:
ft = TypeFloatField
case sql.NullBool:
ft = TypeBooleanField
case sql.NullString:
ft = TypeCharField
case time.Time:
ft = TypeDateTimeField
}
}
}
if ft&IsFieldType == 0 {
err = fmt.Errorf("unsupport field type %s, may be miss setting tag", val)
}
return
}
// parse struct tag string
func parseStructTag(data string, attrs *map[string]bool, tags *map[string]string) {
attr := make(map[string]bool)
tag := make(map[string]string)
for _, v := range strings.Split(data, defaultStructTagDelim) {
v = strings.TrimSpace(v)
if supportTag[v] == 1 {
attr[v] = true
} else if i := strings.Index(v, "("); i > 0 && strings.Index(v, ")") == len(v)-1 {
name := v[:i]
if supportTag[name] == 2 {
v = v[i+1 : len(v)-1]
tag[name] = v
}
}
}
*attrs = attr
*tags = tag
}
|
jekyll-openui5/jekyll-openui5
|
assets/sap/ui/webc/main/Toast-dbg.js
|
/*!
* OpenUI5
* (c) Copyright 2009-2022 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.webc.main.Toast.
sap.ui.define([
"sap/ui/webc/common/WebComponent",
"./library",
"./thirdparty/Toast"
], function(WebComponent, library) {
"use strict";
var ToastPlacement = library.ToastPlacement;
/**
* Constructor for a new <code>Toast</code>.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @extends sap.ui.webc.common.WebComponent
* @class
*
* <h3>Overview</h3>
*
* The <code>sap.ui.webc.main.Toast</code> is a small, non-disruptive popup for success or information messages that disappears automatically after a few seconds.
*
* <h3>Usage</h3>
*
* <h4>When to use:</h4>
* <ul>
* <li>You want to display a short success or information message.</li>
* <li>You do not want to interrupt users while they are performing an action.</li>
* <li>You want to confirm a successful action.</li>
* </ul>
* <h4>When not to use:</h4>
* <ul>
* <li>You want to display error or warning message.</li>
* <li>You want to interrupt users while they are performing an action.</li>
* <li>You want to make sure that users read the message before they leave the page.</li>
* <li>You want users to be able to copy some part of the message text.</li>
* </ul>
*
* @author SAP SE
* @version 1.96.7
*
* @constructor
* @public
* @since 1.92.0
* @experimental Since 1.92.0 This control is experimental and its API might change significantly.
* @alias sap.ui.webc.main.Toast
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var Toast = WebComponent.extend("sap.ui.webc.main.Toast", {
metadata: {
library: "sap.ui.webc.main",
tag: "ui5-toast-ui5",
properties: {
/**
* Defines the duration in milliseconds for which component remains on the screen before it's automatically closed. <br>
* <br>
* <b>Note:</b> The minimum supported value is <code>500</code> ms and even if a lower value is set, the duration would remain <code>500</code> ms.
*/
duration: {
type: "int",
defaultValue: 3000
},
/**
* Defines the height of the control
*/
height: {
type: "sap.ui.core.CSSSize",
defaultValue: null,
mapping: "style"
},
/**
* Defines the placement of the component. <br>
* <br>
* Available options are:
* <ul>
* <li><code>TopStart</code></li>
* <li><code>TopCenter</code></li>
* <li><code>TopEnd</code></li>
* <li><code>MiddleStart</code></li>
* <li><code>MiddleCenter</code></li>
* <li><code>MiddleEnd</code></li>
* <li><code>BottomStart</code></li>
* <li><code>BottomCenter</code></li>
* <li><code>BottomEnd</code></li>
* </ul>
*/
placement: {
type: "sap.ui.webc.main.ToastPlacement",
defaultValue: ToastPlacement.BottomCenter
},
/**
* Defines the content of the control
*/
text: {
type: "string",
defaultValue: "",
mapping: "textContent"
},
/**
* Defines the width of the control
*/
width: {
type: "sap.ui.core.CSSSize",
defaultValue: null,
mapping: "style"
}
},
methods: ["show"]
}
});
/**
* Shows the component.
* @public
* @name sap.ui.webc.main.Toast#show
* @function
*/
return Toast;
});
|
wirmar/CubeCobra
|
models/report.js
|
const mongoose = require('mongoose');
// Deck schema
const reportSchema = mongoose.Schema({
commentid: String,
info: String,
reason: String,
reportee: String,
timePosted: Date,
});
reportSchema.index({
timePosted: -1,
});
reportSchema.index({
commentid: 1,
});
module.exports = mongoose.model('Report', reportSchema);
|
linch1996/java-programming
|
src/cn/blackme/reflect/Reflect.java
|
package cn.blackme.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* 反射
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Class类:任何一个类都是java.lang.Class类的实例对象,这个对象我们称为该类的类类型,这个实例有三种表示方式
* Class c1 = ClassName.class; // 任何一个类都有一个隐含的静态成员变量class,c1是ClassName类的类类型
* Class c2 = ClassName.getClass(); // 知道类的对象通过getClass方法获取,
* Class c3 = null; c3 = Class.ForName("com.ClassName")
*
* 通过类的类类型创建该类的对象实例,通过c1创建ClassName的实例
* (ClassName) c1.newInstance(); // 前提是要有无参数的构造方法,需要调用无参数的构造方法
*
* ------------------------------------------------------------------------------------------------------------
* 动态加载类
* Class.forName("类的全称") 不仅表示类的类类型,还表示了动态加载类
* 编译时刻加载类是静态加载类,运行时刻加载类是动态加载类
* new 创建对象是静态加载类,有编译时刻就需要加载所有的可能使用到的类,类不存在会报错。
* Class c = Class.forName(args[0]); c.newInstance();
* 功能性的类使用动态加载
*
* ------------------------------------------------------------------------------------------------------------
* 基本数据类型都存在类类型(void, int)
* Object.class getClass()是native声明的方法
*
* ------------------------------------------------------------------------------------------------------------
* 方法的反射
* 知道方法的名称和方法的参数列表才能唯一决定某个方法
* 反射操作: method.invoke(对象, 参数列表)
*
* ------------------------------------------------------------------------------------------------------------
* 泛型的本质
* 反射的操作都是编译之后的操作
* Java中集合的泛型,是防止错误输入的,只在编译阶段有效,绕过编译就无效了
*
*/
public class Reflect {
public static void main(String[] args) {
Class c1 = int.class;
Class c2 = String.class;
System.out.println("类的名称:" + c2.getName() + " " + c2.getSimpleName());
// getMethods()获取类的方法,所有的public函数,包括父类继承的
// getDeclaredMethods()获取的是所有该类声明的方法
Method[] methods = c2.getMethods();
for (Method method : methods) {
// 方法返回值类型的类类型
Class returnType = method.getReturnType();
// 方法的名称
String methodName = method.getName();
// 获取参数类型
Class[] paramTypes = method.getParameterTypes();
for (Class param : paramTypes) {
String paramName = param.getName();
}
}
/**
* 成员变量
* java.lang.reflect.Field类封装了关于成员变量的操作
* getFields()方法获取的是所有public的成员变量的信息
* getDeclaredFields()方法获取是是该类自己声明的成员变量的信息
*/
// Field[] fs = c1.getFields();
Field[] fs = c1.getDeclaredFields();
for (Field field : fs) {
// 成员变量的类型的类类型
Class fieldType = field.getType();
String typeName = fieldType.getName();
// 成员变量的名称
String fieldName = field.getName();
}
/**
* 获取对象的构造函数的信息
*/
// Constructor[] cs = c1.getConstructors();
Constructor[] cs = c1.getDeclaredConstructors();
for (Constructor constructor : cs) {
constructor.getName();
// 获取构造函数的参数列表的类类型
Class[] paramTypes = constructor.getParameterTypes();
for (Class c : paramTypes) {
c.getName();
}
}
// 获取类C的print方法,先获取类类型
C c = new C();
Class cc = c.getClass();
// 获取方法 根据方法名和参数列表
try {
// Method m = cc.getMethod("print", new Class[]{int.class, int.class});
Method m = cc.getMethod("print", int.class, int.class);
// 方法的反射操作,根c.print()调用效果一样,如果没有返回值返回null
// Object o = m.invoke(c, new Object[]{1, 2});
Object o = m.invoke(c, 1, 2);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
List<String> list = new ArrayList<>();
list.add("String");
Class listClass = list.getClass();
try {
Method m = listClass.getMethod("add", Object.class);
m.invoke(list, 100); // 可以add int 类型数据,无法foreach循环
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
class C {
public void print(int a, int b) {
System.out.println(a + b);
}
public void print(String a, String b) {
System.out.println(a.toUpperCase() + " " + b.toLowerCase());
}
}
|
boston-library/curator
|
spec/models/curator/filestreams/metadata_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require_relative '../shared/filestreams/file_set'
require_relative '../shared/filestreams/file_attachments'
require_relative '../shared/filestreams/thumbnailable'
require_relative '../shared/versionable'
RSpec.describe Curator::Filestreams::Metadata, type: :model do
subject { build(:curator_filestreams_metadata) }
it_behaves_like 'file_set'
it_behaves_like 'versionable'
describe 'Metadata Associations' do
it { is_expected.to belong_to(:file_set_of).
inverse_of(:metadata_file_sets).
class_name('Curator::DigitalObject').
required }
it_behaves_like 'thumbnailable'
it_behaves_like 'has_file_attachments' do
let(:has_one_file_attachments) { %i(metadata_ia metadata_ia_scan metadata_marc_xml metadata_mods metadata_oai) }
end
end
end
|
Tudor67/Competitive-Programming
|
LeetCode/Problems/Algorithms/#1386_CinemaSeatAllocation_sol1_greedy_and_bit_manipulation_O(RESERVED_SEATS)_time_O(RESERVED_SEATS)_extra_space_194ms_56MB.cpp
|
<reponame>Tudor67/Competitive-Programming
class Solution {
public:
int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) {
unordered_map<int, int> reservedMask;
for(const vector<int>& RC: reservedSeats){
int row = RC[0] - 1;
int col = RC[1] - 1;
reservedMask[row] |= (1 << col);
}
int maxGroups = 2 * n;
const int MASK29 = stoi("0111111110", NULL, 2);
const int MASK25 = stoi("0111100000", NULL, 2);
const int MASK47 = stoi("0001111000", NULL, 2);
const int MASK69 = stoi("0000011110", NULL, 2);
for(const pair<int, int>& P: reservedMask){
int mask = P.second;
if((mask & MASK29) == 0){
// ok
}else if((mask & MASK25) == 0 || (mask & MASK47) == 0 || (mask & MASK69) == 0){
maxGroups -= 1;
}else{
maxGroups -= 2;
}
}
return maxGroups;
}
};
|
uruzahe/carla
|
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/devices/MSDevice_Emissions.h
|
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file MSDevice_Emissions.h
/// @author <NAME>
/// @author <NAME>
/// @date Fri, 30.01.2009
///
// A device which collects vehicular emissions
/****************************************************************************/
#pragma once
#include <config.h>
#include <set>
#include <vector>
#include <map>
#include <utils/common/SUMOTime.h>
#include <utils/common/WrappingCommand.h>
#include <utils/emissions/PollutantsInterface.h>
#include <microsim/MSVehicle.h>
#include "MSVehicleDevice.h"
// ===========================================================================
// class declarations
// ===========================================================================
class MSLane;
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class MSDevice_Emissions
* @brief A device which collects vehicular emissions
*
* Each device collects the vehicular emissions / fuel consumption by being
* called each time step, computing the current values using
* PollutantsInterface, and aggregating them into internal storages over
* the complete journey.
*
* @see MSDevice
* @see PollutantsInterface
*/
class MSDevice_Emissions : public MSVehicleDevice {
public:
/** @brief Inserts MSDevice_Emissions-options
*/
static void insertOptions(OptionsCont& oc);
/** @brief Build devices for the given vehicle, if needed
*
* The options are read and evaluated whether emissions-devices shall be built
* for the given vehicle.
*
* For each seen vehicle, the global vehicle index is increased.
*
* The built device is stored in the given vector.
*
* @param[in] v The vehicle for which a device may be built
* @param[in, filled] into The vector to store the built device in
*/
static void buildVehicleDevices(SUMOVehicle& v, std::vector<MSVehicleDevice*>& into);
public:
/// @name Methods called on vehicle movement / state change, overwriting MSDevice
/// @{
/** @brief Computes current emission values and adds them to their sums
*
* The vehicle's current emission values
* are computed using the current velocity and acceleration.
*
* @param[in] veh The regarded vehicle
* @param[in] oldPos Position before the move-micro-timestep.
* @param[in] newPos Position after the move-micro-timestep.
* @param[in] newSpeed The vehicle's current speed
* @return false, if the vehicle is beyond the lane, true otherwise
* @see MSMoveReminder
* @see MSMoveReminder::notifyMove
* @see PollutantsInterface
*/
bool notifyMove(SUMOTrafficObject& veh, double oldPos, double newPos, double newSpeed);
/** @brief Computes idling emission values and adds them to the emission sums
*
* Idling implied by zero velocity, acceleration and slope
*
* @param[in] veh The vehicle
*
* @see MSMoveReminder::notifyMove
* @see PollutantsInterface
*/
bool notifyIdle(SUMOTrafficObject& veh);
/// @}
/// @brief return the name for this type of device
const std::string deviceName() const {
return "emissions";
}
/** @brief Called on writing tripinfo output
*
* @param[in] os The stream to write the information into
* @exception IOError not yet implemented
* @see MSDevice::tripInfoOutput
*/
void generateOutput(OutputDevice* tripinfoOut) const;
/// @brief Destructor.
~MSDevice_Emissions();
protected:
/** @brief Internal notification about the vehicle moves, see MSMoveReminder::notifyMoveInternal()
*
*/
void notifyMoveInternal(const SUMOTrafficObject& veh,
const double frontOnLane,
const double timeOnLane,
const double meanSpeedFrontOnLane,
const double meanSpeedVehicleOnLane,
const double travelledDistanceFrontOnLane,
const double travelledDistanceVehicleOnLane,
const double meanLengthOnLane);
private:
/** @brief Constructor
*
* @param[in] holder The vehicle that holds this device
* @param[in] id The ID of the device
*/
MSDevice_Emissions(SUMOVehicle& holder, const std::string& id);
private:
/// @brief Internal storages for pollutant/fuel sum in mg or ml
PollutantsInterface::Emissions myEmissions;
private:
/// @brief Invalidated copy constructor.
MSDevice_Emissions(const MSDevice_Emissions&);
/// @brief Invalidated assignment operator.
MSDevice_Emissions& operator=(const MSDevice_Emissions&);
};
|
The-Island/island-app
|
public/js/views/lists/notifications.js
|
/*
* Notification List view
*/
define([
'jQuery',
'Underscore',
'views/boiler/list',
'mps',
'rest',
'Spin',
'text!../../../templates/lists/notifications.html',
'collections/notifications',
'views/rows/notification'
], function ($, _, List, mps, rest, Spin, template, Collection, Row) {
return List.extend({
el: '.panel-content',
initialize: function (app, options) {
this.fetching = false;
this.nomore = false;
this.limit = 5;
this.template = _.template(template);
this.collection = new Collection();
this.Row = Row;
List.prototype.initialize.call(this, app, options);
this.subscriptions = [];
_.bindAll(this, 'collect', 'read', '_remove');
this.app.rpc.socket.on('notification.new', this.collect);
this.app.rpc.socket.on('notification.read', this.read);
this.app.rpc.socket.on('notification.removed', this._remove);
$(window).resize(_.debounce(_.bind(this.resize, this), 50));
this.spin = new Spin($('.notifications-spin', this.$el.parent()));
this.spin.start();
this.latest_list = this.app.profile.notes || {items: []};
this.collection.reset(this.latest_list.items);
},
collect: function (data) {
this.collection.unshift(data);
},
read: function (data) {
var view = _.find(this.views, function (v) {
return v.model.id === data.id;
});
if (view) {
view.update();
mps.publish('notification/change', []);
}
},
render: function (options) {
List.prototype.render.call(this, options);
if (this.collection.length > 0) {
_.delay(_.bind(function () {
this.checkHeight();
}, this), (this.collection.length + 1) * 30);
} else {
this.nomore = true;
$('<span class="empty-feed">No notifications.</span>').appendTo(this.$el);
this.spin.stop();
}
this.paginate();
return this;
},
renderLast: function (pagination) {
List.prototype.renderLast.call(this, pagination);
mps.publish('notification/change', []);
_.delay(_.bind(function () {
this.resize();
if (pagination !== true) {
this.checkHeight();
}
}, this), 20);
return this;
},
setup: function () {
this.spin.stop();
mps.publish('notification/change', []);
this.$el.parent().addClass('animated');
$('.container').addClass('animated');
this.resize();
List.prototype.setup.call(this);
},
destroy: function () {
this.unpaginate();
this.app.rpc.socket.removeListener('notification.new', this.collect);
this.app.rpc.socket.removeListener('notification.read', this.read);
this.app.rpc.socket.removeListener('notification.removed', this._remove);
return List.prototype.destroy.call(this);
},
_remove: function (data) {
var index = -1;
var view = _.find(this.views, function (v) {
++index;
return v.model.id === data.id;
});
if (view) {
this.views.splice(index, 1);
view._remove(_.bind(function () {
this.collection.remove(view.model);
this.checkHeight();
mps.publish('notification/change', []);
}, this));
}
},
// update the panel's height
resize: function () {
this.$el.parent().height($(window).height());
},
// check the panel's empty space and get more
// notes to fill it up.
checkHeight: function () {
wh = this.$el.parent().height();
so = this.spin.target.offset().top;
if (wh - so > this.spin.target.height() / 2) {
this.more();
}
},
// attempt to get more models (older) from server
more: function () {
// render models and handle edge cases
function updateUI(list) {
_.defaults(list, {items:[]});
this.latest_list = list;
var showingall = $('.list-spin .empty-feed', this.$el.parent());
if (list.items.length === 0) {
this.nomore = true;
this.spin.target.hide();
if (this.collection.length > 0) {
showingall.css('display', 'block');
} else {
showingall.hide();
$('<span class="empty-feed">No notifications.</span>')
.appendTo(this.$el);
}
} else {
_.each(list.items, _.bind(function (i) {
this.collection.push(i, {silent: true});
this.renderLast(true);
}, this));
}
_.delay(_.bind(function () {
this.spin.stop();
this.fetching = false;
if (list.items.length < this.limit) {
this.spin.target.hide();
if (!this.$('.empty-feed').is(':visible')) {
showingall.css('display', 'block');
}
}
}, this), (list.items.length + 1) * 30);
}
// already waiting on server
if (this.fetching) {
return;
}
// there are no more, don't call server
if (this.nomore || !this.latest_list.more) {
return updateUI.call(this, _.defaults({items:[]}, this.latest_list));
}
// get more
this.spin.start();
this.fetching = true;
rest.post('/api/notifications/list', {
subscriber_id: this.app.profile.member.id,
limit: this.limit,
cursor: this.latest_list.cursor,
}, _.bind(function (err, data) {
if (err) {
this.spin.stop();
this.fetching = false;
return console.error(err.stack);
}
// Add the items.
updateUI.call(this, data.notes);
}, this));
},
// init pagination
paginate: function () {
var wrap = this.$el.parent();
var paginate = _.debounce(_.bind(function (e) {
var pos = this.$el.height() - wrap.height() - wrap.scrollTop();
if (!this.nomore && pos < -this.spin.target.height() / 2) {
this.more();
}
}, this), 20);
wrap.scroll(paginate).resize(paginate);
},
unpaginate: function () {
$(window).unbind('scroll', this._paginate)
.unbind('resize', this._paginate);
}
});
});
|
yasincidem/educateus-project
|
app/components/Header/index.js
|
import { withStyles } from '@material-ui/core/styles';
import Header from './Header';
import Style from './style';
export default (withStyles(Style, { withTheme: true })(Header));
|
fynch3r/MyLeetCodeRecorder
|
src/com/mlcr/string/_709/Solution.java
|
<filename>src/com/mlcr/string/_709/Solution.java
package com.mlcr.string._709;
/**
* @program: MyLeetCodeRecorder
* @description: https://leetcode-cn.com/problems/to-lower-case/
* @author: fynch3r
* @create: 2021-06-12 15:31
**/
public class Solution {
public String toLowerCase(String str) {
char[] charArray = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c1 : charArray) {
int ascii = (int) c1;
if (ascii <= 'Z' && ascii >= 'A') {
ascii += 32;
}
sb.append((char) ascii);
}
return sb.toString();
}
}
|
OpenAgenda/agenda-portal
|
lib/utils/compile.js
|
<filename>lib/utils/compile.js
'use strict';
const _ = require('lodash');
const moment = require('moment');
const flatten = require('../events/flattenMultilingual');
const relativeTimings = require('../timings/relative');
const { applyContextLink } = require('../eventNavigation');
const links = require('../events/links');
/**
* event is parsed by parsers listed here before being provided to views
*/
module.exports = ({
// eventsPerPage,
lang, // language in which the event is to be flattened
eventParser // project-specific parser
// root // root path for portal
}) => (e, req = null, res = null, context = null) => [
flatten.bind(null, ['range', 'title', 'description', 'html'], lang),
_.partialRight(relativeTimings, { lang }),
_.partialRight(links, { lang, res }),
context ? applyContextLink.bind(null, { req, context }) : _.noop,
eventParser ? _.partialRight(eventParser, { lang, moment }) : _.noop
].reduce((result, fn) => fn(result), e);
|
thejellyfish/feather-icons
|
src/icons/IconAirplay.js
|
<reponame>thejellyfish/feather-icons
import React from 'react';
import Icon from '../Icon';
/* eslint-disable react/jsx-props-no-spreading */
export default function IconAirplay(props) {
return (
<Icon {...props}>
<path d="M5 17H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-1" />
<polygon points="12 15 17 21 7 21 12 15" />
</Icon>
);
}
|
XXBM/glmisWeb
|
src/main/java/com/glmis/domain/minor/Course.java
|
<reponame>XXBM/glmisWeb
package com.glmis.domain.minor;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
@Entity
@Table(name = "course")
@DynamicInsert(true)
@DynamicUpdate(true)
public class Course implements Serializable
{
@Id
@javax.persistence.Column(nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id;
/**
* 课程名
*/
@javax.persistence.Column(nullable = false)
protected String name;
/**
* 教材名
*/
@javax.persistence.Column(nullable = false)
protected String book;
/**
* 学分
*/
@javax.persistence.Column(nullable = false)
protected int credit;
/**
* 学时
*/
@javax.persistence.Column(nullable = false)
protected String period;
/**
* 学费
*/
protected String money;
/**
* 学生_课程
* 双向一对多
*/
@OneToMany(mappedBy = "course")
protected Collection<Student_Course> student_courses;
/**
* 教学计划
* 一对多
*/
@OneToMany(mappedBy = "course")
protected List<CoursePlan> coursePlanList;
public Course() {}
public Course(String name, String book, int credit, String period, String money, Collection<Student_Course> student_courses, List<CoursePlan> coursePlanList) {
this.name = name;
this.book = book;
this.credit = credit;
this.period = period;
this.money = money;
this.student_courses = student_courses;
this.coursePlanList = coursePlanList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public int getCredit() {
return credit;
}
public void setCredit(int credit) {
this.credit = credit;
}
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public Collection<Student_Course> getStudent_courses() {
return student_courses;
}
public void setStudent_courses(Collection<Student_Course> student_courses) {
this.student_courses = student_courses;
}
public List<CoursePlan> getCoursePlanList() {
return coursePlanList;
}
public void setCoursePlanList(List<CoursePlan> coursePlanList) {
this.coursePlanList = coursePlanList;
}
}
|
haizhenhan/Kepler
|
kernel/2.6.32/drivers/staging/rt3090/rt_ate.c
|
<filename>kernel/2.6.32/drivers/staging/rt3090/rt_ate.c
/*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2007, Ralink Technology, Inc.
*
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************
*/
#include "rt_config.h"
#ifdef RALINK_ATE
#ifdef RT30xx
#define ATE_BBP_REG_NUM 168
UCHAR restore_BBP[ATE_BBP_REG_NUM]={0};
#endif // RT30xx //
// 802.11 MAC Header, Type:Data, Length:24bytes
UCHAR TemplateFrame[24] = {0x08,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0x00,0xAA,0xBB,0x12,0x34,0x56,0x00,0x11,0x22,0xAA,0xBB,0xCC,0x00,0x00};
extern RTMP_RF_REGS RF2850RegTable[];
extern UCHAR NUM_OF_2850_CHNL;
extern FREQUENCY_ITEM FreqItems3020[];
extern UCHAR NUM_OF_3020_CHNL;
static CHAR CCKRateTable[] = {0, 1, 2, 3, 8, 9, 10, 11, -1}; /* CCK Mode. */
static CHAR OFDMRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, -1}; /* OFDM Mode. */
static CHAR HTMIXRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1}; /* HT Mix Mode. */
static INT TxDmaBusy(
IN PRTMP_ADAPTER pAd);
static INT RxDmaBusy(
IN PRTMP_ADAPTER pAd);
static VOID RtmpDmaEnable(
IN PRTMP_ADAPTER pAd,
IN INT Enable);
static VOID BbpSoftReset(
IN PRTMP_ADAPTER pAd);
static VOID RtmpRfIoWrite(
IN PRTMP_ADAPTER pAd);
static INT ATESetUpFrame(
IN PRTMP_ADAPTER pAd,
IN UINT32 TxIdx);
static INT ATETxPwrHandler(
IN PRTMP_ADAPTER pAd,
IN char index);
static INT ATECmdHandler(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg);
#ifndef RT30xx
static int CheckMCSValid(
IN UCHAR Mode,
IN UCHAR Mcs);
#endif // RT30xx //
#ifdef RT30xx
static int CheckMCSValid(
IN UCHAR Mode,
IN UCHAR Mcs,
IN BOOLEAN bRT2070);
#endif // RT30xx //
#ifdef RTMP_MAC_PCI
static VOID ATEWriteTxWI(
IN PRTMP_ADAPTER pAd,
IN PTXWI_STRUC pOutTxWI,
IN BOOLEAN FRAG,
IN BOOLEAN CFACK,
IN BOOLEAN InsTimestamp,
IN BOOLEAN AMPDU,
IN BOOLEAN Ack,
IN BOOLEAN NSeq, // HW new a sequence.
IN UCHAR BASize,
IN UCHAR WCID,
IN ULONG Length,
IN UCHAR PID,
IN UCHAR TID,
IN UCHAR TxRate,
IN UCHAR Txopmode,
IN BOOLEAN CfAck,
IN HTTRANSMIT_SETTING *pTransmit);
#endif // RTMP_MAC_PCI //
static VOID SetJapanFilter(
IN PRTMP_ADAPTER pAd);
#ifdef RALINK_28xx_QA
static inline INT DO_RACFG_CMD_ATE_START(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_STOP(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_RF_WRITE_ALL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_E2PROM_READ16(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_E2PROM_WRITE16(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_E2PROM_READ_ALL
(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_E2PROM_WRITE_ALL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_IO_READ(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_IO_WRITE(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_IO_READ_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_BBP_READ8(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_BBP_WRITE8(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_BBP_READ_ALL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_GET_NOISE_LEVEL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_GET_COUNTER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_CLEAR_COUNTER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_TX_START(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_GET_TX_STATUS(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_TX_STOP(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_RX_START(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_RX_STOP(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_RX_STOP(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_START_TX_CARRIER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_START_TX_CONT(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_START_TX_FRAME(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_BW(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_TX_POWER0(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_TX_POWER1(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_FREQ_OFFSET(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_GET_STATISTICS(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_RESET_COUNTER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SEL_TX_ANTENNA(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SEL_RX_ANTENNA(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_PREAMBLE(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_CHANNEL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_ADDR1(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_ADDR2(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_ADDR3(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_RATE(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_TX_FRAME_LEN(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_SET_TX_FRAME_COUNT(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_START_RX_FRAME(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_E2PROM_READ_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_E2PROM_WRITE_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_IO_WRITE_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_BBP_READ_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
static inline INT DO_RACFG_CMD_ATE_BBP_WRITE_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg
);
#endif // RALINK_28xx_QA //
#ifdef RTMP_MAC_PCI
static INT TxDmaBusy(
IN PRTMP_ADAPTER pAd)
{
INT result;
WPDMA_GLO_CFG_STRUC GloCfg;
RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word); // disable DMA
if (GloCfg.field.TxDMABusy)
result = 1;
else
result = 0;
return result;
}
static INT RxDmaBusy(
IN PRTMP_ADAPTER pAd)
{
INT result;
WPDMA_GLO_CFG_STRUC GloCfg;
RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word); // disable DMA
if (GloCfg.field.RxDMABusy)
result = 1;
else
result = 0;
return result;
}
static VOID RtmpDmaEnable(
IN PRTMP_ADAPTER pAd,
IN INT Enable)
{
BOOLEAN value;
ULONG WaitCnt;
WPDMA_GLO_CFG_STRUC GloCfg;
value = Enable > 0 ? 1 : 0;
// check DMA is in busy mode.
WaitCnt = 0;
while (TxDmaBusy(pAd) || RxDmaBusy(pAd))
{
RTMPusecDelay(10);
if (WaitCnt++ > 100)
break;
}
RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word); // disable DMA
GloCfg.field.EnableTxDMA = value;
GloCfg.field.EnableRxDMA = value;
RTMP_IO_WRITE32(pAd, WPDMA_GLO_CFG, GloCfg.word); // abort all TX rings
RTMPusecDelay(5000);
return;
}
#endif // RTMP_MAC_PCI //
static VOID BbpSoftReset(
IN PRTMP_ADAPTER pAd)
{
UCHAR BbpData = 0;
// Soft reset, set BBP R21 bit0=1->0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
BbpData |= 0x00000001; //set bit0=1
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
BbpData &= ~(0x00000001); //set bit0=0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
return;
}
static VOID RtmpRfIoWrite(
IN PRTMP_ADAPTER pAd)
{
// Set RF value 1's set R3[bit2] = [0]
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
RTMPusecDelay(200);
// Set RF value 2's set R3[bit2] = [1]
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 | 0x04));
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
RTMPusecDelay(200);
// Set RF value 3's set R3[bit2] = [0]
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
return;
}
#ifdef RT30xx
static int CheckMCSValid(
UCHAR Mode,
UCHAR Mcs,
BOOLEAN bRT2070)
#endif // RT30xx //
#ifndef RT30xx
static int CheckMCSValid(
IN UCHAR Mode,
IN UCHAR Mcs)
#endif // RT30xx //
{
INT i;
PCHAR pRateTab;
switch (Mode)
{
case 0:
pRateTab = CCKRateTable;
break;
case 1:
pRateTab = OFDMRateTable;
break;
case 2:
case 3:
#ifdef RT30xx
if (bRT2070)
pRateTab = OFDMRateTable;
else
#endif // RT30xx //
pRateTab = HTMIXRateTable;
break;
default:
ATEDBGPRINT(RT_DEBUG_ERROR, ("unrecognizable Tx Mode %d\n", Mode));
return -1;
break;
}
i = 0;
while (pRateTab[i] != -1)
{
if (pRateTab[i] == Mcs)
return 0;
i++;
}
return -1;
}
static INT ATETxPwrHandler(
IN PRTMP_ADAPTER pAd,
IN char index)
{
ULONG R;
CHAR TxPower;
UCHAR Bbp94 = 0;
BOOLEAN bPowerReduce = FALSE;
#ifdef RTMP_RF_RW_SUPPORT
UCHAR RFValue;
#endif // RTMP_RF_RW_SUPPORT //
#ifdef RALINK_28xx_QA
if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
{
/*
When QA is used for Tx, pAd->ate.TxPower0/1 and real tx power
are not synchronized.
*/
return 0;
}
else
#endif // RALINK_28xx_QA //
{
TxPower = index == 0 ? pAd->ate.TxPower0 : pAd->ate.TxPower1;
if (pAd->ate.Channel <= 14)
{
if (TxPower > 31)
{
// R3, R4 can't large than 31 (0x24), 31 ~ 36 used by BBP 94
R = 31;
if (TxPower <= 36)
Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
}
else if (TxPower < 0)
{
// R3, R4 can't less than 0, -1 ~ -6 used by BBP 94
R = 0;
if (TxPower >= -6)
Bbp94 = BBPR94_DEFAULT + TxPower;
}
else
{
// 0 ~ 31
R = (ULONG) TxPower;
Bbp94 = BBPR94_DEFAULT;
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%ld, BBP_R94=%d)\n", __FUNCTION__, TxPower, R, Bbp94));
}
else /* 5.5 GHz */
{
if (TxPower > 15)
{
// R3, R4 can't large than 15 (0x0F)
R = 15;
}
else if (TxPower < 0)
{
// R3, R4 can't less than 0
// -1 ~ -7
ASSERT((TxPower >= -7));
R = (ULONG)(TxPower + 7);
bPowerReduce = TRUE;
}
else
{
// 0 ~ 15
R = (ULONG) TxPower;
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%lu)\n", __FUNCTION__, TxPower, R));
}
//2008/09/10:KH adds to support 3070 ATE TX Power tunning real time<--
#ifdef RTMP_RF_RW_SUPPORT
if (IS_RT30xx(pAd))
{
// Set Tx Power
ATE_RF_IO_READ8_BY_REG_ID(pAd, RF_R12, (PUCHAR)&RFValue);
RFValue = (RFValue & 0xE0) | TxPower;
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R12, (UCHAR)RFValue);
ATEDBGPRINT(RT_DEBUG_TRACE, ("3070 or 2070:%s (TxPower=%d, RFValue=%x)\n", __FUNCTION__, TxPower, RFValue));
}
else
#endif // RTMP_RF_RW_SUPPORT //
{
if (pAd->ate.Channel <= 14)
{
if (index == 0)
{
// shift TX power control to correct RF(R3) register bit position
R = R << 9;
R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
pAd->LatchRfRegs.R3 = R;
}
else
{
// shift TX power control to correct RF(R4) register bit position
R = R << 6;
R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
pAd->LatchRfRegs.R4 = R;
}
}
else /* 5.5GHz */
{
if (bPowerReduce == FALSE)
{
if (index == 0)
{
// shift TX power control to correct RF(R3) register bit position
R = (R << 10) | (1 << 9);
R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
pAd->LatchRfRegs.R3 = R;
}
else
{
// shift TX power control to correct RF(R4) register bit position
R = (R << 7) | (1 << 6);
R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
pAd->LatchRfRegs.R4 = R;
}
}
else
{
if (index == 0)
{
// shift TX power control to correct RF(R3) register bit position
R = (R << 10);
R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
/* Clear bit 9 of R3 to reduce 7dB. */
pAd->LatchRfRegs.R3 = (R & (~(1 << 9)));
}
else
{
// shift TX power control to correct RF(R4) register bit position
R = (R << 7);
R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
/* Clear bit 6 of R4 to reduce 7dB. */
pAd->LatchRfRegs.R4 = (R & (~(1 << 6)));
}
}
}
RtmpRfIoWrite(pAd);
}
//2008/09/10:KH adds to support 3070 ATE TX Power tunning real time-->
return 0;
}
}
/*
==========================================================================
Description:
Set ATE operation mode to
0. ATESTART = Start ATE Mode
1. ATESTOP = Stop ATE Mode
2. TXCONT = Continuous Transmit
3. TXCARR = Transmit Carrier
4. TXFRAME = Transmit Frames
5. RXFRAME = Receive Frames
#ifdef RALINK_28xx_QA
6. TXSTOP = Stop Any Type of Transmition
7. RXSTOP = Stop Receiving Frames
#endif // RALINK_28xx_QA //
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
#ifdef RTMP_MAC_PCI
static INT ATECmdHandler(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UINT32 Value = 0;
UCHAR BbpData;
UINT32 MacData = 0;
PTXD_STRUC pTxD;
INT index;
UINT i = 0, atemode = 0;
PRXD_STRUC pRxD;
PRTMP_TX_RING pTxRing = &pAd->TxRing[QID_AC_BE];
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
#ifdef RT_BIG_ENDIAN
PTXD_STRUC pDestTxD;
TXD_STRUC TxD;
#endif
ATEDBGPRINT(RT_DEBUG_TRACE, ("===> ATECmdHandler()\n"));
ATEAsicSwitchChannel(pAd);
/* empty function */
AsicLockChannel(pAd, pAd->ate.Channel);
RTMPusecDelay(5000);
// read MAC_SYS_CTRL and backup MAC_SYS_CTRL value.
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
// Default value in BBP R22 is 0x0.
BbpData = 0;
// clean bit4 to stop continuous Tx production test.
MacData &= 0xFFFFFFEF;
// Enter ATE mode and set Tx/Rx Idle
if (!strcmp(arg, "ATESTART"))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: ATESTART\n"));
#if defined(LINUX) || defined(VXWORKS)
// check if we have removed the firmware
if (!(ATE_ON(pAd)))
{
NICEraseFirmware(pAd);
}
#endif // defined(LINUX) || defined(VXWORKS) //
atemode = pAd->ate.Mode;
pAd->ate.Mode = ATE_START;
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
if (atemode == ATE_TXCARR)
{
// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= 0xFFFFFF00; // clear bit7, bit6, bit[5~0]
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
}
else if (atemode == ATE_TXCARRSUPP)
{
// No Cont. TX set BBP R22 bit7=0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= ~(1 << 7); // set bit7=0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
// No Carrier Suppression set BBP R24 bit0=0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
BbpData &= 0xFFFFFFFE; // clear bit0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
}
/*
We should free some resource which was allocated
when ATE_TXFRAME , ATE_STOP, and ATE_TXCONT.
*/
else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
{
PRTMP_TX_RING pTxRing = &pAd->TxRing[QID_AC_BE];
if (atemode == ATE_TXCONT)
{
// No Cont. TX set BBP R22 bit7=0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= ~(1 << 7); // set bit7=0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
}
// Abort Tx, Rx DMA.
RtmpDmaEnable(pAd, 0);
for (i=0; i<TX_RING_SIZE; i++)
{
PNDIS_PACKET pPacket;
#ifndef RT_BIG_ENDIAN
pTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
#else
pDestTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
TxD = *pDestTxD;
pTxD = &TxD;
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
#endif
pTxD->DMADONE = 0;
pPacket = pTxRing->Cell[i].pNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNdisPacket as NULL after clear
pTxRing->Cell[i].pNdisPacket = NULL;
pPacket = pTxRing->Cell[i].pNextNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNextNdisPacket as NULL after clear
pTxRing->Cell[i].pNextNdisPacket = NULL;
#ifdef RT_BIG_ENDIAN
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
#endif
}
// Start Tx, RX DMA
RtmpDmaEnable(pAd, 1);
}
// reset Rx statistics.
pAd->ate.LastSNR0 = 0;
pAd->ate.LastSNR1 = 0;
pAd->ate.LastRssi0 = 0;
pAd->ate.LastRssi1 = 0;
pAd->ate.LastRssi2 = 0;
pAd->ate.AvgRssi0 = 0;
pAd->ate.AvgRssi1 = 0;
pAd->ate.AvgRssi2 = 0;
pAd->ate.AvgRssi0X8 = 0;
pAd->ate.AvgRssi1X8 = 0;
pAd->ate.AvgRssi2X8 = 0;
pAd->ate.NumOfAvgRssiSample = 0;
#ifdef RALINK_28xx_QA
// Tx frame
pAd->ate.bQATxStart = FALSE;
pAd->ate.bQARxStart = FALSE;
pAd->ate.seq = 0;
// counters
pAd->ate.U2M = 0;
pAd->ate.OtherData = 0;
pAd->ate.Beacon = 0;
pAd->ate.OtherCount = 0;
pAd->ate.TxAc0 = 0;
pAd->ate.TxAc1 = 0;
pAd->ate.TxAc2 = 0;
pAd->ate.TxAc3 = 0;
/*pAd->ate.TxHCCA = 0;*/
pAd->ate.TxMgmt = 0;
pAd->ate.RSSI0 = 0;
pAd->ate.RSSI1 = 0;
pAd->ate.RSSI2 = 0;
pAd->ate.SNR0 = 0;
pAd->ate.SNR1 = 0;
// control
pAd->ate.TxDoneCount = 0;
// TxStatus : 0 --> task is idle, 1 --> task is running
pAd->ate.TxStatus = 0;
#endif // RALINK_28xx_QA //
// Soft reset BBP.
BbpSoftReset(pAd);
#ifdef CONFIG_STA_SUPPORT
/* LinkDown() has "AsicDisableSync();" and "RTMP_BBP_IO_R/W8_BY_REG_ID();" inside. */
// LinkDown(pAd, FALSE);
// AsicEnableBssSync(pAd);
#if defined(LINUX) || defined(VXWORKS)
RTMP_OS_NETDEV_STOP_QUEUE(pAd->net_dev);
#endif // defined(LINUX) || defined(VXWORKS) //
/*
If we skip "LinkDown()", we should disable protection
to prevent from sending out RTS or CTS-to-self.
*/
ATEDisableAsicProtect(pAd);
RTMPStationStop(pAd);
#endif // CONFIG_STA_SUPPORT //
/* Disable Tx */
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 2);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
/* Disable Rx */
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
}
else if (!strcmp(arg, "ATESTOP"))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: ATESTOP\n"));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
// recover the MAC_SYS_CTRL register back
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
// disable Tx, Rx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= (0xfffffff3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
// abort Tx, RX DMA
RtmpDmaEnable(pAd, 0);
#ifdef LINUX
pAd->ate.bFWLoading = TRUE;
Status = NICLoadFirmware(pAd);
if (Status != NDIS_STATUS_SUCCESS)
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("NICLoadFirmware failed, Status[=0x%08x]\n", Status));
return FALSE;
}
#endif // LINUX //
pAd->ate.Mode = ATE_STOP;
/*
Even the firmware has been loaded,
we still could use ATE_BBP_IO_READ8_BY_REG_ID().
But this is not suggested.
*/
BbpSoftReset(pAd);
RTMP_ASIC_INTERRUPT_DISABLE(pAd);
NICInitializeAdapter(pAd, TRUE);
/*
Reinitialize Rx Ring before Rx DMA is enabled.
>>>RxCoherent<<< was gone !
*/
for (index = 0; index < RX_RING_SIZE; index++)
{
pRxD = (PRXD_STRUC) pAd->RxRing.Cell[index].AllocVa;
pRxD->DDONE = 0;
}
// We should read EEPROM for all cases.
NICReadEEPROMParameters(pAd, NULL);
NICInitAsicFromEEPROM(pAd);
AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
/* empty function */
AsicLockChannel(pAd, pAd->CommonCfg.Channel);
/* clear garbage interrupts */
RTMP_IO_WRITE32(pAd, INT_SOURCE_CSR, 0xffffffff);
/* Enable Interrupt */
RTMP_ASIC_INTERRUPT_ENABLE(pAd);
/* restore RX_FILTR_CFG */
#ifdef CONFIG_STA_SUPPORT
/* restore RX_FILTR_CFG due to that QA maybe set it to 0x3 */
RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL);
#endif // CONFIG_STA_SUPPORT //
// Enable Tx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value |= (1 << 2);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
// Enable Tx, Rx DMA.
RtmpDmaEnable(pAd, 1);
// Enable Rx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value |= (1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
#ifdef CONFIG_STA_SUPPORT
RTMPStationStart(pAd);
#endif // CONFIG_STA_SUPPORT //
#if defined(LINUX) || defined(VXWORKS)
RTMP_OS_NETDEV_START_QUEUE(pAd->net_dev);
#endif // defined(LINUX) || defined(VXWORKS) //
}
else if (!strcmp(arg, "TXCARR"))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCARR\n"));
pAd->ate.Mode = ATE_TXCARR;
// QA has done the following steps if it is used.
if (pAd->ate.bQATxStart == FALSE)
{
// Soft reset BBP.
BbpSoftReset(pAd);
// Carrier Test set BBP R22 bit7=1, bit6=1, bit[5~0]=0x01
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
BbpData |= 0x000000C1; //set bit7=1, bit6=1, bit[5~0]=0x01
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
// set MAC_SYS_CTRL(0x1004) Continuous Tx Production Test (bit4) = 1
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value = Value | 0x00000010;
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
}
}
else if (!strcmp(arg, "TXCONT"))
{
if (pAd->ate.bQATxStart == TRUE)
{
/*
set MAC_SYS_CTRL(0x1004) bit4(Continuous Tx Production Test)
and bit2(MAC TX enable) back to zero.
*/
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
MacData &= 0xFFFFFFEB;
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
// set BBP R22 bit7=0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= 0xFFFFFF7F; //set bit7=0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
}
/*
for TxCont mode.
Step 1: Send 50 packets first then wait for a moment.
Step 2: Send more 50 packet then start continue mode.
*/
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCONT\n"));
// Step 1: send 50 packets first.
pAd->ate.Mode = ATE_TXCONT;
pAd->ate.TxCount = 50;
/* Do it after Tx/Rx DMA is aborted. */
// pAd->ate.TxDoneCount = 0;
// Soft reset BBP.
BbpSoftReset(pAd);
// Abort Tx, RX DMA.
RtmpDmaEnable(pAd, 0);
// Fix can't smooth kick
{
RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * 0x10, &pTxRing->TxDmaIdx);
pTxRing->TxSwFreeIdx = pTxRing->TxDmaIdx;
pTxRing->TxCpuIdx = pTxRing->TxDmaIdx;
RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * 0x10, pTxRing->TxCpuIdx);
}
pAd->ate.TxDoneCount = 0;
/* Only needed if we have to send some normal frames. */
SetJapanFilter(pAd);
for (i = 0; (i < TX_RING_SIZE-1) && (i < pAd->ate.TxCount); i++)
{
PNDIS_PACKET pPacket;
UINT32 TxIdx = pTxRing->TxCpuIdx;
#ifndef RT_BIG_ENDIAN
pTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
#else
pDestTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
TxD = *pDestTxD;
pTxD = &TxD;
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
#endif
// Clean current cell.
pPacket = pTxRing->Cell[TxIdx].pNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNdisPacket as NULL after clear
pTxRing->Cell[TxIdx].pNdisPacket = NULL;
pPacket = pTxRing->Cell[TxIdx].pNextNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNextNdisPacket as NULL after clear
pTxRing->Cell[TxIdx].pNextNdisPacket = NULL;
#ifdef RT_BIG_ENDIAN
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
#endif
if (ATESetUpFrame(pAd, TxIdx) != 0)
break;
INC_RING_INDEX(pTxRing->TxCpuIdx, TX_RING_SIZE);
}
// Setup frame format.
ATESetUpFrame(pAd, pTxRing->TxCpuIdx);
// Start Tx, RX DMA.
RtmpDmaEnable(pAd, 1);
// Enable Tx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value |= (1 << 2);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
// Disable Rx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
#ifdef RALINK_28xx_QA
if (pAd->ate.bQATxStart == TRUE)
{
pAd->ate.TxStatus = 1;
}
#endif // RALINK_28xx_QA //
// kick Tx-Ring
RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * RINGREG_DIFF, pAd->TxRing[QID_AC_BE].TxCpuIdx);
RTMPusecDelay(5000);
// Step 2: send more 50 packets then start continue mode.
// Abort Tx, RX DMA.
RtmpDmaEnable(pAd, 0);
// Cont. TX set BBP R22 bit7=1
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData |= 0x00000080; //set bit7=1
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
pAd->ate.TxCount = 50;
// Fix can't smooth kick
{
RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * 0x10, &pTxRing->TxDmaIdx);
pTxRing->TxSwFreeIdx = pTxRing->TxDmaIdx;
pTxRing->TxCpuIdx = pTxRing->TxDmaIdx;
RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * 0x10, pTxRing->TxCpuIdx);
}
pAd->ate.TxDoneCount = 0;
SetJapanFilter(pAd);
for (i = 0; (i < TX_RING_SIZE-1) && (i < pAd->ate.TxCount); i++)
{
PNDIS_PACKET pPacket;
UINT32 TxIdx = pTxRing->TxCpuIdx;
#ifndef RT_BIG_ENDIAN
pTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
#else
pDestTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
TxD = *pDestTxD;
pTxD = &TxD;
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
#endif
// clean current cell.
pPacket = pTxRing->Cell[TxIdx].pNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNdisPacket as NULL after clear
pTxRing->Cell[TxIdx].pNdisPacket = NULL;
pPacket = pTxRing->Cell[TxIdx].pNextNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNextNdisPacket as NULL after clear
pTxRing->Cell[TxIdx].pNextNdisPacket = NULL;
#ifdef RT_BIG_ENDIAN
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
#endif
if (ATESetUpFrame(pAd, TxIdx) != 0)
break;
INC_RING_INDEX(pTxRing->TxCpuIdx, TX_RING_SIZE);
}
ATESetUpFrame(pAd, pTxRing->TxCpuIdx);
// Start Tx, RX DMA.
RtmpDmaEnable(pAd, 1);
// Enable Tx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value |= (1 << 2);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
// Disable Rx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
#ifdef RALINK_28xx_QA
if (pAd->ate.bQATxStart == TRUE)
{
pAd->ate.TxStatus = 1;
}
#endif // RALINK_28xx_QA //
// kick Tx-Ring.
RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * RINGREG_DIFF, pAd->TxRing[QID_AC_BE].TxCpuIdx);
RTMPusecDelay(500);
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
MacData |= 0x00000010;
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
}
else if (!strcmp(arg, "TXFRAME"))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXFRAME(Count=%d)\n", pAd->ate.TxCount));
pAd->ate.Mode |= ATE_TXFRAME;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
// Soft reset BBP.
BbpSoftReset(pAd);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
// Abort Tx, RX DMA.
RtmpDmaEnable(pAd, 0);
// Fix can't smooth kick
{
RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * 0x10, &pTxRing->TxDmaIdx);
pTxRing->TxSwFreeIdx = pTxRing->TxDmaIdx;
pTxRing->TxCpuIdx = pTxRing->TxDmaIdx;
RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * 0x10, pTxRing->TxCpuIdx);
}
pAd->ate.TxDoneCount = 0;
SetJapanFilter(pAd);
for (i = 0; (i < TX_RING_SIZE-1) && (i < pAd->ate.TxCount); i++)
{
PNDIS_PACKET pPacket;
UINT32 TxIdx = pTxRing->TxCpuIdx;
#ifndef RT_BIG_ENDIAN
pTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
#else
pDestTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
TxD = *pDestTxD;
pTxD = &TxD;
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
#endif
// Clean current cell.
pPacket = pTxRing->Cell[TxIdx].pNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNdisPacket as NULL after clear
pTxRing->Cell[TxIdx].pNdisPacket = NULL;
pPacket = pTxRing->Cell[TxIdx].pNextNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNextNdisPacket as NULL after clear
pTxRing->Cell[TxIdx].pNextNdisPacket = NULL;
#ifdef RT_BIG_ENDIAN
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
#endif
if (ATESetUpFrame(pAd, TxIdx) != 0)
break;
INC_RING_INDEX(pTxRing->TxCpuIdx, TX_RING_SIZE);
}
ATESetUpFrame(pAd, pTxRing->TxCpuIdx);
// Start Tx, Rx DMA.
RtmpDmaEnable(pAd, 1);
// Enable Tx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value |= (1 << 2);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
#ifdef RALINK_28xx_QA
// add this for LoopBack mode
if (pAd->ate.bQARxStart == FALSE)
{
// Disable Rx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
}
if (pAd->ate.bQATxStart == TRUE)
{
pAd->ate.TxStatus = 1;
}
#else
// Disable Rx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
#endif // RALINK_28xx_QA //
RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * RINGREG_DIFF, &pAd->TxRing[QID_AC_BE].TxDmaIdx);
// kick Tx-Ring.
RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * RINGREG_DIFF, pAd->TxRing[QID_AC_BE].TxCpuIdx);
pAd->RalinkCounters.KickTxCount++;
}
#ifdef RALINK_28xx_QA
else if (!strcmp(arg, "TXSTOP"))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXSTOP\n"));
atemode = pAd->ate.Mode;
pAd->ate.Mode &= ATE_TXSTOP;
pAd->ate.bQATxStart = FALSE;
// pAd->ate.TxDoneCount = pAd->ate.TxCount;
if (atemode == ATE_TXCARR)
{
// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
}
else if (atemode == ATE_TXCARRSUPP)
{
// No Cont. TX set BBP R22 bit7=0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= ~(1 << 7); //set bit7=0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
// No Carrier Suppression set BBP R24 bit0=0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
BbpData &= 0xFFFFFFFE; //clear bit0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
}
/*
We should free some resource which was allocated
when ATE_TXFRAME, ATE_STOP, and ATE_TXCONT.
*/
else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
{
PRTMP_TX_RING pTxRing = &pAd->TxRing[QID_AC_BE];
if (atemode == ATE_TXCONT)
{
// No Cont. TX set BBP R22 bit7=0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
BbpData &= ~(1 << 7); //set bit7=0
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
}
// Abort Tx, Rx DMA.
RtmpDmaEnable(pAd, 0);
for (i=0; i<TX_RING_SIZE; i++)
{
PNDIS_PACKET pPacket;
#ifndef RT_BIG_ENDIAN
pTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
#else
pDestTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
TxD = *pDestTxD;
pTxD = &TxD;
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
#endif
pTxD->DMADONE = 0;
pPacket = pTxRing->Cell[i].pNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNdisPacket as NULL after clear
pTxRing->Cell[i].pNdisPacket = NULL;
pPacket = pTxRing->Cell[i].pNextNdisPacket;
if (pPacket)
{
PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
}
// Always assign pNextNdisPacket as NULL after clear
pTxRing->Cell[i].pNextNdisPacket = NULL;
#ifdef RT_BIG_ENDIAN
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
#endif
}
// Enable Tx, Rx DMA
RtmpDmaEnable(pAd, 1);
}
// TxStatus : 0 --> task is idle, 1 --> task is running
pAd->ate.TxStatus = 0;
// Soft reset BBP.
BbpSoftReset(pAd);
// Disable Tx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 2);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
}
else if (!strcmp(arg, "RXSTOP"))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXSTOP\n"));
atemode = pAd->ate.Mode;
pAd->ate.Mode &= ATE_RXSTOP;
pAd->ate.bQARxStart = FALSE;
// pAd->ate.TxDoneCount = pAd->ate.TxCount;
if (atemode == ATE_TXCARR)
{
;
}
else if (atemode == ATE_TXCARRSUPP)
{
;
}
/*
We should free some resource which was allocated
when ATE_TXFRAME, ATE_STOP, and ATE_TXCONT.
*/
else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
{
if (atemode == ATE_TXCONT)
{
;
}
}
// Soft reset BBP.
BbpSoftReset(pAd);
// Disable Rx
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
}
#endif // RALINK_28xx_QA //
else if (!strcmp(arg, "RXFRAME"))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXFRAME\n"));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
pAd->ate.Mode |= ATE_RXFRAME;
// Disable Tx of MAC block.
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value &= ~(1 << 2);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
// Enable Rx of MAC block.
RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
Value |= (1 << 3);
RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
}
else
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: Invalid arg!\n"));
return FALSE;
}
RTMPusecDelay(5000);
ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== ATECmdHandler()\n"));
return TRUE;
}
/*=======================End of RTMP_MAC_PCI =======================*/
#endif // RTMP_MAC_PCI //
INT Set_ATE_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
if (ATECmdHandler(pAd, arg))
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Success\n"));
return TRUE;
}
else
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Failed\n"));
return FALSE;
}
}
/*
==========================================================================
Description:
Set ATE ADDR1=DA for TxFrame(AP : To DS = 0 ; From DS = 1)
or
Set ATE ADDR3=DA for TxFrame(STA : To DS = 1 ; From DS = 0)
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_DA_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
PSTRING value;
INT i;
// Mac address acceptable format 01:02:03:04:05:06 length 17
if (strlen(arg) != 17)
return FALSE;
for (i = 0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
{
/* sanity check */
if ((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))))
{
return FALSE;
}
#ifdef CONFIG_STA_SUPPORT
AtoH(value, &pAd->ate.Addr3[i++], 1);
#endif // CONFIG_STA_SUPPORT //
}
/* sanity check */
if (i != 6)
{
return FALSE;
}
#ifdef CONFIG_STA_SUPPORT
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_DA_Proc (DA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr3[0],
pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]));
#endif // CONFIG_STA_SUPPORT //
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_DA_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE ADDR3=SA for TxFrame(AP : To DS = 0 ; From DS = 1)
or
Set ATE ADDR2=SA for TxFrame(STA : To DS = 1 ; From DS = 0)
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_SA_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
PSTRING value;
INT i;
// Mac address acceptable format 01:02:03:04:05:06 length 17
if (strlen(arg) != 17)
return FALSE;
for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
{
/* sanity check */
if ((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))))
{
return FALSE;
}
#ifdef CONFIG_STA_SUPPORT
AtoH(value, &pAd->ate.Addr2[i++], 1);
#endif // CONFIG_STA_SUPPORT //
}
/* sanity check */
if (i != 6)
{
return FALSE;
}
#ifdef CONFIG_STA_SUPPORT
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_SA_Proc (SA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr2[0],
pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]));
#endif // CONFIG_STA_SUPPORT //
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_SA_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE ADDR2=BSSID for TxFrame(AP : To DS = 0 ; From DS = 1)
or
Set ATE ADDR1=BSSID for TxFrame(STA : To DS = 1 ; From DS = 0)
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_BSSID_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
PSTRING value;
INT i;
// Mac address acceptable format 01:02:03:04:05:06 length 17
if (strlen(arg) != 17)
return FALSE;
for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
{
/* sanity check */
if ((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))))
{
return FALSE;
}
#ifdef CONFIG_STA_SUPPORT
AtoH(value, &pAd->ate.Addr1[i++], 1);
#endif // CONFIG_STA_SUPPORT //
}
/* sanity check */
if(i != 6)
{
return FALSE;
}
#ifdef CONFIG_STA_SUPPORT
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_BSSID_Proc (BSSID = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr1[0],
pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]));
#endif // CONFIG_STA_SUPPORT //
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_BSSID_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx Channel
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_CHANNEL_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UCHAR channel;
channel = simple_strtol(arg, 0, 10);
// to allow A band channel : ((channel < 1) || (channel > 14))
if ((channel < 1) || (channel > 216))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_CHANNEL_Proc::Out of range, it should be in range of 1~14.\n"));
return FALSE;
}
pAd->ate.Channel = channel;
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_CHANNEL_Proc (ATE Channel = %d)\n", pAd->ate.Channel));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_CHANNEL_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx Power0
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_POWER0_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
CHAR TxPower;
TxPower = simple_strtol(arg, 0, 10);
if (pAd->ate.Channel <= 14)
{
if ((TxPower > 31) || (TxPower < 0))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
return FALSE;
}
}
else/* 5.5 GHz */
{
if ((TxPower > 15) || (TxPower < -7))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
return FALSE;
}
}
pAd->ate.TxPower0 = TxPower;
ATETxPwrHandler(pAd, 0);
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER0_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx Power1
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_POWER1_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
CHAR TxPower;
TxPower = simple_strtol(arg, 0, 10);
if (pAd->ate.Channel <= 14)
{
if ((TxPower > 31) || (TxPower < 0))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
return FALSE;
}
}
else
{
if ((TxPower > 15) || (TxPower < -7))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
return FALSE;
}
}
pAd->ate.TxPower1 = TxPower;
ATETxPwrHandler(pAd, 1);
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER1_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx Antenna
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_Antenna_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
CHAR value;
value = simple_strtol(arg, 0, 10);
if ((value > 2) || (value < 0))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_Antenna_Proc::Out of range (Value=%d)\n", value));
return FALSE;
}
pAd->ate.TxAntennaSel = value;
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_Antenna_Proc (Antenna = %d)\n", pAd->ate.TxAntennaSel));
ATEDBGPRINT(RT_DEBUG_TRACE,("Ralink: Set_ATE_TX_Antenna_Proc Success\n"));
// calibration power unbalance issues, merged from Arch Team
ATEAsicSwitchChannel(pAd);
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Rx Antenna
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_RX_Antenna_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
CHAR value;
value = simple_strtol(arg, 0, 10);
if ((value > 3) || (value < 0))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_RX_Antenna_Proc::Out of range (Value=%d)\n", value));
return FALSE;
}
pAd->ate.RxAntennaSel = value;
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_Antenna_Proc (Antenna = %d)\n", pAd->ate.RxAntennaSel));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_Antenna_Proc Success\n"));
// calibration power unbalance issues, merged from Arch Team
ATEAsicSwitchChannel(pAd);
return TRUE;
}
/*
==========================================================================
Description:
Set ATE RF frequence offset
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_FREQOFFSET_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UCHAR RFFreqOffset = 0;
ULONG R4 = 0;
RFFreqOffset = simple_strtol(arg, 0, 10);
#ifndef RTMP_RF_RW_SUPPORT
if (RFFreqOffset >= 64)
#endif // RTMP_RF_RW_SUPPORT //
/* RT35xx ATE will reuse this code segment. */
#ifdef RTMP_RF_RW_SUPPORT
//2008/08/06: KH modified the limit of offset value from 65 to 95(0x5F)
if (RFFreqOffset >= 95)
#endif // RTMP_RF_RW_SUPPORT //
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_FREQOFFSET_Proc::Out of range, it should be in range of 0~63.\n"));
return FALSE;
}
pAd->ate.RFFreqOffset = RFFreqOffset;
#ifdef RTMP_RF_RW_SUPPORT
if (IS_RT30xx(pAd) || IS_RT3572(pAd))
{
// Set RF offset
UCHAR RFValue;
ATE_RF_IO_READ8_BY_REG_ID(pAd, RF_R23, (PUCHAR)&RFValue);
//2008/08/06: KH modified "pAd->RFFreqOffset" to "pAd->ate.RFFreqOffset"
RFValue = ((RFValue & 0x80) | pAd->ate.RFFreqOffset);
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R23, (UCHAR)RFValue);
}
else
#endif // RTMP_RF_RW_SUPPORT //
{
// RT28xx
// shift TX power control to correct RF register bit position
R4 = pAd->ate.RFFreqOffset << 15;
R4 |= (pAd->LatchRfRegs.R4 & ((~0x001f8000)));
pAd->LatchRfRegs.R4 = R4;
RtmpRfIoWrite(pAd);
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_FREQOFFSET_Proc (RFFreqOffset = %d)\n", pAd->ate.RFFreqOffset));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_FREQOFFSET_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE RF BW
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_BW_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
INT i;
UCHAR value = 0;
UCHAR BBPCurrentBW;
BBPCurrentBW = simple_strtol(arg, 0, 10);
if ((BBPCurrentBW == 0)
#ifdef RT30xx
|| IS_RT2070(pAd)
#endif // RT30xx //
)
{
pAd->ate.TxWI.BW = BW_20;
}
else
{
pAd->ate.TxWI.BW = BW_40;
}
/* RT35xx ATE will reuse this code segment. */
// Fix the error spectrum of CCK-40MHZ
// Turn on BBP 20MHz mode by request here.
if ((pAd->ate.TxWI.PHYMODE == MODE_CCK) && (pAd->ate.TxWI.BW == BW_40))
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_BW_Proc!! Warning!! CCK only supports 20MHZ!!\nBandwidth switch to 20\n"));
pAd->ate.TxWI.BW = BW_20;
}
if (pAd->ate.TxWI.BW == BW_20)
{
if (pAd->ate.Channel <= 14)
{
for (i=0; i<5; i++)
{
if (pAd->Tx20MPwrCfgGBand[i] != 0xffffffff)
{
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgGBand[i]);
RTMPusecDelay(5000);
}
}
}
else
{
for (i=0; i<5; i++)
{
if (pAd->Tx20MPwrCfgABand[i] != 0xffffffff)
{
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgABand[i]);
RTMPusecDelay(5000);
}
}
}
// Set BBP R4 bit[4:3]=0:0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
value &= (~0x18);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
// Set BBP R66=0x3C
value = 0x3C;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
// Set BBP R68=0x0B
// to improve Rx sensitivity.
value = 0x0B;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
// Set BBP R69=0x16
value = 0x16;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
// Set BBP R70=0x08
value = 0x08;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
// Set BBP R73=0x11
value = 0x11;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
/*
If Channel=14, Bandwidth=20M and Mode=CCK, Set BBP R4 bit5=1
(to set Japan filter coefficients).
This segment of code will only works when ATETXMODE and ATECHANNEL
were set to MODE_CCK and 14 respectively before ATETXBW is set to 0.
*/
if (pAd->ate.Channel == 14)
{
INT TxMode = pAd->ate.TxWI.PHYMODE;
if (TxMode == MODE_CCK)
{
// when Channel==14 && Mode==CCK && BandWidth==20M, BBP R4 bit5=1
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
value |= 0x20; //set bit5=1
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
}
}
#ifdef RT30xx
// set BW = 20 MHz
if (IS_RT30xx(pAd))
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R24, (UCHAR) pAd->Mlme.CaliBW20RfR24);
else
#endif // RT30xx //
// set BW = 20 MHz
{
pAd->LatchRfRegs.R4 &= ~0x00200000;
RtmpRfIoWrite(pAd);
}
}
// If bandwidth = 40M, set RF Reg4 bit 21 = 0.
else if (pAd->ate.TxWI.BW == BW_40)
{
if (pAd->ate.Channel <= 14)
{
for (i=0; i<5; i++)
{
if (pAd->Tx40MPwrCfgGBand[i] != 0xffffffff)
{
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgGBand[i]);
RTMPusecDelay(5000);
}
}
}
else
{
for (i=0; i<5; i++)
{
if (pAd->Tx40MPwrCfgABand[i] != 0xffffffff)
{
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgABand[i]);
RTMPusecDelay(5000);
}
}
#ifdef DOT11_N_SUPPORT
if ((pAd->ate.TxWI.PHYMODE >= MODE_HTMIX) && (pAd->ate.TxWI.MCS == 7))
{
value = 0x28;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R67, value);
}
#endif // DOT11_N_SUPPORT //
}
// Set BBP R4 bit[4:3]=1:0
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
value &= (~0x18);
value |= 0x10;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
// Set BBP R66=0x3C
value = 0x3C;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
// Set BBP R68=0x0C
// to improve Rx sensitivity
value = 0x0C;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
// Set BBP R69=0x1A
value = 0x1A;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
// Set BBP R70=0x0A
value = 0x0A;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
// Set BBP R73=0x16
value = 0x16;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
// If bandwidth = 40M, set RF Reg4 bit 21 = 1.
#ifdef RT30xx
// set BW = 40 MHz
if(IS_RT30xx(pAd))
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R24, (UCHAR) pAd->Mlme.CaliBW40RfR24);
else
#endif // RT30xx //
// set BW = 40 MHz
{
pAd->LatchRfRegs.R4 |= 0x00200000;
RtmpRfIoWrite(pAd);
}
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_BW_Proc (BBPCurrentBW = %d)\n", pAd->ate.TxWI.BW));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_BW_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx frame length
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_LENGTH_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
pAd->ate.TxLength = simple_strtol(arg, 0, 10);
if ((pAd->ate.TxLength < 24) || (pAd->ate.TxLength > (MAX_FRAME_SIZE - 34/* == 2312 */)))
{
pAd->ate.TxLength = (MAX_FRAME_SIZE - 34/* == 2312 */);
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_LENGTH_Proc::Out of range, it should be in range of 24~%d.\n", (MAX_FRAME_SIZE - 34/* == 2312 */)));
return FALSE;
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_LENGTH_Proc (TxLength = %d)\n", pAd->ate.TxLength));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_LENGTH_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx frame count
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_COUNT_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
pAd->ate.TxCount = simple_strtol(arg, 0, 10);
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_COUNT_Proc (TxCount = %d)\n", pAd->ate.TxCount));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_COUNT_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx frame MCS
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_MCS_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UCHAR MCS;
INT result;
MCS = simple_strtol(arg, 0, 10);
#ifndef RT30xx
result = CheckMCSValid(pAd->ate.TxWI.PHYMODE, MCS);
#endif // RT30xx //
/* RT35xx ATE will reuse this code segment. */
#ifdef RT30xx
result = CheckMCSValid(pAd->ate.TxWI.PHYMODE, MCS, IS_RT2070(pAd));
#endif // RT30xx //
if (result != -1)
{
pAd->ate.TxWI.MCS = (UCHAR)MCS;
}
else
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MCS_Proc::Out of range, refer to rate table.\n"));
return FALSE;
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MCS_Proc (MCS = %d)\n", pAd->ate.TxWI.MCS));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MCS_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx frame Mode
0: MODE_CCK
1: MODE_OFDM
2: MODE_HTMIX
3: MODE_HTGREENFIELD
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_MODE_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UCHAR BbpData = 0;
pAd->ate.TxWI.PHYMODE = simple_strtol(arg, 0, 10);
if (pAd->ate.TxWI.PHYMODE > 3)
{
pAd->ate.TxWI.PHYMODE = 0;
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MODE_Proc::Out of range.\nIt should be in range of 0~3\n"));
ATEDBGPRINT(RT_DEBUG_ERROR, ("0: CCK, 1: OFDM, 2: HT_MIX, 3: HT_GREEN_FIELD.\n"));
return FALSE;
}
// Turn on BBP 20MHz mode by request here.
if (pAd->ate.TxWI.PHYMODE == MODE_CCK)
{
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BbpData);
BbpData &= (~0x18);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BbpData);
pAd->ate.TxWI.BW = BW_20;
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MODE_Proc::CCK Only support 20MHZ. Switch to 20MHZ.\n"));
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MODE_Proc (TxMode = %d)\n", pAd->ate.TxWI.PHYMODE));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MODE_Proc Success\n"));
return TRUE;
}
/*
==========================================================================
Description:
Set ATE Tx frame GI
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
INT Set_ATE_TX_GI_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
pAd->ate.TxWI.ShortGI = simple_strtol(arg, 0, 10);
if (pAd->ate.TxWI.ShortGI > 1)
{
pAd->ate.TxWI.ShortGI = 0;
ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_GI_Proc::Out of range\n"));
return FALSE;
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_GI_Proc (GI = %d)\n", pAd->ate.TxWI.ShortGI));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_GI_Proc Success\n"));
return TRUE;
}
INT Set_ATE_RX_FER_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
pAd->ate.bRxFER = simple_strtol(arg, 0, 10);
if (pAd->ate.bRxFER == 1)
{
pAd->ate.RxCntPerSec = 0;
pAd->ate.RxTotalCnt = 0;
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_FER_Proc (bRxFER = %d)\n", pAd->ate.bRxFER));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_FER_Proc Success\n"));
return TRUE;
}
INT Set_ATE_Read_RF_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
#ifdef RTMP_RF_RW_SUPPORT
//2008/07/10:KH add to support RT30xx ATE<--
if (IS_RT30xx(pAd) || IS_RT3572(pAd))
{
/* modify by WY for Read RF Reg. error */
UCHAR RFValue;
INT index=0;
for (index = 0; index < 32; index++)
{
ATE_RF_IO_READ8_BY_REG_ID(pAd, index, (PUCHAR)&RFValue);
ate_print("R%d=%d\n",index,RFValue);
}
}
else
//2008/07/10:KH add to support RT30xx ATE-->
#endif // RTMP_RF_RW_SUPPORT //
{
ate_print(KERN_EMERG "R1 = %lx\n", pAd->LatchRfRegs.R1);
ate_print(KERN_EMERG "R2 = %lx\n", pAd->LatchRfRegs.R2);
ate_print(KERN_EMERG "R3 = %lx\n", pAd->LatchRfRegs.R3);
ate_print(KERN_EMERG "R4 = %lx\n", pAd->LatchRfRegs.R4);
}
return TRUE;
}
INT Set_ATE_Write_RF1_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UINT32 value = (UINT32) simple_strtol(arg, 0, 16);
#ifdef RTMP_RF_RW_SUPPORT
//2008/07/10:KH add to support 3070 ATE<--
if (IS_RT30xx(pAd) || IS_RT3572(pAd))
{
ate_print("Warning!! RT3xxx Don't Support !\n");
return FALSE;
}
else
//2008/07/10:KH add to support 3070 ATE-->
#endif // RTMP_RF_RW_SUPPORT //
{
pAd->LatchRfRegs.R1 = value;
RtmpRfIoWrite(pAd);
}
return TRUE;
}
INT Set_ATE_Write_RF2_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UINT32 value = (UINT32) simple_strtol(arg, 0, 16);
#ifdef RTMP_RF_RW_SUPPORT
//2008/07/10:KH add to support 3070 ATE<--
if (IS_RT30xx(pAd) || IS_RT3572(pAd))
{
ate_print("Warning!! RT3xxx Don't Support !\n");
return FALSE;
}
else
//2008/07/10:KH add to support 3070 ATE-->
#endif // RTMP_RF_RW_SUPPORT //
{
pAd->LatchRfRegs.R2 = value;
RtmpRfIoWrite(pAd);
}
return TRUE;
}
INT Set_ATE_Write_RF3_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UINT32 value = simple_strtol(arg, 0, 16);
#ifdef RTMP_RF_RW_SUPPORT
//2008/07/10:KH add to support 3070 ATE<--
if (IS_RT30xx(pAd) || IS_RT3572(pAd))
{
ate_print("Warning!! RT3xxx Don't Support !\n");
return FALSE;
}
else
//2008/07/10:KH add to support 3070 ATE-->
#endif // RTMP_RF_RW_SUPPORT //
{
pAd->LatchRfRegs.R3 = value;
RtmpRfIoWrite(pAd);
}
return TRUE;
}
INT Set_ATE_Write_RF4_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UINT32 value = (UINT32) simple_strtol(arg, 0, 16);
#ifdef RTMP_RF_RW_SUPPORT
//2008/07/10:KH add to support 3070 ATE<--
if (IS_RT30xx(pAd) || IS_RT3572(pAd))
{
ate_print("Warning!! RT3xxx Don't Support !\n");
return FALSE;
}
else
//2008/07/10:KH add to support 3070 ATE-->
#endif // RTMP_RF_RW_SUPPORT //
{
pAd->LatchRfRegs.R4 = value;
RtmpRfIoWrite(pAd);
}
return TRUE;
}
/*
==========================================================================
Description:
Load and Write EEPROM from a binary file prepared in advance.
Return:
TRUE if all parameters are OK, FALSE otherwise
==========================================================================
*/
#if defined(LINUX) || defined(VXWORKS)
INT Set_ATE_Load_E2P_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
BOOLEAN ret = FALSE;
PSTRING src = EEPROM_BIN_FILE_NAME;
RTMP_OS_FD srcf;
INT32 retval;
USHORT WriteEEPROM[(EEPROM_SIZE/2)];
INT FileLength = 0;
UINT32 value = (UINT32) simple_strtol(arg, 0, 10);
RTMP_OS_FS_INFO osFSInfo;
ATEDBGPRINT(RT_DEBUG_ERROR, ("===> %s (value=%d)\n\n", __FUNCTION__, value));
if (value > 0)
{
/* zero the e2p buffer */
NdisZeroMemory((PUCHAR)WriteEEPROM, EEPROM_SIZE);
RtmpOSFSInfoChange(&osFSInfo, TRUE);
do
{
/* open the bin file */
srcf = RtmpOSFileOpen(src, O_RDONLY, 0);
if (IS_FILE_OPEN_ERR(srcf))
{
ate_print("%s - Error opening file %s\n", __FUNCTION__, src);
break;
}
/* read the firmware from the file *.bin */
FileLength = RtmpOSFileRead(srcf, (PSTRING)WriteEEPROM, EEPROM_SIZE);
if (FileLength != EEPROM_SIZE)
{
ate_print("%s: error file length (=%d) in e2p.bin\n",
__FUNCTION__, FileLength);
break;
}
else
{
/* write the content of .bin file to EEPROM */
rt_ee_write_all(pAd, WriteEEPROM);
ret = TRUE;
}
break;
} while(TRUE);
/* close firmware file */
if (IS_FILE_OPEN_ERR(srcf))
{
;
}
else
{
retval = RtmpOSFileClose(srcf);
if (retval)
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("--> Error %d closing %s\n", -retval, src));
}
}
/* restore */
RtmpOSFSInfoChange(&osFSInfo, FALSE);
}
ATEDBGPRINT(RT_DEBUG_ERROR, ("<=== %s (ret=%d)\n", __FUNCTION__, ret));
return ret;
}
#endif // defined(LINUX) || defined(VXWORKS) //
INT Set_ATE_Read_E2P_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
USHORT buffer[EEPROM_SIZE/2];
USHORT *p;
int i;
rt_ee_read_all(pAd, (USHORT *)buffer);
p = buffer;
for (i = 0; i < (EEPROM_SIZE/2); i++)
{
ate_print("%4.4x ", *p);
if (((i+1) % 16) == 0)
ate_print("\n");
p++;
}
return TRUE;
}
INT Set_ATE_Show_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
ate_print("Mode=%d\n", pAd->ate.Mode);
ate_print("TxPower0=%d\n", pAd->ate.TxPower0);
ate_print("TxPower1=%d\n", pAd->ate.TxPower1);
ate_print("TxAntennaSel=%d\n", pAd->ate.TxAntennaSel);
ate_print("RxAntennaSel=%d\n", pAd->ate.RxAntennaSel);
ate_print("BBPCurrentBW=%d\n", pAd->ate.TxWI.BW);
ate_print("GI=%d\n", pAd->ate.TxWI.ShortGI);
ate_print("MCS=%d\n", pAd->ate.TxWI.MCS);
ate_print("TxMode=%d\n", pAd->ate.TxWI.PHYMODE);
ate_print("Addr1=%02x:%02x:%02x:%02x:%02x:%02x\n",
pAd->ate.Addr1[0], pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]);
ate_print("Addr2=%02x:%02x:%02x:%02x:%02x:%02x\n",
pAd->ate.Addr2[0], pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]);
ate_print("Addr3=%02x:%02x:%02x:%02x:%02x:%02x\n",
pAd->ate.Addr3[0], pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]);
ate_print("Channel=%d\n", pAd->ate.Channel);
ate_print("TxLength=%d\n", pAd->ate.TxLength);
ate_print("TxCount=%u\n", pAd->ate.TxCount);
ate_print("RFFreqOffset=%d\n", pAd->ate.RFFreqOffset);
ate_print(KERN_EMERG "Set_ATE_Show_Proc Success\n");
return TRUE;
}
INT Set_ATE_Help_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
ate_print("ATE=ATESTART, ATESTOP, TXCONT, TXCARR, TXFRAME, RXFRAME\n");
ate_print("ATEDA\n");
ate_print("ATESA\n");
ate_print("ATEBSSID\n");
ate_print("ATECHANNEL, range:0~14(unless A band !)\n");
ate_print("ATETXPOW0, set power level of antenna 1.\n");
ate_print("ATETXPOW1, set power level of antenna 2.\n");
ate_print("ATETXANT, set TX antenna. 0:all, 1:antenna one, 2:antenna two.\n");
ate_print("ATERXANT, set RX antenna.0:all, 1:antenna one, 2:antenna two, 3:antenna three.\n");
ate_print("ATETXFREQOFFSET, set frequency offset, range 0~63\n");
ate_print("ATETXBW, set BandWidth, 0:20MHz, 1:40MHz.\n");
ate_print("ATETXLEN, set Frame length, range 24~%d\n", (MAX_FRAME_SIZE - 34/* == 2312 */));
ate_print("ATETXCNT, set how many frame going to transmit.\n");
ate_print("ATETXMCS, set MCS, reference to rate table.\n");
ate_print("ATETXMODE, set Mode 0:CCK, 1:OFDM, 2:HT-Mix, 3:GreenField, reference to rate table.\n");
ate_print("ATETXGI, set GI interval, 0:Long, 1:Short\n");
ate_print("ATERXFER, 0:disable Rx Frame error rate. 1:enable Rx Frame error rate.\n");
ate_print("ATERRF, show all RF registers.\n");
ate_print("ATEWRF1, set RF1 register.\n");
ate_print("ATEWRF2, set RF2 register.\n");
ate_print("ATEWRF3, set RF3 register.\n");
ate_print("ATEWRF4, set RF4 register.\n");
ate_print("ATELDE2P, load EEPROM from .bin file.\n");
ate_print("ATERE2P, display all EEPROM content.\n");
ate_print("ATESHOW, display all parameters of ATE.\n");
ate_print("ATEHELP, online help.\n");
return TRUE;
}
/*
==========================================================================
Description:
AsicSwitchChannel() dedicated for ATE.
==========================================================================
*/
VOID ATEAsicSwitchChannel(
IN PRTMP_ADAPTER pAd)
{
UINT32 R2 = 0, R3 = DEFAULT_RF_TX_POWER, R4 = 0, Value = 0;
CHAR TxPwer = 0, TxPwer2 = 0;
UCHAR index = 0, BbpValue = 0, R66 = 0x30;
RTMP_RF_REGS *RFRegTable;
UCHAR Channel = 0;
RFRegTable = NULL;
#ifdef RALINK_28xx_QA
// for QA mode, TX power values are passed from UI
if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
{
if (pAd->ate.Channel != pAd->LatchRfRegs.Channel)
{
pAd->ate.Channel = pAd->LatchRfRegs.Channel;
}
return;
}
else
#endif // RALINK_28xx_QA //
Channel = pAd->ate.Channel;
// select antenna for RT3090
AsicAntennaSelect(pAd, Channel);
// fill Tx power value
TxPwer = pAd->ate.TxPower0;
TxPwer2 = pAd->ate.TxPower1;
#ifdef RT30xx
//2008/07/10:KH add to support 3070 ATE<--
/*
The RF programming sequence is difference between 3xxx and 2xxx.
The 3070 is 1T1R. Therefore, we don't need to set the number of Tx/Rx path
and the only job is to set the parameters of channels.
*/
if (IS_RT30xx(pAd) && ((pAd->RfIcType == RFIC_3020) ||
(pAd->RfIcType == RFIC_3021) || (pAd->RfIcType == RFIC_3022) ||
(pAd->RfIcType == RFIC_2020)))
{
/* modify by WY for Read RF Reg. error */
UCHAR RFValue = 0;
for (index = 0; index < NUM_OF_3020_CHNL; index++)
{
if (Channel == FreqItems3020[index].Channel)
{
// Programming channel parameters.
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R02, FreqItems3020[index].N);
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R03, FreqItems3020[index].K);
ATE_RF_IO_READ8_BY_REG_ID(pAd, RF_R06, (PUCHAR)&RFValue);
RFValue = (RFValue & 0xFC) | FreqItems3020[index].R;
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R06, (UCHAR)RFValue);
// Set Tx Power.
ATE_RF_IO_READ8_BY_REG_ID(pAd, RF_R12, (PUCHAR)&RFValue);
RFValue = (RFValue & 0xE0) | TxPwer;
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R12, (UCHAR)RFValue);
// Set RF offset.
ATE_RF_IO_READ8_BY_REG_ID(pAd, RF_R23, (PUCHAR)&RFValue);
//2008/08/06: KH modified "pAd->RFFreqOffset" to "pAd->ate.RFFreqOffset"
RFValue = (RFValue & 0x80) | pAd->ate.RFFreqOffset;
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R23, (UCHAR)RFValue);
// Set BW.
if (pAd->ate.TxWI.BW == BW_40)
{
RFValue = pAd->Mlme.CaliBW40RfR24;
// DISABLE_11N_CHECK(pAd);
}
else
{
RFValue = pAd->Mlme.CaliBW20RfR24;
}
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R24, (UCHAR)RFValue);
// Enable RF tuning
ATE_RF_IO_READ8_BY_REG_ID(pAd, RF_R07, (PUCHAR)&RFValue);
RFValue = RFValue | 0x1;
ATE_RF_IO_WRITE8_BY_REG_ID(pAd, RF_R07, (UCHAR)RFValue);
// latch channel for future usage
pAd->LatchRfRegs.Channel = Channel;
break;
}
}
ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n",
Channel,
pAd->RfIcType,
TxPwer,
TxPwer2,
pAd->Antenna.field.TxPath,
FreqItems3020[index].N,
FreqItems3020[index].K,
FreqItems3020[index].R));
}
else
//2008/07/10:KH add to support 3070 ATE-->
#endif // RT30xx //
{
/* RT28xx */
RFRegTable = RF2850RegTable;
switch (pAd->RfIcType)
{
/* But only 2850 and 2750 support 5.5GHz band... */
case RFIC_2820:
case RFIC_2850:
case RFIC_2720:
case RFIC_2750:
for (index = 0; index < NUM_OF_2850_CHNL; index++)
{
if (Channel == RFRegTable[index].Channel)
{
R2 = RFRegTable[index].R2;
// If TX path is 1, bit 14 = 1;
if (pAd->Antenna.field.TxPath == 1)
{
R2 |= 0x4000;
}
if (pAd->Antenna.field.RxPath == 2)
{
switch (pAd->ate.RxAntennaSel)
{
case 1:
R2 |= 0x20040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x00;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
case 2:
R2 |= 0x10040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x01;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
default:
R2 |= 0x40;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
/* Only enable two Antenna to receive. */
BbpValue |= 0x08;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
}
}
else if (pAd->Antenna.field.RxPath == 1)
{
// write 1 to off RxPath
R2 |= 0x20040;
}
if (pAd->Antenna.field.TxPath == 2)
{
if (pAd->ate.TxAntennaSel == 1)
{
// If TX Antenna select is 1 , bit 14 = 1; Disable Ant 2
R2 |= 0x4000;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
BbpValue &= 0xE7; // 11100111B
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
}
else if (pAd->ate.TxAntennaSel == 2)
{
// If TX Antenna select is 2 , bit 15 = 1; Disable Ant 1
R2 |= 0x8000;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
BbpValue &= 0xE7;
BbpValue |= 0x08;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
}
else
{
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
BbpValue &= 0xE7;
BbpValue |= 0x10;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
}
}
if (pAd->Antenna.field.RxPath == 3)
{
switch (pAd->ate.RxAntennaSel)
{
case 1:
R2 |= 0x20040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x00;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
case 2:
R2 |= 0x10040;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x01;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
case 3:
R2 |= 0x30000;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x02;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
default:
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
BbpValue &= 0xE4;
BbpValue |= 0x10;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
break;
}
}
if (Channel > 14)
{
// initialize R3, R4
R3 = (RFRegTable[index].R3 & 0xffffc1ff);
R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15);
/*
According the Rory's suggestion to solve the middle range issue.
5.5G band power range : 0xF9~0X0F, TX0 Reg3 bit9/TX1 Reg4 bit6="0"
means the TX power reduce 7dB.
*/
// R3
if ((TxPwer >= -7) && (TxPwer < 0))
{
TxPwer = (7+TxPwer);
TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
R3 |= (TxPwer << 10);
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer=%d \n", TxPwer));
}
else
{
TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
R3 |= (TxPwer << 10) | (1 << 9);
}
// R4
if ((TxPwer2 >= -7) && (TxPwer2 < 0))
{
TxPwer2 = (7+TxPwer2);
TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
R4 |= (TxPwer2 << 7);
ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer2=%d \n", TxPwer2));
}
else
{
TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
R4 |= (TxPwer2 << 7) | (1 << 6);
}
}
else
{
// Set TX power0.
R3 = (RFRegTable[index].R3 & 0xffffc1ff) | (TxPwer << 9);
// Set frequency offset and TX power1.
R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15) | (TxPwer2 <<6);
}
// based on BBP current mode before changing RF channel
if (pAd->ate.TxWI.BW == BW_40)
{
R4 |=0x200000;
}
// Update variables.
pAd->LatchRfRegs.Channel = Channel;
pAd->LatchRfRegs.R1 = RFRegTable[index].R1;
pAd->LatchRfRegs.R2 = R2;
pAd->LatchRfRegs.R3 = R3;
pAd->LatchRfRegs.R4 = R4;
RtmpRfIoWrite(pAd);
break;
}
}
break;
default:
break;
}
}
// Change BBP setting during switch from a->g, g->a
if (Channel <= 14)
{
UINT32 TxPinCfg = 0x00050F0A;// 2007.10.09 by Brian : 0x0005050A ==> 0x00050F0A
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
/* For 1T/2R chip only... */
if (pAd->NicConfig2.field.ExternalLNAForG)
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
}
else
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
}
// According the Rory's suggestion to solve the middle range issue.
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);// may be removed for RT35xx ++
ASSERT((BbpValue == 0x00));
if ((BbpValue != 0x00))
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
}// may be removed for RT35xx --
// 5.5 GHz band selection PIN, bit1 and bit2 are complement
RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
Value &= (~0x6);
Value |= (0x04);
RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
// Turn off unused PA or LNA when only 1T or 1R.
if (pAd->Antenna.field.TxPath == 1)
{
TxPinCfg &= 0xFFFFFFF3;
}
if (pAd->Antenna.field.RxPath == 1)
{
TxPinCfg &= 0xFFFFF3FF;
}
// calibration power unbalance issues
if (pAd->Antenna.field.TxPath == 2)
{
if (pAd->ate.TxAntennaSel == 1)
{
TxPinCfg &= 0xFFFFFFF7;
}
else if (pAd->ate.TxAntennaSel == 2)
{
TxPinCfg &= 0xFFFFFFFD;
}
}
RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
}
else
{
UINT32 TxPinCfg = 0x00050F05;// 2007.10.09 by Brian : 0x00050505 ==> 0x00050F05
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0xF2);
// According the Rory's suggestion to solve the middle range issue.
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);// may be removed for RT35xx ++
ASSERT((BbpValue == 0x00));
if ((BbpValue != 0x00))
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
}
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R91, &BbpValue);
ASSERT((BbpValue == 0x04));
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R92, &BbpValue);
ASSERT((BbpValue == 0x00));// may be removed for RT35xx --
// 5.5 GHz band selection PIN, bit1 and bit2 are complement
RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
Value &= (~0x6);
Value |= (0x02);
RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
// Turn off unused PA or LNA when only 1T or 1R.
if (pAd->Antenna.field.TxPath == 1)
{
TxPinCfg &= 0xFFFFFFF3;
}
if (pAd->Antenna.field.RxPath == 1)
{
TxPinCfg &= 0xFFFFF3FF;
}
RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
}
// R66 should be set according to Channel and use 20MHz when scanning
if (Channel <= 14)
{
// BG band
R66 = 0x2E + GET_LNA_GAIN(pAd);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
}
else
{
// 5.5 GHz band
if (pAd->ate.TxWI.BW == BW_20)
{
R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
}
else
{
R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
}
}
/*
On 11A, We should delay and wait RF/BBP to be stable
and the appropriate time should be 1000 micro seconds.
2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.
*/
RTMPusecDelay(1000);
#ifndef RTMP_RF_RW_SUPPORT
if (Channel > 14)
{
// When 5.5GHz band the LSB of TxPwr will be used to reduced 7dB or not.
ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
Channel,
pAd->RfIcType,
pAd->Antenna.field.TxPath,
pAd->LatchRfRegs.R1,
pAd->LatchRfRegs.R2,
pAd->LatchRfRegs.R3,
pAd->LatchRfRegs.R4));
}
else
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%u, Pwr1=%u, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
Channel,
pAd->RfIcType,
(R3 & 0x00003e00) >> 9,
(R4 & 0x000007c0) >> 6,
pAd->Antenna.field.TxPath,
pAd->LatchRfRegs.R1,
pAd->LatchRfRegs.R2,
pAd->LatchRfRegs.R3,
pAd->LatchRfRegs.R4));
}
#endif // RTMP_RF_RW_SUPPORT //
}
/* In fact, no one will call this routine so far ! */
/*
==========================================================================
Description:
Gives CCK TX rate 2 more dB TX power.
This routine works only in ATE mode.
calculate desired Tx power in RF R3.Tx0~5, should consider -
0. if current radio is a noisy environment (pAd->DrsCounters.fNoisyEnvironment)
1. TxPowerPercentage
2. auto calibration based on TSSI feedback
3. extra 2 db for CCK
4. -10 db upon very-short distance (AvgRSSI >= -40db) to AP
NOTE: Since this routine requires the value of (pAd->DrsCounters.fNoisyEnvironment),
it should be called AFTER MlmeDynamicTxRateSwitching()
==========================================================================
*/
VOID ATEAsicAdjustTxPower(
IN PRTMP_ADAPTER pAd)
{
INT i, j;
CHAR DeltaPwr = 0;
BOOLEAN bAutoTxAgc = FALSE;
UCHAR TssiRef, *pTssiMinusBoundary, *pTssiPlusBoundary, TxAgcStep;
UCHAR BbpR49 = 0, idx;
PCHAR pTxAgcCompensate;
ULONG TxPwr[5];
CHAR Value;
/* no one calls this procedure so far */
if (pAd->ate.TxWI.BW == BW_40)
{
if (pAd->ate.Channel > 14)
{
TxPwr[0] = pAd->Tx40MPwrCfgABand[0];
TxPwr[1] = pAd->Tx40MPwrCfgABand[1];
TxPwr[2] = pAd->Tx40MPwrCfgABand[2];
TxPwr[3] = pAd->Tx40MPwrCfgABand[3];
TxPwr[4] = pAd->Tx40MPwrCfgABand[4];
}
else
{
TxPwr[0] = pAd->Tx40MPwrCfgGBand[0];
TxPwr[1] = pAd->Tx40MPwrCfgGBand[1];
TxPwr[2] = pAd->Tx40MPwrCfgGBand[2];
TxPwr[3] = pAd->Tx40MPwrCfgGBand[3];
TxPwr[4] = pAd->Tx40MPwrCfgGBand[4];
}
}
else
{
if (pAd->ate.Channel > 14)
{
TxPwr[0] = pAd->Tx20MPwrCfgABand[0];
TxPwr[1] = pAd->Tx20MPwrCfgABand[1];
TxPwr[2] = pAd->Tx20MPwrCfgABand[2];
TxPwr[3] = pAd->Tx20MPwrCfgABand[3];
TxPwr[4] = pAd->Tx20MPwrCfgABand[4];
}
else
{
TxPwr[0] = pAd->Tx20MPwrCfgGBand[0];
TxPwr[1] = pAd->Tx20MPwrCfgGBand[1];
TxPwr[2] = pAd->Tx20MPwrCfgGBand[2];
TxPwr[3] = pAd->Tx20MPwrCfgGBand[3];
TxPwr[4] = pAd->Tx20MPwrCfgGBand[4];
}
}
// TX power compensation for temperature variation based on TSSI.
// Do it per 4 seconds.
if (pAd->Mlme.OneSecPeriodicRound % 4 == 0)
{
if (pAd->ate.Channel <= 14)
{
/* bg channel */
bAutoTxAgc = pAd->bAutoTxAgcG;
TssiRef = pAd->TssiRefG;
pTssiMinusBoundary = &pAd->TssiMinusBoundaryG[0];
pTssiPlusBoundary = &pAd->TssiPlusBoundaryG[0];
TxAgcStep = pAd->TxAgcStepG;
pTxAgcCompensate = &pAd->TxAgcCompensateG;
}
else
{
/* a channel */
bAutoTxAgc = pAd->bAutoTxAgcA;
TssiRef = pAd->TssiRefA;
pTssiMinusBoundary = &pAd->TssiMinusBoundaryA[0];
pTssiPlusBoundary = &pAd->TssiPlusBoundaryA[0];
TxAgcStep = pAd->TxAgcStepA;
pTxAgcCompensate = &pAd->TxAgcCompensateA;
}
if (bAutoTxAgc)
{
/* BbpR49 is unsigned char. */
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49);
/* (p) TssiPlusBoundaryG[0] = 0 = (m) TssiMinusBoundaryG[0] */
/* compensate: +4 +3 +2 +1 0 -1 -2 -3 -4 * steps */
/* step value is defined in pAd->TxAgcStepG for tx power value */
/* [4]+1+[4] p4 p3 p2 p1 o1 m1 m2 m3 m4 */
/* ex: 0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
above value are examined in mass factory production */
/* [4] [3] [2] [1] [0] [1] [2] [3] [4] */
/* plus is 0x10 ~ 0x40, minus is 0x60 ~ 0x90 */
/* if value is between p1 ~ o1 or o1 ~ s1, no need to adjust tx power */
/* if value is 0x65, tx power will be -= TxAgcStep*(2-1) */
if (BbpR49 > pTssiMinusBoundary[1])
{
// Reading is larger than the reference value.
// Check for how large we need to decrease the Tx power.
for (idx = 1; idx < 5; idx++)
{
// Found the range.
if (BbpR49 <= pTssiMinusBoundary[idx])
break;
}
// The index is the step we should decrease, idx = 0 means there is nothing to compensate.
// if (R3 > (ULONG) (TxAgcStep * (idx-1)))
*pTxAgcCompensate = -(TxAgcStep * (idx-1));
// else
// *pTxAgcCompensate = -((UCHAR)R3);
DeltaPwr += (*pTxAgcCompensate);
ATEDBGPRINT(RT_DEBUG_TRACE, ("-- Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = -%d\n",
BbpR49, TssiRef, TxAgcStep, idx-1));
}
else if (BbpR49 < pTssiPlusBoundary[1])
{
// Reading is smaller than the reference value.
// Check for how large we need to increase the Tx power.
for (idx = 1; idx < 5; idx++)
{
// Found the range.
if (BbpR49 >= pTssiPlusBoundary[idx])
break;
}
// The index is the step we should increase, idx = 0 means there is nothing to compensate.
*pTxAgcCompensate = TxAgcStep * (idx-1);
DeltaPwr += (*pTxAgcCompensate);
ATEDBGPRINT(RT_DEBUG_TRACE, ("++ Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
BbpR49, TssiRef, TxAgcStep, idx-1));
}
else
{
*pTxAgcCompensate = 0;
ATEDBGPRINT(RT_DEBUG_TRACE, (" Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
BbpR49, TssiRef, TxAgcStep, 0));
}
}
}
else
{
if (pAd->ate.Channel <= 14)
{
bAutoTxAgc = pAd->bAutoTxAgcG;
pTxAgcCompensate = &pAd->TxAgcCompensateG;
}
else
{
bAutoTxAgc = pAd->bAutoTxAgcA;
pTxAgcCompensate = &pAd->TxAgcCompensateA;
}
if (bAutoTxAgc)
DeltaPwr += (*pTxAgcCompensate);
}
/* Calculate delta power based on the percentage specified from UI. */
// E2PROM setting is calibrated for maximum TX power (i.e. 100%)
// We lower TX power here according to the percentage specified from UI.
if (pAd->CommonCfg.TxPowerPercentage == 0xffffffff) // AUTO TX POWER control
;
else if (pAd->CommonCfg.TxPowerPercentage > 90) // 91 ~ 100% & AUTO, treat as 100% in terms of mW
;
else if (pAd->CommonCfg.TxPowerPercentage > 60) // 61 ~ 90%, treat as 75% in terms of mW
{
DeltaPwr -= 1;
}
else if (pAd->CommonCfg.TxPowerPercentage > 30) // 31 ~ 60%, treat as 50% in terms of mW
{
DeltaPwr -= 3;
}
else if (pAd->CommonCfg.TxPowerPercentage > 15) // 16 ~ 30%, treat as 25% in terms of mW
{
DeltaPwr -= 6;
}
else if (pAd->CommonCfg.TxPowerPercentage > 9) // 10 ~ 15%, treat as 12.5% in terms of mW
{
DeltaPwr -= 9;
}
else // 0 ~ 9 %, treat as MIN(~3%) in terms of mW
{
DeltaPwr -= 12;
}
/* Reset different new tx power for different TX rate. */
for (i=0; i<5; i++)
{
if (TxPwr[i] != 0xffffffff)
{
for (j=0; j<8; j++)
{
Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F); /* 0 ~ 15 */
if ((Value + DeltaPwr) < 0)
{
Value = 0; /* min */
}
else if ((Value + DeltaPwr) > 0xF)
{
Value = 0xF; /* max */
}
else
{
Value += DeltaPwr; /* temperature compensation */
}
/* fill new value to CSR offset */
TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
}
/* write tx power value to CSR */
/* TX_PWR_CFG_0 (8 tx rate) for TX power for OFDM 12M/18M
TX power for OFDM 6M/9M
TX power for CCK5.5M/11M
TX power for CCK1M/2M */
/* TX_PWR_CFG_1 ~ TX_PWR_CFG_4 */
RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, TxPwr[i]);
}
}
}
/*
========================================================================
Routine Description:
Write TxWI for ATE mode.
Return Value:
None
========================================================================
*/
#ifdef RTMP_MAC_PCI
static VOID ATEWriteTxWI(
IN PRTMP_ADAPTER pAd,
IN PTXWI_STRUC pOutTxWI,
IN BOOLEAN FRAG,
IN BOOLEAN CFACK,
IN BOOLEAN InsTimestamp,
IN BOOLEAN AMPDU,
IN BOOLEAN Ack,
IN BOOLEAN NSeq, // HW new a sequence.
IN UCHAR BASize,
IN UCHAR WCID,
IN ULONG Length,
IN UCHAR PID,
IN UCHAR TID,
IN UCHAR TxRate,
IN UCHAR Txopmode,
IN BOOLEAN CfAck,
IN HTTRANSMIT_SETTING *pTransmit)
{
TXWI_STRUC TxWI;
PTXWI_STRUC pTxWI;
//
// Always use Long preamble before verifiation short preamble functionality works well.
// Todo: remove the following line if short preamble functionality works
//
OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
NdisZeroMemory(&TxWI, TXWI_SIZE);
pTxWI = &TxWI;
pTxWI->FRAG= FRAG;
pTxWI->CFACK = CFACK;
pTxWI->TS= InsTimestamp;
pTxWI->AMPDU = AMPDU;
pTxWI->ACK = Ack;
pTxWI->txop= Txopmode;
pTxWI->NSEQ = NSeq;
// John tune the performace with Intel Client in 20 MHz performance
if ( BASize >7 )
BASize =7;
pTxWI->BAWinSize = BASize;
pTxWI->WirelessCliID = WCID;
pTxWI->MPDUtotalByteCount = Length;
pTxWI->PacketId = PID;
// If CCK or OFDM, BW must be 20
pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
pTxWI->ShortGI = pTransmit->field.ShortGI;
pTxWI->STBC = pTransmit->field.STBC;
pTxWI->MCS = pTransmit->field.MCS;
pTxWI->PHYMODE = pTransmit->field.MODE;
pTxWI->CFACK = CfAck;
pTxWI->MIMOps = 0;
pTxWI->MpduDensity = 0;
pTxWI->PacketId = pTxWI->MCS;
NdisMoveMemory(pOutTxWI, &TxWI, sizeof(TXWI_STRUC));
return;
}
#endif // RTMP_MAC_PCI //
/*
========================================================================
Routine Description:
Disable protection for ATE.
========================================================================
*/
VOID ATEDisableAsicProtect(
IN PRTMP_ADAPTER pAd)
{
PROT_CFG_STRUC ProtCfg, ProtCfg4;
UINT32 Protect[6];
USHORT offset;
UCHAR i;
UINT32 MacReg = 0;
// Config ASIC RTS threshold register
RTMP_IO_READ32(pAd, TX_RTS_CFG, &MacReg);
MacReg &= 0xFF0000FF;
MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
RTMP_IO_WRITE32(pAd, TX_RTS_CFG, MacReg);
// Initial common protection settings
RTMPZeroMemory(Protect, sizeof(Protect));
ProtCfg4.word = 0;
ProtCfg.word = 0;
ProtCfg.field.TxopAllowGF40 = 1;
ProtCfg.field.TxopAllowGF20 = 1;
ProtCfg.field.TxopAllowMM40 = 1;
ProtCfg.field.TxopAllowMM20 = 1;
ProtCfg.field.TxopAllowOfdm = 1;
ProtCfg.field.TxopAllowCck = 1;
ProtCfg.field.RTSThEn = 1;
ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
// Handle legacy(B/G) protection
ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
ProtCfg.field.ProtectCtrl = 0;
Protect[0] = ProtCfg.word;
Protect[1] = ProtCfg.word;
// NO PROTECT
// 1.All STAs in the BSS are 20/40 MHz HT
// 2. in ai 20/40MHz BSS
// 3. all STAs are 20MHz in a 20MHz BSS
// Pure HT. no protection.
// MM20_PROT_CFG
// Reserved (31:27)
// PROT_TXOP(25:20) -- 010111
// PROT_NAV(19:18) -- 01 (Short NAV protection)
// PROT_CTRL(17:16) -- 00 (None)
// PROT_RATE(15:0) -- 0x4004 (OFDM 24M)
Protect[2] = 0x01744004;
// MM40_PROT_CFG
// Reserved (31:27)
// PROT_TXOP(25:20) -- 111111
// PROT_NAV(19:18) -- 01 (Short NAV protection)
// PROT_CTRL(17:16) -- 00 (None)
// PROT_RATE(15:0) -- 0x4084 (duplicate OFDM 24M)
Protect[3] = 0x03f44084;
// CF20_PROT_CFG
// Reserved (31:27)
// PROT_TXOP(25:20) -- 010111
// PROT_NAV(19:18) -- 01 (Short NAV protection)
// PROT_CTRL(17:16) -- 00 (None)
// PROT_RATE(15:0) -- 0x4004 (OFDM 24M)
Protect[4] = 0x01744004;
// CF40_PROT_CFG
// Reserved (31:27)
// PROT_TXOP(25:20) -- 111111
// PROT_NAV(19:18) -- 01 (Short NAV protection)
// PROT_CTRL(17:16) -- 00 (None)
// PROT_RATE(15:0) -- 0x4084 (duplicate OFDM 24M)
Protect[5] = 0x03f44084;
pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
offset = CCK_PROT_CFG;
for (i = 0;i < 6;i++)
RTMP_IO_WRITE32(pAd, offset + i*4, Protect[i]);
}
/* There are two ways to convert Rssi */
/* the way used with GET_LNA_GAIN() */
CHAR ATEConvertToRssi(
IN PRTMP_ADAPTER pAd,
IN CHAR Rssi,
IN UCHAR RssiNumber)
{
UCHAR RssiOffset, LNAGain;
// Rssi equals to zero should be an invalid value
if (Rssi == 0)
return -99;
LNAGain = GET_LNA_GAIN(pAd);
if (pAd->LatchRfRegs.Channel > 14)
{
if (RssiNumber == 0)
RssiOffset = pAd->ARssiOffset0;
else if (RssiNumber == 1)
RssiOffset = pAd->ARssiOffset1;
else
RssiOffset = pAd->ARssiOffset2;
}
else
{
if (RssiNumber == 0)
RssiOffset = pAd->BGRssiOffset0;
else if (RssiNumber == 1)
RssiOffset = pAd->BGRssiOffset1;
else
RssiOffset = pAd->BGRssiOffset2;
}
return (-12 - RssiOffset - LNAGain - Rssi);
}
/*
========================================================================
Routine Description:
Set Japan filter coefficients if needed.
Note:
This routine should only be called when
entering TXFRAME mode or TXCONT mode.
========================================================================
*/
static VOID SetJapanFilter(
IN PRTMP_ADAPTER pAd)
{
UCHAR BbpData = 0;
//
// If Channel=14 and Bandwidth=20M and Mode=CCK, set BBP R4 bit5=1
// (Japan Tx filter coefficients)when (TXFRAME or TXCONT).
//
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BbpData);
if ((pAd->ate.TxWI.PHYMODE == MODE_CCK) && (pAd->ate.Channel == 14) && (pAd->ate.TxWI.BW == BW_20))
{
BbpData |= 0x20; // turn on
ATEDBGPRINT(RT_DEBUG_TRACE, ("SetJapanFilter!!!\n"));
}
else
{
BbpData &= 0xdf; // turn off
ATEDBGPRINT(RT_DEBUG_TRACE, ("ClearJapanFilter!!!\n"));
}
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BbpData);
}
VOID ATESampleRssi(
IN PRTMP_ADAPTER pAd,
IN PRXWI_STRUC pRxWI)
{
/* There are two ways to collect RSSI. */
// pAd->LastRxRate = (USHORT)((pRxWI->MCS) + (pRxWI->BW <<7) + (pRxWI->ShortGI <<8)+ (pRxWI->PHYMODE <<14)) ;
if (pRxWI->RSSI0 != 0)
{
pAd->ate.LastRssi0 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI0, RSSI_0);
pAd->ate.AvgRssi0X8 = (pAd->ate.AvgRssi0X8 - pAd->ate.AvgRssi0) + pAd->ate.LastRssi0;
pAd->ate.AvgRssi0 = pAd->ate.AvgRssi0X8 >> 3;
}
if (pRxWI->RSSI1 != 0)
{
pAd->ate.LastRssi1 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI1, RSSI_1);
pAd->ate.AvgRssi1X8 = (pAd->ate.AvgRssi1X8 - pAd->ate.AvgRssi1) + pAd->ate.LastRssi1;
pAd->ate.AvgRssi1 = pAd->ate.AvgRssi1X8 >> 3;
}
if (pRxWI->RSSI2 != 0)
{
pAd->ate.LastRssi2 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI2, RSSI_2);
pAd->ate.AvgRssi2X8 = (pAd->ate.AvgRssi2X8 - pAd->ate.AvgRssi2) + pAd->ate.LastRssi2;
pAd->ate.AvgRssi2 = pAd->ate.AvgRssi2X8 >> 3;
}
pAd->ate.LastSNR0 = (CHAR)(pRxWI->SNR0);// CHAR ==> UCHAR ?
pAd->ate.LastSNR1 = (CHAR)(pRxWI->SNR1);// CHAR ==> UCHAR ?
pAd->ate.NumOfAvgRssiSample ++;
}
#ifdef CONFIG_STA_SUPPORT
VOID RTMPStationStop(
IN PRTMP_ADAPTER pAd)
{
// BOOLEAN Cancelled;
ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStop\n"));
// For rx statistics, we need to keep this timer running.
// RTMPCancelTimer(&pAd->Mlme.PeriodicTimer, &Cancelled);
ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStop\n"));
}
VOID RTMPStationStart(
IN PRTMP_ADAPTER pAd)
{
ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStart\n"));
#ifdef RTMP_MAC_PCI
pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
/* We did not cancel this timer when entering ATE mode. */
// RTMPSetTimer(&pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
#endif // RTMP_MAC_PCI //
ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStart\n"));
}
#endif // CONFIG_STA_SUPPORT //
/*
==========================================================================
Description:
Setup Frame format.
NOTE:
This routine should only be used in ATE mode.
==========================================================================
*/
#ifdef RTMP_MAC_PCI
static INT ATESetUpFrame(
IN PRTMP_ADAPTER pAd,
IN UINT32 TxIdx)
{
UINT j;
PTXD_STRUC pTxD;
#ifdef RT_BIG_ENDIAN
PTXD_STRUC pDestTxD;
TXD_STRUC TxD;
#endif
PNDIS_PACKET pPacket;
PUCHAR pDest;
PVOID AllocVa;
NDIS_PHYSICAL_ADDRESS AllocPa;
HTTRANSMIT_SETTING TxHTPhyMode;
PRTMP_TX_RING pTxRing = &pAd->TxRing[QID_AC_BE];
PTXWI_STRUC pTxWI = (PTXWI_STRUC) pTxRing->Cell[TxIdx].DmaBuf.AllocVa;
PUCHAR pDMAHeaderBufVA = (PUCHAR) pTxRing->Cell[TxIdx].DmaBuf.AllocVa;
#ifdef RALINK_28xx_QA
PHEADER_802_11 pHeader80211;
#endif // RALINK_28xx_QA //
if (pAd->ate.bQATxStart == TRUE)
{
// always use QID_AC_BE and FIFO_EDCA
// fill TxWI
TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
TxHTPhyMode.field.STBC = 0;
TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
ATEWriteTxWI(pAd, pTxWI, pAd->ate.TxWI.FRAG, pAd->ate.TxWI.CFACK,
pAd->ate.TxWI.TS, pAd->ate.TxWI.AMPDU, pAd->ate.TxWI.ACK, pAd->ate.TxWI.NSEQ,
pAd->ate.TxWI.BAWinSize, 0, pAd->ate.TxWI.MPDUtotalByteCount, pAd->ate.TxWI.PacketId, 0, 0,
pAd->ate.TxWI.txop/*IFS_HTTXOP*/, pAd->ate.TxWI.CFACK/*FALSE*/, &TxHTPhyMode);
}
else
{
TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
TxHTPhyMode.field.STBC = 0;
TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
ATEWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
4, 0, pAd->ate.TxLength, 0, 0, 0, IFS_HTTXOP, FALSE, &TxHTPhyMode);
}
// fill 802.11 header
#ifdef RALINK_28xx_QA
if (pAd->ate.bQATxStart == TRUE)
{
NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE, pAd->ate.Header, pAd->ate.HLen);
}
else
#endif // RALINK_28xx_QA //
{
NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE, TemplateFrame, LENGTH_802_11);
NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE+4, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE+10, pAd->ate.Addr2, ETH_LENGTH_OF_ADDRESS);
NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE+16, pAd->ate.Addr3, ETH_LENGTH_OF_ADDRESS);
}
#ifdef RT_BIG_ENDIAN
RTMPFrameEndianChange(pAd, (((PUCHAR)pDMAHeaderBufVA)+TXWI_SIZE), DIR_READ, FALSE);
#endif // RT_BIG_ENDIAN //
/* alloc buffer for payload */
#ifdef RALINK_28xx_QA
if (pAd->ate.bQATxStart == TRUE)
{
pPacket = RTMP_AllocateRxPacketBuffer(pAd, pAd->ate.DLen + 0x100, FALSE, &AllocVa, &AllocPa);
}
else
#endif // RALINK_28xx_QA //
{
pPacket = RTMP_AllocateRxPacketBuffer(pAd, pAd->ate.TxLength, FALSE, &AllocVa, &AllocPa);
}
if (pPacket == NULL)
{
pAd->ate.TxCount = 0;
ATEDBGPRINT(RT_DEBUG_TRACE, ("%s fail to alloc packet space.\n", __FUNCTION__));
return -1;
}
pTxRing->Cell[TxIdx].pNextNdisPacket = pPacket;
pDest = (PUCHAR) AllocVa;
#ifdef RALINK_28xx_QA
if (pAd->ate.bQATxStart == TRUE)
{
RTPKT_TO_OSPKT(pPacket)->len = pAd->ate.DLen;
}
else
#endif // RALINK_28xx_QA //
{
RTPKT_TO_OSPKT(pPacket)->len = pAd->ate.TxLength - LENGTH_802_11;
}
// prepare frame payload
#ifdef RALINK_28xx_QA
if (pAd->ate.bQATxStart == TRUE)
{
// copy pattern
if ((pAd->ate.PLen != 0))
{
int j;
for (j = 0; j < pAd->ate.DLen; j+=pAd->ate.PLen)
{
memcpy(RTPKT_TO_OSPKT(pPacket)->data + j, pAd->ate.Pattern, pAd->ate.PLen);
}
}
}
else
#endif // RALINK_28xx_QA //
{
for (j = 0; j < RTPKT_TO_OSPKT(pPacket)->len; j++)
{
pDest[j] = 0xA5;
}
}
/* build Tx Descriptor */
#ifndef RT_BIG_ENDIAN
pTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
#else
pDestTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
TxD = *pDestTxD;
pTxD = &TxD;
#endif // !RT_BIG_ENDIAN //
#ifdef RALINK_28xx_QA
if (pAd->ate.bQATxStart == TRUE)
{
// prepare TxD
NdisZeroMemory(pTxD, TXD_SIZE);
RTMPWriteTxDescriptor(pAd, pTxD, FALSE, FIFO_EDCA);
// build TX DESC
pTxD->SDPtr0 = RTMP_GetPhysicalAddressLow(pTxRing->Cell[TxIdx].DmaBuf.AllocPa);
pTxD->SDLen0 = TXWI_SIZE + pAd->ate.HLen;
pTxD->LastSec0 = 0;
pTxD->SDPtr1 = AllocPa;
pTxD->SDLen1 = RTPKT_TO_OSPKT(pPacket)->len;
pTxD->LastSec1 = 1;
pDest = (PUCHAR)pTxWI;
pDest += TXWI_SIZE;
pHeader80211 = (PHEADER_802_11)pDest;
// modify sequence number...
if (pAd->ate.TxDoneCount == 0)
{
pAd->ate.seq = pHeader80211->Sequence;
}
else
pHeader80211->Sequence = ++pAd->ate.seq;
}
else
#endif // RALINK_28xx_QA //
{
NdisZeroMemory(pTxD, TXD_SIZE);
RTMPWriteTxDescriptor(pAd, pTxD, FALSE, FIFO_EDCA);
// build TX DESC
pTxD->SDPtr0 = RTMP_GetPhysicalAddressLow (pTxRing->Cell[TxIdx].DmaBuf.AllocPa);
pTxD->SDLen0 = TXWI_SIZE + LENGTH_802_11;
pTxD->LastSec0 = 0;
pTxD->SDPtr1 = AllocPa;
pTxD->SDLen1 = RTPKT_TO_OSPKT(pPacket)->len;
pTxD->LastSec1 = 1;
}
#ifdef RT_BIG_ENDIAN
RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
RTMPFrameEndianChange(pAd, (((PUCHAR)pDMAHeaderBufVA)+TXWI_SIZE), DIR_WRITE, FALSE);
RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
#endif // RT_BIG_ENDIAN //
return 0;
}
/*=======================End of RTMP_MAC_PCI =======================*/
#endif // RTMP_MAC_PCI //
VOID rt_ee_read_all(PRTMP_ADAPTER pAd, USHORT *Data)
{
USHORT i;
USHORT value;
for (i = 0 ; i < EEPROM_SIZE/2 ; )
{
/* "value" is especially for some compilers... */
RT28xx_EEPROM_READ16(pAd, i*2, value);
Data[i] = value;
i++;
}
}
VOID rt_ee_write_all(PRTMP_ADAPTER pAd, USHORT *Data)
{
USHORT i;
USHORT value;
for (i = 0 ; i < EEPROM_SIZE/2 ; )
{
/* "value" is especially for some compilers... */
value = Data[i];
RT28xx_EEPROM_WRITE16(pAd, i*2, value);
i++;
}
}
#ifdef RALINK_28xx_QA
VOID ATE_QA_Statistics(
IN PRTMP_ADAPTER pAd,
IN PRXWI_STRUC pRxWI,
IN PRT28XX_RXD_STRUC pRxD,
IN PHEADER_802_11 pHeader)
{
// update counter first
if (pHeader != NULL)
{
if (pHeader->FC.Type == BTYPE_DATA)
{
if (pRxD->U2M)
pAd->ate.U2M++;
else
pAd->ate.OtherData++;
}
else if (pHeader->FC.Type == BTYPE_MGMT)
{
if (pHeader->FC.SubType == SUBTYPE_BEACON)
pAd->ate.Beacon++;
else
pAd->ate.OtherCount++;
}
else if (pHeader->FC.Type == BTYPE_CNTL)
{
pAd->ate.OtherCount++;
}
}
pAd->ate.RSSI0 = pRxWI->RSSI0;
pAd->ate.RSSI1 = pRxWI->RSSI1;
pAd->ate.RSSI2 = pRxWI->RSSI2;
pAd->ate.SNR0 = pRxWI->SNR0;
pAd->ate.SNR1 = pRxWI->SNR1;
}
/* command id with Cmd Type == 0x0008(for 28xx)/0x0005(for iNIC) */
#define RACFG_CMD_RF_WRITE_ALL 0x0000
#define RACFG_CMD_E2PROM_READ16 0x0001
#define RACFG_CMD_E2PROM_WRITE16 0x0002
#define RACFG_CMD_E2PROM_READ_ALL 0x0003
#define RACFG_CMD_E2PROM_WRITE_ALL 0x0004
#define RACFG_CMD_IO_READ 0x0005
#define RACFG_CMD_IO_WRITE 0x0006
#define RACFG_CMD_IO_READ_BULK 0x0007
#define RACFG_CMD_BBP_READ8 0x0008
#define RACFG_CMD_BBP_WRITE8 0x0009
#define RACFG_CMD_BBP_READ_ALL 0x000a
#define RACFG_CMD_GET_COUNTER 0x000b
#define RACFG_CMD_CLEAR_COUNTER 0x000c
#define RACFG_CMD_RSV1 0x000d
#define RACFG_CMD_RSV2 0x000e
#define RACFG_CMD_RSV3 0x000f
#define RACFG_CMD_TX_START 0x0010
#define RACFG_CMD_GET_TX_STATUS 0x0011
#define RACFG_CMD_TX_STOP 0x0012
#define RACFG_CMD_RX_START 0x0013
#define RACFG_CMD_RX_STOP 0x0014
#define RACFG_CMD_GET_NOISE_LEVEL 0x0015
#define RACFG_CMD_ATE_START 0x0080
#define RACFG_CMD_ATE_STOP 0x0081
#define RACFG_CMD_ATE_START_TX_CARRIER 0x0100
#define RACFG_CMD_ATE_START_TX_CONT 0x0101
#define RACFG_CMD_ATE_START_TX_FRAME 0x0102
#define RACFG_CMD_ATE_SET_BW 0x0103
#define RACFG_CMD_ATE_SET_TX_POWER0 0x0104
#define RACFG_CMD_ATE_SET_TX_POWER1 0x0105
#define RACFG_CMD_ATE_SET_FREQ_OFFSET 0x0106
#define RACFG_CMD_ATE_GET_STATISTICS 0x0107
#define RACFG_CMD_ATE_RESET_COUNTER 0x0108
#define RACFG_CMD_ATE_SEL_TX_ANTENNA 0x0109
#define RACFG_CMD_ATE_SEL_RX_ANTENNA 0x010a
#define RACFG_CMD_ATE_SET_PREAMBLE 0x010b
#define RACFG_CMD_ATE_SET_CHANNEL 0x010c
#define RACFG_CMD_ATE_SET_ADDR1 0x010d
#define RACFG_CMD_ATE_SET_ADDR2 0x010e
#define RACFG_CMD_ATE_SET_ADDR3 0x010f
#define RACFG_CMD_ATE_SET_RATE 0x0110
#define RACFG_CMD_ATE_SET_TX_FRAME_LEN 0x0111
#define RACFG_CMD_ATE_SET_TX_FRAME_COUNT 0x0112
#define RACFG_CMD_ATE_START_RX_FRAME 0x0113
#define RACFG_CMD_ATE_E2PROM_READ_BULK 0x0114
#define RACFG_CMD_ATE_E2PROM_WRITE_BULK 0x0115
#define RACFG_CMD_ATE_IO_WRITE_BULK 0x0116
#define RACFG_CMD_ATE_BBP_READ_BULK 0x0117
#define RACFG_CMD_ATE_BBP_WRITE_BULK 0x0118
#define RACFG_CMD_ATE_RF_READ_BULK 0x0119
#define RACFG_CMD_ATE_RF_WRITE_BULK 0x011a
static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len);
VOID RtmpDoAte(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq)
{
USHORT Command_Id;
INT Status = NDIS_STATUS_SUCCESS;
struct ate_racfghdr *pRaCfg;
if ((pRaCfg = kmalloc(sizeof(struct ate_racfghdr), GFP_KERNEL)) == NULL)
{
Status = -EINVAL;
return;
}
NdisZeroMemory(pRaCfg, sizeof(struct ate_racfghdr));
if (copy_from_user((PUCHAR)pRaCfg, wrq->u.data.pointer, wrq->u.data.length))
{
Status = -EFAULT;
kfree(pRaCfg);
return;
}
Command_Id = ntohs(pRaCfg->command_id);
ATEDBGPRINT(RT_DEBUG_TRACE,("\n%s: Command_Id = 0x%04x !\n", __FUNCTION__, Command_Id));
switch (Command_Id)
{
/* We will get this command when QA starts. */
case RACFG_CMD_ATE_START:
Status=DO_RACFG_CMD_ATE_START(pAdapter,wrq,pRaCfg);
break;
/* We will get this command either QA is closed or ated is killed by user. */
case RACFG_CMD_ATE_STOP:
Status=DO_RACFG_CMD_ATE_STOP(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_RF_WRITE_ALL:
Status=DO_RACFG_CMD_RF_WRITE_ALL(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_E2PROM_READ16:
Status=DO_RACFG_CMD_E2PROM_READ16(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_E2PROM_WRITE16:
Status=DO_RACFG_CMD_E2PROM_WRITE16(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_E2PROM_READ_ALL:
Status=DO_RACFG_CMD_E2PROM_READ_ALL(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_E2PROM_WRITE_ALL:
Status=DO_RACFG_CMD_E2PROM_WRITE_ALL(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_IO_READ:
Status=DO_RACFG_CMD_IO_READ(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_IO_WRITE:
Status=DO_RACFG_CMD_IO_WRITE(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_IO_READ_BULK:
Status=DO_RACFG_CMD_IO_READ_BULK(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_BBP_READ8:
Status=DO_RACFG_CMD_BBP_READ8(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_BBP_WRITE8:
Status=DO_RACFG_CMD_BBP_WRITE8(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_BBP_READ_ALL:
Status=DO_RACFG_CMD_BBP_READ_ALL(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_E2PROM_READ_BULK:
Status=DO_RACFG_CMD_ATE_E2PROM_READ_BULK(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_E2PROM_WRITE_BULK:
Status=DO_RACFG_CMD_ATE_E2PROM_WRITE_BULK(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_IO_WRITE_BULK:
Status=DO_RACFG_CMD_ATE_IO_WRITE_BULK(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_BBP_READ_BULK:
Status=DO_RACFG_CMD_ATE_BBP_READ_BULK(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_BBP_WRITE_BULK:
Status=DO_RACFG_CMD_ATE_BBP_WRITE_BULK(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_GET_NOISE_LEVEL:
Status=DO_RACFG_CMD_GET_NOISE_LEVEL(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_GET_COUNTER:
Status=DO_RACFG_CMD_GET_COUNTER(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_CLEAR_COUNTER:
Status=DO_RACFG_CMD_CLEAR_COUNTER(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_TX_START:
Status=DO_RACFG_CMD_TX_START(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_GET_TX_STATUS:
Status=DO_RACFG_CMD_GET_TX_STATUS(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_TX_STOP:
Status=DO_RACFG_CMD_TX_STOP(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_RX_START:
Status=DO_RACFG_CMD_RX_START(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_RX_STOP:
Status=DO_RACFG_CMD_RX_STOP(pAdapter,wrq,pRaCfg);
break;
/* The following cases are for new ATE GUI(not QA). */
/*==================================================*/
case RACFG_CMD_ATE_START_TX_CARRIER:
Status=DO_RACFG_CMD_ATE_START_TX_CARRIER(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_START_TX_CONT:
Status=DO_RACFG_CMD_ATE_START_TX_CONT(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_START_TX_FRAME:
Status=DO_RACFG_CMD_ATE_START_TX_FRAME(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_BW:
Status=DO_RACFG_CMD_ATE_SET_BW(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_TX_POWER0:
Status=DO_RACFG_CMD_ATE_SET_TX_POWER0(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_TX_POWER1:
Status=DO_RACFG_CMD_ATE_SET_TX_POWER1(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_FREQ_OFFSET:
Status=DO_RACFG_CMD_ATE_SET_TX_POWER1(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_GET_STATISTICS:
Status=DO_RACFG_CMD_ATE_GET_STATISTICS(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_RESET_COUNTER:
Status=DO_RACFG_CMD_ATE_RESET_COUNTER(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SEL_TX_ANTENNA:
Status=DO_RACFG_CMD_ATE_SEL_TX_ANTENNA(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SEL_RX_ANTENNA:
Status=DO_RACFG_CMD_ATE_SEL_TX_ANTENNA(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_PREAMBLE:
Status=DO_RACFG_CMD_ATE_SET_PREAMBLE(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_CHANNEL:
Status=DO_RACFG_CMD_ATE_SET_CHANNEL(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_ADDR1:
Status=DO_RACFG_CMD_ATE_SET_ADDR1(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_ADDR2:
Status=DO_RACFG_CMD_ATE_SET_ADDR2(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_ADDR3:
Status=DO_RACFG_CMD_ATE_SET_ADDR3(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_RATE:
Status=DO_RACFG_CMD_ATE_SET_RATE(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_TX_FRAME_LEN:
Status=DO_RACFG_CMD_ATE_SET_TX_FRAME_LEN(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_SET_TX_FRAME_COUNT:
Status=DO_RACFG_CMD_ATE_SET_TX_FRAME_COUNT(pAdapter,wrq,pRaCfg);
break;
case RACFG_CMD_ATE_START_RX_FRAME:
Status=DO_RACFG_CMD_ATE_START_RX_FRAME(pAdapter,wrq,pRaCfg);
break;
default:
break;
}
ASSERT(pRaCfg != NULL);
if (pRaCfg != NULL)
kfree(pRaCfg);
return;
}
VOID BubbleSort(INT32 n, INT32 a[])
{
INT32 k, j, temp;
for (k = n-1; k>0; k--)
{
for (j = 0; j<k; j++)
{
if (a[j] > a[j+1])
{
temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
VOID CalNoiseLevel(PRTMP_ADAPTER pAd, UCHAR channel, INT32 RSSI[3][10])
{
INT32 RSSI0, RSSI1, RSSI2;
CHAR Rssi0Offset, Rssi1Offset, Rssi2Offset;
UCHAR BbpR50Rssi0 = 0, BbpR51Rssi1 = 0, BbpR52Rssi2 = 0;
UCHAR Org_BBP66value = 0, Org_BBP69value = 0, Org_BBP70value = 0, data = 0;
USHORT LNA_Gain = 0;
INT32 j = 0;
UCHAR Org_Channel = pAd->ate.Channel;
USHORT GainValue = 0, OffsetValue = 0;
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &Org_BBP66value);
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R69, &Org_BBP69value);
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R70, &Org_BBP70value);
//**********************************************************************
// Read the value of LNA gain and Rssi offset
//**********************************************************************
RT28xx_EEPROM_READ16(pAd, EEPROM_LNA_OFFSET, GainValue);
// for Noise Level
if (channel <= 14)
{
LNA_Gain = GainValue & 0x00FF;
RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET, OffsetValue);
Rssi0Offset = OffsetValue & 0x00FF;
Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_BG_OFFSET + 2)/* 0x48 */, OffsetValue);
Rssi2Offset = OffsetValue & 0x00FF;
}
else
{
LNA_Gain = (GainValue & 0xFF00) >> 8;
RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_A_OFFSET, OffsetValue);
Rssi0Offset = OffsetValue & 0x00FF;
Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_A_OFFSET + 2)/* 0x4C */, OffsetValue);
Rssi2Offset = OffsetValue & 0x00FF;
}
//**********************************************************************
{
pAd->ate.Channel = channel;
ATEAsicSwitchChannel(pAd);
mdelay(5);
data = 0x10;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, data);
data = 0x40;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, data);
data = 0x40;
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, data);
mdelay(5);
// start Rx
pAd->ate.bQARxStart = TRUE;
Set_ATE_Proc(pAd, "RXFRAME");
mdelay(5);
for (j = 0; j < 10; j++)
{
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R50, &BbpR50Rssi0);
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R51, &BbpR51Rssi1);
ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R52, &BbpR52Rssi2);
mdelay(10);
// calculate RSSI 0
if (BbpR50Rssi0 == 0)
{
RSSI0 = -100;
}
else
{
RSSI0 = (INT32)(-12 - BbpR50Rssi0 - LNA_Gain - Rssi0Offset);
}
RSSI[0][j] = RSSI0;
if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
{
// calculate RSSI 1
if (BbpR51Rssi1 == 0)
{
RSSI1 = -100;
}
else
{
RSSI1 = (INT32)(-12 - BbpR51Rssi1 - LNA_Gain - Rssi1Offset);
}
RSSI[1][j] = RSSI1;
}
if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
{
// calculate RSSI 2
if (BbpR52Rssi2 == 0)
RSSI2 = -100;
else
RSSI2 = (INT32)(-12 - BbpR52Rssi2 - LNA_Gain - Rssi2Offset);
RSSI[2][j] = RSSI2;
}
}
// stop Rx
Set_ATE_Proc(pAd, "RXSTOP");
mdelay(5);
BubbleSort(10, RSSI[0]); // 1R
if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
{
BubbleSort(10, RSSI[1]);
}
if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
{
BubbleSort(10, RSSI[2]);
}
}
pAd->ate.Channel = Org_Channel;
ATEAsicSwitchChannel(pAd);
// restore original value
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, Org_BBP66value);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, Org_BBP69value);
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, Org_BBP70value);
return;
}
BOOLEAN SyncTxRxConfig(PRTMP_ADAPTER pAd, USHORT offset, UCHAR value)
{
UCHAR tmp = 0, bbp_data = 0;
if (ATE_ON(pAd))
{
ATE_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
}
else
{
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
}
/* confirm again */
ASSERT(bbp_data == value);
switch (offset)
{
case BBP_R1:
/* Need to synchronize tx configuration with legacy ATE. */
tmp = (bbp_data & ((1 << 4) | (1 << 3))/* 0x18 */) >> 3;
switch (tmp)
{
/* The BBP R1 bit[4:3] = 2 :: Both DACs will be used by QA. */
case 2:
/* All */
pAd->ate.TxAntennaSel = 0;
break;
/* The BBP R1 bit[4:3] = 0 :: DAC 0 will be used by QA. */
case 0:
/* Antenna one */
pAd->ate.TxAntennaSel = 1;
break;
/* The BBP R1 bit[4:3] = 1 :: DAC 1 will be used by QA. */
case 1:
/* Antenna two */
pAd->ate.TxAntennaSel = 2;
break;
default:
DBGPRINT(RT_DEBUG_TRACE, ("%s -- Sth. wrong! : return FALSE; \n", __FUNCTION__));
return FALSE;
}
break;/* case BBP_R1 */
case BBP_R3:
/* Need to synchronize rx configuration with legacy ATE. */
tmp = (bbp_data & ((1 << 1) | (1 << 0))/* 0x03 */);
switch(tmp)
{
/* The BBP R3 bit[1:0] = 3 :: All ADCs will be used by QA. */
case 3:
/* All */
pAd->ate.RxAntennaSel = 0;
break;
/*
The BBP R3 bit[1:0] = 0 :: ADC 0 will be used by QA,
unless the BBP R3 bit[4:3] = 2
*/
case 0:
/* Antenna one */
pAd->ate.RxAntennaSel = 1;
tmp = ((bbp_data & ((1 << 4) | (1 << 3))/* 0x03 */) >> 3);
if (tmp == 2)// 3R
{
/* Default : All ADCs will be used by QA */
pAd->ate.RxAntennaSel = 0;
}
break;
/* The BBP R3 bit[1:0] = 1 :: ADC 1 will be used by QA. */
case 1:
/* Antenna two */
pAd->ate.RxAntennaSel = 2;
break;
/* The BBP R3 bit[1:0] = 2 :: ADC 2 will be used by QA. */
case 2:
/* Antenna three */
pAd->ate.RxAntennaSel = 3;
break;
default:
DBGPRINT(RT_DEBUG_ERROR, ("%s -- Impossible! : return FALSE; \n", __FUNCTION__));
return FALSE;
}
break;/* case BBP_R3 */
default:
DBGPRINT(RT_DEBUG_ERROR, ("%s -- Sth. wrong! : return FALSE; \n", __FUNCTION__));
return FALSE;
}
return TRUE;
}
static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
{
ULONG i, Value = 0;
ULONG *pDst, *pSrc;
UCHAR *p8;
p8 = src;
pDst = (ULONG *) dst;
pSrc = (ULONG *) src;
for (i = 0 ; i < (len/4); i++)
{
/* For alignment issue, we need a variable "Value". */
memmove(&Value, pSrc, 4);
Value = htonl(Value);
memmove(pDst, &Value, 4);
pDst++;
pSrc++;
}
if ((len % 4) != 0)
{
/* wish that it will never reach here */
memmove(&Value, pSrc, (len % 4));
Value = htonl(Value);
memmove(pDst, &Value, (len % 4));
}
}
static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
{
ULONG i;
UCHAR *pDst, *pSrc;
pDst = dst;
pSrc = src;
for (i = 0; i < (len/2); i++)
{
memmove(pDst, pSrc, 2);
*((USHORT *)pDst) = htons(*((USHORT *)pDst));
pDst+=2;
pSrc+=2;
}
if ((len % 2) != 0)
{
memmove(pDst, pSrc, 1);
}
}
static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len)
{
UINT32 i, Value;
UINT32 *pDst, *pSrc;
pDst = (UINT32 *) dst;
pSrc = (UINT32 *) src;
for (i = 0 ; i < (len/4); i++)
{
RTMP_IO_READ32(pAd, (ULONG)pSrc, &Value);
Value = htonl(Value);
memmove(pDst, &Value, 4);
pDst++;
pSrc++;
}
return;
}
INT Set_TxStop_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("Set_TxStop_Proc\n"));
if (Set_ATE_Proc(pAd, "TXSTOP"))
{
return TRUE;
}
else
{
return FALSE;
}
}
INT Set_RxStop_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("Set_RxStop_Proc\n"));
if (Set_ATE_Proc(pAd, "RXSTOP"))
{
return TRUE;
}
else
{
return FALSE;
}
}
#ifdef DBG
INT Set_EERead_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
USHORT buffer[EEPROM_SIZE/2];
USHORT *p;
INT i;
rt_ee_read_all(pAd, (USHORT *)buffer);
p = buffer;
for (i = 0; i < (EEPROM_SIZE/2); i++)
{
ate_print(KERN_EMERG "%4.4x ", *p);
if (((i+1) % 16) == 0)
ate_print(KERN_EMERG "\n");
p++;
}
return TRUE;
}
INT Set_EEWrite_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
USHORT offset = 0, value;
PSTRING p2 = arg;
while ((*p2 != ':') && (*p2 != '\0'))
{
p2++;
}
if (*p2 == ':')
{
A2Hex(offset, arg);
A2Hex(value, p2 + 1);
}
else
{
A2Hex(value, arg);
}
if (offset >= EEPROM_SIZE)
{
ate_print(KERN_EMERG "Offset can not exceed EEPROM_SIZE( == 0x%04x)\n", EEPROM_SIZE);
return FALSE;
}
RT28xx_EEPROM_WRITE16(pAd, offset, value);
return TRUE;
}
INT Set_BBPRead_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
UCHAR value = 0, offset;
A2Hex(offset, arg);
if (ATE_ON(pAd))
{
ATE_BBP_IO_READ8_BY_REG_ID(pAd, offset, &value);
}
else
{
RTMP_BBP_IO_READ8_BY_REG_ID(pAd, offset, &value);
}
ate_print(KERN_EMERG "%x\n", value);
return TRUE;
}
INT Set_BBPWrite_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
USHORT offset = 0;
PSTRING p2 = arg;
UCHAR value;
while ((*p2 != ':') && (*p2 != '\0'))
{
p2++;
}
if (*p2 == ':')
{
A2Hex(offset, arg);
A2Hex(value, p2 + 1);
}
else
{
A2Hex(value, arg);
}
if (ATE_ON(pAd))
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, offset, value);
}
else
{
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, offset, value);
}
return TRUE;
}
INT Set_RFWrite_Proc(
IN PRTMP_ADAPTER pAd,
IN PSTRING arg)
{
PSTRING p2, p3, p4;
UINT32 R1, R2, R3, R4;
p2 = arg;
while ((*p2 != ':') && (*p2 != '\0'))
{
p2++;
}
if (*p2 != ':')
return FALSE;
p3 = p2 + 1;
while((*p3 != ':') && (*p3 != '\0'))
{
p3++;
}
if (*p3 != ':')
return FALSE;
p4 = p3 + 1;
while ((*p4 != ':') && (*p4 != '\0'))
{
p4++;
}
if (*p4 != ':')
return FALSE;
A2Hex(R1, arg);
A2Hex(R2, p2 + 1);
A2Hex(R3, p3 + 1);
A2Hex(R4, p4 + 1);
RTMP_RF_IO_WRITE32(pAd, R1);
RTMP_RF_IO_WRITE32(pAd, R2);
RTMP_RF_IO_WRITE32(pAd, R3);
RTMP_RF_IO_WRITE32(pAd, R4);
return TRUE;
}
#endif // DBG //
#endif // RALINK_28xx_QA //
#ifdef RALINK_28xx_QA
#define LEN_OF_ARG 16
#define RESPONSE_TO_GUI(__pRaCfg, __pwrq, __Length, __Status) \
(__pRaCfg)->length = htons((__Length)); \
(__pRaCfg)->status = htons((__Status)); \
(__pwrq)->u.data.length = sizeof((__pRaCfg)->magic_no) + sizeof((__pRaCfg)->command_type) \
+ sizeof((__pRaCfg)->command_id) + sizeof((__pRaCfg)->length) \
+ sizeof((__pRaCfg)->sequence) + ntohs((__pRaCfg)->length); \
ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", (__pwrq)->u.data.length)); \
if (copy_to_user((__pwrq)->u.data.pointer, (UCHAR *)(__pRaCfg), (__pwrq)->u.data.length)) \
{ \
ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in %s\n", __FUNCTION__)); \
return (-EFAULT); \
} \
else \
{ \
ATEDBGPRINT(RT_DEBUG_TRACE, ("%s is done !\n", __FUNCTION__)); \
}
static inline INT DO_RACFG_CMD_ATE_START(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START\n"));
/* Prepare feedback as soon as we can to avoid QA timeout. */
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
Set_ATE_Proc(pAdapter, "ATESTART");
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_STOP(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
INT32 ret;
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_STOP\n"));
/*
Distinguish this command came from QA(via ate agent)
or ate agent according to the existence of pid in payload.
No need to prepare feedback if this cmd came directly from ate agent,
not from QA.
*/
pRaCfg->length = ntohs(pRaCfg->length);
if (pRaCfg->length == sizeof(pAdapter->ate.AtePid))
{
/*
This command came from QA.
Get the pid of ATE agent.
*/
memcpy((UCHAR *)&pAdapter->ate.AtePid,
(&pRaCfg->data[0]) - 2/* == sizeof(pRaCfg->status) */,
sizeof(pAdapter->ate.AtePid));
/* Prepare feedback as soon as we can to avoid QA timeout. */
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
/*
Kill ATE agent when leaving ATE mode.
We must kill ATE agent first before setting ATESTOP,
or Microsoft will report sth. wrong.
*/
ret = KILL_THREAD_PID(pAdapter->ate.AtePid, SIGTERM, 1);
if (ret)
{
ATEDBGPRINT(RT_DEBUG_ERROR, ("%s: unable to kill ate thread\n", pAdapter->net_dev->name));
}
}
/* AP/STA might have in ATE_STOP mode due to cmd from QA. */
if (ATE_ON(pAdapter))
{
/* Someone has killed ate agent while QA GUI is still open. */
Set_ATE_Proc(pAdapter, "ATESTOP");
ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_AP_START is done !\n"));
}
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_RF_WRITE_ALL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UINT32 R1, R2, R3, R4;
USHORT channel;
memcpy(&R1, pRaCfg->data-2, 4);
memcpy(&R2, pRaCfg->data+2, 4);
memcpy(&R3, pRaCfg->data+6, 4);
memcpy(&R4, pRaCfg->data+10, 4);
memcpy(&channel, pRaCfg->data+14, 2);
pAdapter->LatchRfRegs.R1 = ntohl(R1);
pAdapter->LatchRfRegs.R2 = ntohl(R2);
pAdapter->LatchRfRegs.R3 = ntohl(R3);
pAdapter->LatchRfRegs.R4 = ntohl(R4);
pAdapter->LatchRfRegs.Channel = ntohs(channel);
RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R1);
RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R2);
RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R3);
RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R4);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_E2PROM_READ16(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UINT16 offset=0, value=0;
USHORT tmp=0;
offset = ntohs(pRaCfg->status);
/* "tmp" is especially for some compilers... */
RT28xx_EEPROM_READ16(pAdapter, offset, tmp);
value = tmp;
value = htons(value);
ATEDBGPRINT(RT_DEBUG_TRACE,("EEPROM Read offset = 0x%04x, value = 0x%04x\n", offset, value));
memcpy(pRaCfg->data, &value, 2);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+2, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_E2PROM_WRITE16(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT offset, value;
offset = ntohs(pRaCfg->status);
memcpy(&value, pRaCfg->data, 2);
value = ntohs(value);
RT28xx_EEPROM_WRITE16(pAdapter, offset, value);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_E2PROM_READ_ALL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT buffer[EEPROM_SIZE/2];
rt_ee_read_all(pAdapter,(USHORT *)buffer);
memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer, EEPROM_SIZE);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+EEPROM_SIZE, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_E2PROM_WRITE_ALL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT buffer[EEPROM_SIZE/2];
NdisZeroMemory((UCHAR *)buffer, EEPROM_SIZE);
memcpy_exs(pAdapter, (UCHAR *)buffer, (UCHAR *)&pRaCfg->status, EEPROM_SIZE);
rt_ee_write_all(pAdapter,(USHORT *)buffer);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_IO_READ(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UINT32 offset;
UINT32 value;
memcpy(&offset, &pRaCfg->status, 4);
offset = ntohl(offset);
/*
We do not need the base address.
So just extract the offset out.
*/
offset &= 0x0000FFFF;
RTMP_IO_READ32(pAdapter, offset, &value);
value = htonl(value);
memcpy(pRaCfg->data, &value, 4);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+4, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_IO_WRITE(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UINT32 offset, value;
memcpy(&offset, pRaCfg->data-2, 4);
memcpy(&value, pRaCfg->data+2, 4);
offset = ntohl(offset);
/*
We do not need the base address.
So just extract the offset out.
*/
offset &= 0x0000FFFF;
value = ntohl(value);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_IO_WRITE: offset = %x, value = %x\n", offset, value));
RTMP_IO_WRITE32(pAdapter, offset, value);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_IO_READ_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UINT32 offset;
USHORT len;
memcpy(&offset, &pRaCfg->status, 4);
offset = ntohl(offset);
/*
We do not need the base address.
So just extract the offset out.
*/
offset &= 0x0000FFFF;
memcpy(&len, pRaCfg->data+2, 2);
len = ntohs(len);
if (len > 371)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("length requested is too large, make it smaller\n"));
pRaCfg->length = htons(2);
pRaCfg->status = htons(1);
return -EFAULT;
}
RTMP_IO_READ_BULK(pAdapter, pRaCfg->data, (UCHAR *)offset, len*4);// unit in four bytes
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+(len*4), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_BBP_READ8(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT offset;
UCHAR value;
value = 0;
offset = ntohs(pRaCfg->status);
if (ATE_ON(pAdapter))
{
ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, offset, &value);
}
else
{
RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, offset, &value);
}
pRaCfg->data[0] = value;
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+1, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_BBP_WRITE8(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT offset;
UCHAR value;
offset = ntohs(pRaCfg->status);
memcpy(&value, pRaCfg->data, 1);
if (ATE_ON(pAdapter))
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset, value);
}
else
{
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset, value);
}
if ((offset == BBP_R1) || (offset == BBP_R3))
{
SyncTxRxConfig(pAdapter, offset, value);
}
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_BBP_READ_ALL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT bbp_reg_index;
for (bbp_reg_index = 0; bbp_reg_index < MAX_BBP_ID+1; bbp_reg_index++)
{
pRaCfg->data[bbp_reg_index] = 0;
if (ATE_ON(pAdapter))
{
ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbp_reg_index, &pRaCfg->data[bbp_reg_index]);
}
else
{
RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbp_reg_index, &pRaCfg->data[bbp_reg_index]);
}
}
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+MAX_BBP_ID+1, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_GET_NOISE_LEVEL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UCHAR channel;
INT32 buffer[3][10];/* 3 : RxPath ; 10 : no. of per rssi samples */
channel = (ntohs(pRaCfg->status) & 0x00FF);
CalNoiseLevel(pAdapter, channel, buffer);
memcpy_exl(pAdapter, (UCHAR *)pRaCfg->data, (UCHAR *)&(buffer[0][0]), (sizeof(INT32)*3*10));
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+(sizeof(INT32)*3*10), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_GET_COUNTER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.U2M, 4);
memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->ate.OtherData, 4);
memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->ate.Beacon, 4);
memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->ate.OtherCount, 4);
memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->ate.TxAc0, 4);
memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->ate.TxAc1, 4);
memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->ate.TxAc2, 4);
memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->ate.TxAc3, 4);
/*memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->ate.TxHCCA, 4);*/
memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->ate.TxMgmt, 4);
memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&pAdapter->ate.RSSI0, 4);
memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&pAdapter->ate.RSSI1, 4);
memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&pAdapter->ate.RSSI2, 4);
memcpy_exl(pAdapter, &pRaCfg->data[52], (UCHAR *)&pAdapter->ate.SNR0, 4);
memcpy_exl(pAdapter, &pRaCfg->data[56], (UCHAR *)&pAdapter->ate.SNR1, 4);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+60, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_CLEAR_COUNTER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
pAdapter->ate.U2M = 0;
pAdapter->ate.OtherData = 0;
pAdapter->ate.Beacon = 0;
pAdapter->ate.OtherCount = 0;
pAdapter->ate.TxAc0 = 0;
pAdapter->ate.TxAc1 = 0;
pAdapter->ate.TxAc2 = 0;
pAdapter->ate.TxAc3 = 0;
/*pAdapter->ate.TxHCCA = 0;*/
pAdapter->ate.TxMgmt = 0;
pAdapter->ate.TxDoneCount = 0;
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_TX_START(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT *p;
USHORT err = 1;
UCHAR Bbp22Value = 0, Bbp24Value = 0;
if ((pAdapter->ate.TxStatus != 0) && (pAdapter->ate.Mode & ATE_TXFRAME))
{
ATEDBGPRINT(RT_DEBUG_TRACE,("Ate Tx is already running, to run next Tx, you must stop it first\n"));
err = 2;
goto TX_START_ERROR;
}
else if ((pAdapter->ate.TxStatus != 0) && !(pAdapter->ate.Mode & ATE_TXFRAME))
{
int i = 0;
while ((i++ < 10) && (pAdapter->ate.TxStatus != 0))
{
RTMPusecDelay(5000);
}
/* force it to stop */
pAdapter->ate.TxStatus = 0;
pAdapter->ate.TxDoneCount = 0;
pAdapter->ate.bQATxStart = FALSE;
}
/*
If pRaCfg->length == 0, this "RACFG_CMD_TX_START"
is for Carrier test or Carrier Suppression.
*/
if (ntohs(pRaCfg->length) != 0)
{
/* get frame info */
NdisMoveMemory(&pAdapter->ate.TxWI, pRaCfg->data + 2, 16);
#ifdef RT_BIG_ENDIAN
RTMPWIEndianChange((PUCHAR)&pAdapter->ate.TxWI, TYPE_TXWI);
#endif // RT_BIG_ENDIAN //
NdisMoveMemory(&pAdapter->ate.TxCount, pRaCfg->data + 18, 4);
pAdapter->ate.TxCount = ntohl(pAdapter->ate.TxCount);
p = (USHORT *)(&pRaCfg->data[22]);
/* always use QID_AC_BE */
pAdapter->ate.QID = 0;
p = (USHORT *)(&pRaCfg->data[24]);
pAdapter->ate.HLen = ntohs(*p);
if (pAdapter->ate.HLen > 32)
{
ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.HLen > 32\n"));
err = 3;
goto TX_START_ERROR;
}
NdisMoveMemory(&pAdapter->ate.Header, pRaCfg->data + 26, pAdapter->ate.HLen);
pAdapter->ate.PLen = ntohs(pRaCfg->length) - (pAdapter->ate.HLen + 28);
if (pAdapter->ate.PLen > 32)
{
ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.PLen > 32\n"));
err = 4;
goto TX_START_ERROR;
}
NdisMoveMemory(&pAdapter->ate.Pattern, pRaCfg->data + 26 + pAdapter->ate.HLen, pAdapter->ate.PLen);
pAdapter->ate.DLen = pAdapter->ate.TxWI.MPDUtotalByteCount - pAdapter->ate.HLen;
}
ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R22, &Bbp22Value);
switch (Bbp22Value)
{
case BBP22_TXFRAME:
{
if (pAdapter->ate.TxCount == 0)
{
#ifdef RTMP_MAC_PCI
pAdapter->ate.TxCount = 0xFFFFFFFF;
#endif // RTMP_MAC_PCI //
}
ATEDBGPRINT(RT_DEBUG_TRACE,("START TXFRAME\n"));
pAdapter->ate.bQATxStart = TRUE;
Set_ATE_Proc(pAdapter, "TXFRAME");
}
break;
case BBP22_TXCONT_OR_CARRSUPP:
{
ATEDBGPRINT(RT_DEBUG_TRACE,("BBP22_TXCONT_OR_CARRSUPP\n"));
ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R24, &Bbp24Value);
switch (Bbp24Value)
{
case BBP24_TXCONT:
{
ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCONT\n"));
pAdapter->ate.bQATxStart = TRUE;
Set_ATE_Proc(pAdapter, "TXCONT");
}
break;
case BBP24_CARRSUPP:
{
ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARRSUPP\n"));
pAdapter->ate.bQATxStart = TRUE;
pAdapter->ate.Mode |= ATE_TXCARRSUPP;
}
break;
default:
{
ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown TX subtype !"));
}
break;
}
}
break;
case BBP22_TXCARR:
{
ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARR\n"));
pAdapter->ate.bQATxStart = TRUE;
Set_ATE_Proc(pAdapter, "TXCARR");
}
break;
default:
{
ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown Start TX subtype !"));
}
break;
}
if (pAdapter->ate.bQATxStart == TRUE)
{
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
TX_START_ERROR:
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), err);
return err;
}
static inline INT DO_RACFG_CMD_GET_TX_STATUS(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UINT32 count=0;
count = htonl(pAdapter->ate.TxDoneCount);
NdisMoveMemory(pRaCfg->data, &count, 4);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+4, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_TX_STOP(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_TX_STOP\n"));
Set_ATE_Proc(pAdapter, "TXSTOP");
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_RX_START(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
pAdapter->ate.bQARxStart = TRUE;
Set_ATE_Proc(pAdapter, "RXFRAME");
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_RX_STOP(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_STOP\n"));
Set_ATE_Proc(pAdapter, "RXSTOP");
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_START_TX_CARRIER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CARRIER\n"));
Set_ATE_Proc(pAdapter, "TXCARR");
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_START_TX_CONT(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CONT\n"));
Set_ATE_Proc(pAdapter, "TXCONT");
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_START_TX_FRAME(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_FRAME\n"));
Set_ATE_Proc(pAdapter, "TXFRAME");
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_BW(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_BW\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_BW_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_TX_POWER0(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER0\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_POWER0_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_TX_POWER1(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER1\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_POWER1_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_FREQ_OFFSET(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_FREQ_OFFSET\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_FREQOFFSET_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_GET_STATISTICS(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_GET_STATISTICS\n"));
memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.TxDoneCount, 4);
memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->WlanCounters.RetryCount.u.LowPart, 4);
memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->WlanCounters.FailedCount.u.LowPart, 4);
memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->WlanCounters.RTSSuccessCount.u.LowPart, 4);
memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->WlanCounters.RTSFailureCount.u.LowPart, 4);
memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart, 4);
memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->WlanCounters.FCSErrorCount.u.LowPart, 4);
memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->Counters8023.RxNoBuffer, 4);
memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart, 4);
memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->RalinkCounters.OneSecFalseCCACnt, 4);
if (pAdapter->ate.RxAntennaSel == 0)
{
INT32 RSSI0 = 0;
INT32 RSSI1 = 0;
INT32 RSSI2 = 0;
RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
RSSI1 = (INT32)(pAdapter->ate.LastRssi1 - pAdapter->BbpRssiToDbmDelta);
RSSI2 = (INT32)(pAdapter->ate.LastRssi2 - pAdapter->BbpRssiToDbmDelta);
memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&RSSI1, 4);
memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&RSSI2, 4);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+52, NDIS_STATUS_SUCCESS);
}
else
{
INT32 RSSI0 = 0;
RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+44, NDIS_STATUS_SUCCESS);
}
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_RESET_COUNTER(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 1;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_RESET_COUNTER\n"));
sprintf((char *)str, "%d", value);
Set_ResetStatCounter_Proc(pAdapter, str);
pAdapter->ate.TxDoneCount = 0;
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SEL_TX_ANTENNA(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_TX_ANTENNA\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_Antenna_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SEL_RX_ANTENNA(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_RX_ANTENNA\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_RX_Antenna_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_PREAMBLE(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_PREAMBLE\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_MODE_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_CHANNEL(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_CHANNEL\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_CHANNEL_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_ADDR1(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR1\n"));
/*
Addr is an array of UCHAR,
so no need to perform endian swap.
*/
memcpy(pAdapter->ate.Addr1, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_ADDR2(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR2\n"));
/*
Addr is an array of UCHAR,
so no need to perform endian swap.
*/
memcpy(pAdapter->ate.Addr2, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_ADDR3(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR3\n"));
/*
Addr is an array of UCHAR,
so no need to perform endian swap.
*/
memcpy(pAdapter->ate.Addr3, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_RATE(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_RATE\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_MCS_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_TX_FRAME_LEN(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
SHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_LEN\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
sprintf((char *)str, "%d", value);
Set_ATE_TX_LENGTH_Proc(pAdapter, str);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_SET_TX_FRAME_COUNT(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT value = 0;
STRING str[LEN_OF_ARG];
NdisZeroMemory(str, LEN_OF_ARG);
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_COUNT\n"));
memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
value = ntohs(value);
#ifdef RTMP_MAC_PCI
/* TX_FRAME_COUNT == 0 means tx infinitely */
if (value == 0)
{
/* Use TxCount = 0xFFFFFFFF to approximate the infinity. */
pAdapter->ate.TxCount = 0xFFFFFFFF;
ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_COUNT_Proc (TxCount = %d)\n", pAdapter->ate.TxCount));
ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_COUNT_Proc Success\n"));
}
else
#endif // RTMP_MAC_PCI //
{
sprintf((char *)str, "%d", value);
Set_ATE_TX_COUNT_Proc(pAdapter, str);
}
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_START_RX_FRAME(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
Set_ATE_Proc(pAdapter, "RXFRAME");
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_E2PROM_READ_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT offset;
USHORT len;
USHORT buffer[EEPROM_SIZE/2];
offset = ntohs(pRaCfg->status);
memcpy(&len, pRaCfg->data, 2);
len = ntohs(len);
rt_ee_read_all(pAdapter, (USHORT *)buffer);
if (offset + len <= EEPROM_SIZE)
memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer+offset, len);
else
ATEDBGPRINT(RT_DEBUG_ERROR, ("exceed EEPROM size\n"));
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+len, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_E2PROM_WRITE_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT offset;
USHORT len;
USHORT buffer[EEPROM_SIZE/2];
offset = ntohs(pRaCfg->status);
memcpy(&len, pRaCfg->data, 2);
len = ntohs(len);
rt_ee_read_all(pAdapter,(USHORT *)buffer);
memcpy_exs(pAdapter, (UCHAR *)buffer + offset, (UCHAR *)pRaCfg->data + 2, len);
rt_ee_write_all(pAdapter,(USHORT *)buffer);
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_IO_WRITE_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
UINT32 offset, i, value;
USHORT len;
memcpy(&offset, &pRaCfg->status, 4);
offset = ntohl(offset);
memcpy(&len, pRaCfg->data+2, 2);
len = ntohs(len);
for (i = 0; i < len; i += 4)
{
memcpy_exl(pAdapter, (UCHAR *)&value, pRaCfg->data+4+i, 4);
ATEDBGPRINT(RT_DEBUG_TRACE,("Write %x %x\n", offset + i, value));
RTMP_IO_WRITE32(pAdapter, ((offset+i) & (0xffff)), value);
}
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_BBP_READ_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT offset;
USHORT len;
USHORT j;
offset = ntohs(pRaCfg->status);
memcpy(&len, pRaCfg->data, 2);
len = ntohs(len);
for (j = offset; j < (offset+len); j++)
{
pRaCfg->data[j - offset] = 0;
if (pAdapter->ate.Mode == ATE_STOP)
{
RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, j, &pRaCfg->data[j - offset]);
}
else
{
ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, j, &pRaCfg->data[j - offset]);
}
}
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status)+len, NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
static inline INT DO_RACFG_CMD_ATE_BBP_WRITE_BULK(
IN PRTMP_ADAPTER pAdapter,
IN struct iwreq *wrq,
IN struct ate_racfghdr *pRaCfg)
{
USHORT offset;
USHORT len;
USHORT j;
UCHAR *value;
offset = ntohs(pRaCfg->status);
memcpy(&len, pRaCfg->data, 2);
len = ntohs(len);
for (j = offset; j < (offset+len); j++)
{
value = pRaCfg->data + 2 + (j - offset);
if (pAdapter->ate.Mode == ATE_STOP)
{
RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j, *value);
}
else
{
ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j, *value);
}
}
RESPONSE_TO_GUI(pRaCfg, wrq, sizeof(pRaCfg->status), NDIS_STATUS_SUCCESS);
return NDIS_STATUS_SUCCESS;
}
#endif // RALINK_28xx_QA //
#endif // RALINK_ATE //
|
klaantczak/Nordic
|
src/hps/statemachine/triggers/Probabilistic.go
|
<reponame>klaantczak/Nordic<gh_stars>0
package triggers
import (
"encoding/json"
"fmt"
"hps"
sm "hps/statemachine"
"math"
)
type ProbabilisticTrigger struct {
parameter float64
comment string
}
func NewProbabilisticTrigger(parameter float64) *ProbabilisticTrigger {
t := &ProbabilisticTrigger{}
t.parameter = parameter
_ = sm.ITrigger(t)
return t
}
func (t *ProbabilisticTrigger) Time(time float64) float64 {
return time + math.Log(1-hps.RndNext())/(-t.parameter)
}
func (t *ProbabilisticTrigger) GetComment() string {
return t.comment
}
func (t *ProbabilisticTrigger) SetComment(comment string) {
t.comment = comment
}
func (t *ProbabilisticTrigger) GetParameter() float64 {
return t.parameter
}
func (t *ProbabilisticTrigger) SetMachine(machine *sm.Machine) {
}
func (t *ProbabilisticTrigger) UnmarshalJSON(data []byte) error {
trigger := struct {
Type string `json:"type"`
Distribution string `json:"distribution"`
Parameter float64 `json:"parameter"`
Comment string `json:"comment,omitempty"`
}{"", "", 0.0, ""}
err := json.Unmarshal(data, &trigger)
if err != nil {
return err
}
if trigger.Type != "probabilistic" || trigger.Distribution != "exponential" {
return fmt.Errorf("Expect the trigger type to be \"probabilistic\" and the distribution is \"exponential\".")
}
*t = ProbabilisticTrigger{}
t.parameter = trigger.Parameter
t.comment = trigger.Comment
return nil
}
func (t *ProbabilisticTrigger) MarshalJSON() ([]byte, error) {
trigger := struct {
Type string `json:"type"`
Distribution string `json:"distribution"`
Parameter float64 `json:"parameter"`
Comment string `json:"comment,omitempty"`
}{"probabilistic", "exponential", t.parameter, t.comment}
return json.Marshal(trigger)
}
|
EricChang82/springBootDemo
|
springBootDemo/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java
|
<gh_stars>0
package com.alibaba.excel.analysis.v07;
import com.alibaba.excel.annotation.FieldType;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventRegisterCenter;
import com.alibaba.excel.event.OneRowAnalysisFinishEvent;
import com.alibaba.excel.util.CellValueUtil;
import com.alibaba.excel.util.PositionUtils;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.Arrays;
import static com.alibaba.excel.constant.ExcelXmlConstants.*;
/**
* @author jipengfei
*/
public class XlsxRowHandler extends DefaultHandler {
private String currentCellIndex;
private FieldType currentCellType;
private int curRow;
private int curCol;
private String[] curRowContent = new String[20];
private String currentCellValue;
private SharedStringsTable sst;
private AnalysisContext analysisContext;
private AnalysisEventRegisterCenter registerCenter;
private StylesTable stylesTable;
public XlsxRowHandler(AnalysisEventRegisterCenter registerCenter, SharedStringsTable sst,
AnalysisContext analysisContext, StylesTable stylesTable) {
this.registerCenter = registerCenter;
this.analysisContext = analysisContext;
this.sst = sst;
this.stylesTable = stylesTable;
}
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
setTotalRowCount(name, attributes);
startCell(name, attributes);
startCellValue(name);
}
private void startCellValue(String name) {
if (name.equals(CELL_VALUE_TAG) || name.equals(CELL_VALUE_TAG_1)) {
// initialize current cell value
currentCellValue = "";
}
}
private void startCell(String name, Attributes attributes) {
if (ExcelXmlConstants.CELL_TAG.equals(name)) {
currentCellIndex = attributes.getValue(ExcelXmlConstants.POSITION);
int nextRow = PositionUtils.getRow(currentCellIndex);
if (nextRow > curRow) {
curRow = nextRow;
// endRow(ROW_TAG);
}
analysisContext.setCurrentRowNum(curRow);
curCol = PositionUtils.getCol(currentCellIndex);
currentCellType = CellValueUtil.getCellType(attributes, stylesTable);
// String cellType = attributes.getValue("t");
// currentCellType = FieldType.EMPTY;
// if (cellType != null && cellType.equals("s")) {
// currentCellType = FieldType.STRING;
// }
}
}
private void endCellValue(String name) throws SAXException {
// ensure size
if (curCol >= curRowContent.length) {
curRowContent = Arrays.copyOf(curRowContent, (int) (curCol * 1.5));
}
if (CELL_VALUE_TAG.equals(name)) {
// switch (currentCellType) {
// case STRING:
// int idx = Integer.parseInt(currentCellValue);
// currentCellValue = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
// currentCellType = FieldType.EMPTY;
// break;
// }
String cellValue = CellValueUtil.getCellValue(currentCellType, currentCellValue, sst, analysisContext.use1904WindowDate(), analysisContext.getDefaultDateFormat());
curRowContent[curCol] = cellValue;
} else if (CELL_VALUE_TAG_1.equals(name)) {
curRowContent[curCol] = currentCellValue;
}
}
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
endRow(name);
endCellValue(name);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
currentCellValue += new String(ch, start, length);
}
private void setTotalRowCount(String name, Attributes attributes) {
if (DIMENSION.equals(name)) {
String d = attributes.getValue(DIMENSION_REF);
String totalStr = d.substring(d.indexOf(":") + 1, d.length());
String c = totalStr.toUpperCase().replaceAll("[A-Z]", "");
analysisContext.setTotalCount(Integer.parseInt(c));
}
}
private void endRow(String name) {
if (name.equals(ROW_TAG)) {
registerCenter.notifyListeners(new OneRowAnalysisFinishEvent(curRowContent, curCol));
curRowContent = new String[20];
}
}
}
|
Mimecast/ioriot
|
ioriot/src/vfd.c
|
<filename>ioriot/src/vfd.c
// Copyright 2018 Mimecast 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 "vfd.h"
vfd_s* vfd_new(const int fd, const long mapped_fd, char *path)
{
vfd_s *vfd = Malloc(vfd_s);
vfd->path = NULL;
vfd->debug = false;
vfd_update(vfd, fd, mapped_fd, path);
return vfd;
}
void vfd_update(vfd_s *vfd, const int fd, const long mapped_fd, char *path)
{
vfd->fd = fd;
vfd->dirfd = NULL;
vfd->mapped_fd = mapped_fd;
vfd->offset = 0;
if (path)
free(vfd->path);
vfd->path = Clone(path);
}
void vfd_destroy(vfd_s *vfd)
{
if (!vfd)
return;
if (vfd->path)
free(vfd->path);
free(vfd);
}
void vfd_print(vfd_s *vfd)
{
fprintf(stderr, "virtfd(%p) fd:%x mapped_fd:%lx path:%s\n",
(void*)vfd, vfd->fd, vfd->mapped_fd, vfd->path);
}
|
RickK213/react-firebase-starter
|
src/components/session/index.js
|
import { withEmailVerification } from './with-email-verification';
import { withAuthorization } from './with-authorization';
import { withAuthentication } from './with-authentication';
import AuthUserContext from './context';
export {
withEmailVerification,
withAuthorization,
withAuthentication,
AuthUserContext
};
|
devgateway/gtp
|
persistence/src/main/java/org/devgateway/toolkit/persistence/dto/GTPLocation.java
|
package org.devgateway.toolkit.persistence.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.devgateway.toolkit.persistence.dao.location.Department;
/**
* @author <NAME>
*/
@JsonInclude(JsonInclude.Include.ALWAYS)
public class GTPLocation {
private final Long id;
private final String name;
public GTPLocation(Department department) {
this.id = department.getId();
this.name = department.getName();
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
|
r3m0t/debugpy
|
src/debugpy/_vendored/pydevd/tests_python/resources/my_code/my_code_double_step.py
|
<filename>src/debugpy/_vendored/pydevd/tests_python/resources/my_code/my_code_double_step.py
if __name__ == '__main__':
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from not_my_code import other_noop
other_noop.call_noop() # break here
print('TEST SUCEEDED!')
|
bhupendpatil/Practice
|
Android/Email/MainActivity.java
|
<gh_stars>1-10
package hk.ust.cse.comp107x.email;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button emailing;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailing = (Button) findViewById(R.id.email);
emailing.setOnClickListener(this);
}
@Override
public void onClick(View v){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
}
}
|
ChineseTony/javaDataStruct
|
nettystudy/src/main/java/com/tom/mycode/codec/RpcMessageDecoder.java
|
package com.tom.mycode.codec;
import com.tom.mycode.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Map;
import static com.tom.mycode.MyEncodeDecodeConstans.TOTAL_LENGTH;
/**
* @author WangTao
* @link https://blog.csdn.net/u010853261/article/details/55803933
*/
public class RpcMessageDecoder extends LengthFieldBasedFrameDecoder {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcMessageDecoder.class);
public RpcMessageDecoder() {
// default is 8M
this(MyEncodeDecodeConstans.MAX_FRAME_LENGTH);
}
public RpcMessageDecoder(int maxFrameLength) {
/*
int maxFrameLength,
int lengthFieldOffset, magic code is 4B, and version is 1B, and then FullLength. so value is 5
int lengthFieldLength, FullLength is int(4B). so values is 4
int lengthAdjustment, FullLength include all data and read 9 bytes before, so the left length is (FullLength-9). so values is -9
int initialBytesToStrip we will check magic code and version self, so do not strip any bytes. so values is 0
*/
super(maxFrameLength, 5, 4, -9, 0);
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
Object decoded = super.decode(ctx, in);
if (decoded instanceof ByteBuf) {
ByteBuf frame = (ByteBuf) decoded;
if (frame.readableBytes() >= TOTAL_LENGTH){
try {
return decodeFrame(frame);
} catch (Exception e) {
LOGGER.error("Decode frame error!", e);
throw e;
} finally {
frame.release();
}
}
}
return decoded;
}
private Object decodeFrame(ByteBuf in)
throws Exception {
// 读取前4个magic比对一下
int len = MyEncodeDecodeConstans.MAGIC_NUMBER.length;
byte[] tmp = new byte[len];
in.readBytes(tmp);
for (int i = 0; i < len; i++) {
if (tmp[i] != MyEncodeDecodeConstans.MAGIC_NUMBER[i]){
throw new IllegalArgumentException("Unknown magic code: " + Arrays.toString(tmp));
}
}
byte version = in.readByte();
if (version != MyEncodeDecodeConstans.VERSION){
throw new RuntimeException("version isn't compatible"+version);
}
int fullLength = in.readInt();
short headLength = in.readShort();
//消息类型
byte messageType = in.readByte();
int requestId = in.readInt();
RpcMessage rpcMessage = new RpcMessage();
rpcMessage.setRequestId(requestId);
rpcMessage.setMessageType(messageType);
int headMapLength = headLength - MyEncodeDecodeConstans.HEAD_LENGTH;
if (headMapLength > 0) {
Map<String, String> map = MyHeadMapSerializer.getInstance().decode(in, headMapLength);
rpcMessage.setParams(map);
}
if (messageType == MyEncodeDecodeConstans.MSGTYPE_HEARTBEAT_REQUEST) {
rpcMessage.setData(MyEncodeDecodeConstans.PING);
}else if(messageType == MyEncodeDecodeConstans.MSGTYPE_HEARTBEAT_RESPONSE){
rpcMessage.setData(MyEncodeDecodeConstans.PONG);
} if (messageType != MyEncodeDecodeConstans.MSGTYPE_HEARTBEAT_REQUEST
&& messageType != MyEncodeDecodeConstans.MSGTYPE_HEARTBEAT_RESPONSE){
int bodyLength = fullLength - headLength;
if (bodyLength > 0) {
byte[] bs = new byte[bodyLength];
in.readBytes(bs);
Object tmpValue = SerializerFactory.deserialize(bs,Object.class);
rpcMessage.setData(tmpValue);
}
}
return rpcMessage;
}
}
|
Vinicius-de-Souza-Reis-Lima/Python
|
Scripts/Tratamento de strings/MTEX D5.py
|
frase = str(input('Digite uma frase: ')).strip().upper()
print('Quantas vezes aparece a letra "A"? {}'.format(frase.count('A')))
print('Em que posição a letra "A" aparece primeiro? {}'.format(frase.find('A')))
print('Em que posição a letra "A" aparece pela última vez? {}'.format((frase.rfind('A'))))
|
dalalsunil1986/gramado
|
landos/kernel/2io/dev/tty/chardev/serial/serial.c
|
<reponame>dalalsunil1986/gramado
#include <kernel.h>
void serial1_handler (void)
{
debug_print("serial1_handler:\n");
}
void serial2_handler (void)
{
debug_print("serial2_handler:\n");
}
void serial3_handler (void)
{
debug_print("serial3_handler:\n");
}
void serial4_handler (void)
{
debug_print("serial4_handler:\n");
}
//=====================================
unsigned int serial_in(unsigned int base, int offset)
{
return (unsigned int) in8 (base + offset);
}
void serial_out(unsigned int base, int offset, int value)
{
out8 (value, base + offset);
}
//====================================
// # We don't have debug messages in this routine.
int serial_init_port ( uint16_t port )
{
int PortBase=0;
PortBase = (int) port;
// Se não é alguma das bases possiveis.
// #todo: Existem máquinas com mais do que 4 portas seriais?
if ( PortBase != COM1_PORT &&
PortBase != COM2_PORT &&
PortBase != COM3_PORT &&
PortBase != COM4_PORT )
{
// #bugbug
// E se falhar aqui ???
// We can't use panic yet.
// We have no serial debug.
return (int) (-1);
}
// Disable all interrupts
out8 (PortBase + 1, 0x00);
// Set baud rate.
// Baud Rate
// The serial controller (UART) has an internal clock
// which runs at 115200 ticks per second and a clock divisor
// which is used to control the baud rate.
// This is exactly the same type of system used by
// the Programmable Interrupt Timer (PIT).
// In order to set the speed of the port,
// calculate the divisor required for the given baud rate and
// program that in to the divisor register.
// For example, a divisor of 1 will give 115200 baud,
// a divisor of 2 will give 57600 baud, 3 will give 38400 baud, etc.
// Do not be tempted to use a divisor of 0.
// =============
// To set the divisor to the controller:
// > Set the most significant bit of the Line Control Register.
// This is the DLAB bit,
// and allows access to the divisor registers.
// > Send the least significant byte of the divisor value to [PORT + 0].
// > Send the most significant byte of the divisor value to [PORT + 1].
// > Clear the most significant bit of the Line Control Register.
// #define LCR 3
// See: serial.h
// credits: https://wiki.osdev.org/Serial_Ports
// Enable DLAB (set baud rate divisor)
out8 (PortBase + LCR, 0x80);
// Set divisor to 3 (lo byte) 38400 baud (hi byte)
out8 (PortBase + 0, 0x03);
out8 (PortBase + 1, 0x00);
// In the next command we will clear the msb of the LCR.
// ======================
// Line Protocol
// These days you could consider
// 8N1 (8 bits, no parity, one stop bit) pretty much the default.
// 8 bits, no parity, one stop bit
out8 (PortBase + LCR, 0x03);
// Enable FIFO, clear then with 14-byte threshold
// #define FCR 2
out8 (PortBase + FCR, 0xC7);
// IRQs enables, RTS/DSR set
// modem control register
// #define MCR 4
out8 (PortBase + MCR, 0x0B);
return 0;
}
/*
******************
* serial_init:
*
*/
// inicializa todas as portas.
// #IMPORTANT:
// We can't use debug in this first initialization.
// We can't use serial debug. It's because the serial port support
// is not working yet. :)
// # We don't have debug messages in this routine.
int serial_init (void){
int Status = -1;
//__breaker_com1_initialized = 0;
//__breaker_com2_initialized = 0;
//__breaker_com3_initialized = 0;
//__breaker_com4_initialized = 0;
Status = serial_init_port (COM1_PORT);
if (Status != 0)
return -1;
Status = serial_init_port (COM2_PORT);
if (Status != 0)
return -1;
Status = serial_init_port (COM3_PORT);
if (Status != 0)
return -1;
Status = serial_init_port (COM4_PORT);
if (Status != 0)
return -1;
//__breaker_com1_initialized = 1;
//__breaker_com2_initialized = 1;
//__breaker_com3_initialized = 1;
//__breaker_com4_initialized = 1;
return 0;
}
/*
* serial_write_char:
* NOT tested yet.
*/
char serial_read_char (unsigned int port)
{
// #todo
// Check the port validation.
while (( in8(port + 5) & 1 ) == 0);
return (char) in8 (port);
}
/*
* serial_write_char:
*
*/
void serial_write_char (unsigned int port, char data)
{
// #todo
// Check the port validation.
while (( in8(port + 5) & 0x20 ) == 0);
out8 (port, data);
}
void serial_print (unsigned int port, char *data )
{
register int i=0;
// #todo
// Check the port validation.
for ( i=0; data[i] != '\0'; i++ )
{
serial_write_char ( port ,data[i] );
};
}
void debug_print_string ( char *data )
{
register int i=0;
for ( i=0; data[i] != '\0'; i++ )
{
serial_write_char ( COM1_PORT ,data[i] );
};
}
// #todo
// We need a ioctl for serial devices.
int serial_ioctl ( int fd, unsigned long request, unsigned long arg )
{
debug_print("serial_ioctl: [TODO]\n");
return -1;
}
|
WallaTeam/WallaLinks
|
src/main/java/urlshortener/bangladeshgreen/domain/URISafe.java
|
<reponame>WallaTeam/WallaLinks
package urlshortener.bangladeshgreen.domain;
import org.springframework.data.annotation.Id;
/**
* Represents an object for information about URIs safe.
* Author: BangladeshGreen
*/
public class URISafe {
@Id
private String target;
private boolean safe;
private long date;
public URISafe(String target, boolean safe, long date) {
this.target = target;
this.safe = safe;
this.date = date;
}
public URISafe(){}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public boolean isSafe() {
return safe;
}
public void setSafe(boolean safe) {
this.safe = safe;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String toString() {
return new String("URLSafe[target='"+ target + "', safe='" + safe +
"', date='\"" + date + "\"']\n");
}
public boolean compareTo(ShortURL other){
if(this.target.compareTo(other.getTarget()) == 0){
return true;
}
else {return false;}
}
@Override
public boolean equals(Object o) {
URISafe other = (URISafe) o;
if(this.safe==other.isSafe() && this.target.equals(other.target)
&& this.date==date){
return true;
} else {
return false;
}
}
}
|
weicao/galaxysql
|
polardbx-executor/src/main/java/com/alibaba/polardbx/executor/ddl/job/factory/AlterTableGroupSplitPartitionByHotValueJobFactory.java
|
<gh_stars>0
package com.alibaba.polardbx.executor.ddl.job.factory;
import com.alibaba.polardbx.common.properties.ConnectionParams;
import com.alibaba.polardbx.common.utils.Pair;
import com.alibaba.polardbx.executor.ddl.job.builder.tablegroup.AlterTableGroupSplitPartitionByHotValueBuilder;
import com.alibaba.polardbx.executor.ddl.job.task.basic.PauseCurrentJobTask;
import com.alibaba.polardbx.executor.ddl.job.task.shared.EmptyTask;
import com.alibaba.polardbx.executor.ddl.job.task.tablegroup.AlterTableGroupAddMetaTask;
import com.alibaba.polardbx.executor.ddl.job.task.tablegroup.AlterTableGroupValidateTask;
import com.alibaba.polardbx.executor.ddl.newengine.job.DdlTask;
import com.alibaba.polardbx.executor.ddl.newengine.job.ExecutableDdlJob;
import com.alibaba.polardbx.executor.ddl.newengine.job.TransientDdlJob;
import com.alibaba.polardbx.executor.scaleout.ScaleOutUtils;
import com.alibaba.polardbx.gms.tablegroup.PartitionGroupRecord;
import com.alibaba.polardbx.gms.tablegroup.TableGroupConfig;
import com.alibaba.polardbx.optimizer.OptimizerContext;
import com.alibaba.polardbx.optimizer.config.table.ComplexTaskMetaManager;
import com.alibaba.polardbx.optimizer.context.ExecutionContext;
import com.alibaba.polardbx.optimizer.core.rel.PhyDdlTableOperation;
import com.alibaba.polardbx.optimizer.core.rel.ddl.data.AlterTableGroupItemPreparedData;
import com.alibaba.polardbx.optimizer.core.rel.ddl.data.AlterTableGroupSplitPartitionByHotValuePreparedData;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.calcite.rel.core.DDL;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* @author luoyanxin
*/
public class AlterTableGroupSplitPartitionByHotValueJobFactory extends AlterTableGroupBaseJobFactory {
public AlterTableGroupSplitPartitionByHotValueJobFactory(DDL ddl,
AlterTableGroupSplitPartitionByHotValuePreparedData preparedData,
Map<String, AlterTableGroupItemPreparedData> tablesPrepareData,
Map<String, List<PhyDdlTableOperation>> newPartitionsPhysicalPlansMap,
Map<String, Map<String, List<List<String>>>> tablesTopologyMap,
Map<String, Map<String, Set<String>>> targetTablesTopology,
Map<String, Map<String, Set<String>>> sourceTablesTopology,
Map<String, List<Pair<String, String>>> orderedTargetTablesLocations,
ExecutionContext executionContext) {
super(ddl, preparedData, tablesPrepareData, newPartitionsPhysicalPlansMap, tablesTopologyMap,
targetTablesTopology, sourceTablesTopology, orderedTargetTablesLocations,
ComplexTaskMetaManager.ComplexTaskType.SPLIT_HOT_VALUE, executionContext);
}
@Override
protected void validate() {
}
@Override
protected ExecutableDdlJob doCreate() {
AlterTableGroupSplitPartitionByHotValuePreparedData alterTableGroupSplitPartitionByHotValuePreparedData =
(AlterTableGroupSplitPartitionByHotValuePreparedData) preparedData;
String schemaName = alterTableGroupSplitPartitionByHotValuePreparedData.getSchemaName();
String tableGroupName = alterTableGroupSplitPartitionByHotValuePreparedData.getTableGroupName();
ExecutableDdlJob executableDdlJob = new ExecutableDdlJob();
Map<String, Long> tablesVersion = getTablesVersion();
DdlTask validateTask =
new AlterTableGroupValidateTask(schemaName,
alterTableGroupSplitPartitionByHotValuePreparedData.getTableGroupName(), tablesVersion, true,
alterTableGroupSplitPartitionByHotValuePreparedData.getTargetPhysicalGroups());
TableGroupConfig tableGroupConfig = OptimizerContext.getContext(schemaName).getTableGroupInfoManager()
.getTableGroupConfigByName(alterTableGroupSplitPartitionByHotValuePreparedData.getTableGroupName());
Set<Long> outdatedPartitionGroupId = new HashSet<>();
for (String splitPartitionName : alterTableGroupSplitPartitionByHotValuePreparedData.getOldPartitionNames()) {
for (PartitionGroupRecord record : tableGroupConfig.getPartitionGroupRecords()) {
if (record.partition_name.equalsIgnoreCase(splitPartitionName)) {
outdatedPartitionGroupId.add(record.id);
break;
}
}
}
List<String> targetDbList = new ArrayList<>();
int targetDbCnt =
alterTableGroupSplitPartitionByHotValuePreparedData.getTargetGroupDetailInfoExRecords().size();
List<String> newPartitions = alterTableGroupSplitPartitionByHotValuePreparedData.getNewPartitionNames();
for (int i = 0; i < alterTableGroupSplitPartitionByHotValuePreparedData.getNewPartitionNames().size(); i++) {
targetDbList.add(alterTableGroupSplitPartitionByHotValuePreparedData.getTargetGroupDetailInfoExRecords()
.get(i % targetDbCnt).phyDbName);
}
DdlTask addMetaTask = new AlterTableGroupAddMetaTask(schemaName,
tableGroupName,
tableGroupConfig.getTableGroupRecord().getId(),
alterTableGroupSplitPartitionByHotValuePreparedData.getSourceSql(),
ComplexTaskMetaManager.ComplexTaskStatus.DOING_REORG.getValue(),
taskType.getValue(),
outdatedPartitionGroupId,
targetDbList,
newPartitions);
executableDdlJob.addSequentialTasks(Lists.newArrayList(
validateTask,
addMetaTask
));
List<DdlTask> bringUpAlterTableGroupTasks =
ComplexTaskFactory.bringUpAlterTableGroup(schemaName, tableGroupName, null,
taskType, executionContext);
final String finalStatus =
executionContext.getParamManager().getString(ConnectionParams.TABLEGROUP_REORG_FINAL_TABLE_STATUS_DEBUG);
boolean stayAtPublic = true;
if (StringUtils.isNotEmpty(finalStatus)) {
stayAtPublic =
StringUtils.equalsIgnoreCase(ComplexTaskMetaManager.ComplexTaskStatus.PUBLIC.name(), finalStatus);
}
if (stayAtPublic) {
executableDdlJob.addSequentialTasks(bringUpAlterTableGroupTasks);
constructSubTasks(schemaName, executableDdlJob, addMetaTask, bringUpAlterTableGroupTasks,
alterTableGroupSplitPartitionByHotValuePreparedData.getOldPartitionNames().get(0));
} else {
PauseCurrentJobTask pauseCurrentJobTask = new PauseCurrentJobTask(schemaName);
constructSubTasks(schemaName, executableDdlJob, addMetaTask, ImmutableList.of(pauseCurrentJobTask),
alterTableGroupSplitPartitionByHotValuePreparedData.getOldPartitionNames().get(0));
}
if (((AlterTableGroupSplitPartitionByHotValuePreparedData) preparedData).isSkipSplit()) {
return new TransientDdlJob();
} else {
executableDdlJob.setMaxParallelism(ScaleOutUtils.getTableGroupTaskParallelism(executionContext));
return executableDdlJob;
}
}
public static ExecutableDdlJob create(@Deprecated DDL ddl,
AlterTableGroupSplitPartitionByHotValuePreparedData preparedData,
ExecutionContext executionContext) {
AlterTableGroupSplitPartitionByHotValueBuilder alterTableGroupSplitPartitionByHotValueBuilder =
new AlterTableGroupSplitPartitionByHotValueBuilder(ddl, preparedData, executionContext);
Map<String, Map<String, List<List<String>>>> tablesTopologyMap =
alterTableGroupSplitPartitionByHotValueBuilder.build().getTablesTopologyMap();
Map<String, Map<String, Set<String>>> targetTablesTopology =
alterTableGroupSplitPartitionByHotValueBuilder.getTargetTablesTopology();
Map<String, Map<String, Set<String>>> sourceTablesTopology =
alterTableGroupSplitPartitionByHotValueBuilder.getSourceTablesTopology();
Map<String, AlterTableGroupItemPreparedData> tableGroupItemPreparedDataMap =
alterTableGroupSplitPartitionByHotValueBuilder.getTablesPreparedData();
Map<String, List<PhyDdlTableOperation>> newPartitionsPhysicalPlansMap =
alterTableGroupSplitPartitionByHotValueBuilder.getNewPartitionsPhysicalPlansMap();
Map<String, List<Pair<String, String>>> orderedTargetTablesLocations =
alterTableGroupSplitPartitionByHotValueBuilder.getOrderedTargetTablesLocations();
return new AlterTableGroupSplitPartitionByHotValueJobFactory(ddl, preparedData, tableGroupItemPreparedDataMap,
newPartitionsPhysicalPlansMap, tablesTopologyMap, targetTablesTopology, sourceTablesTopology,
orderedTargetTablesLocations, executionContext).create();
}
@Override
public void constructSubTasks(String schemaName, ExecutableDdlJob executableDdlJob, DdlTask tailTask,
List<DdlTask> bringUpAlterTableGroupTasks, String targetPartitionName) {
EmptyTask emptyTask = new EmptyTask(schemaName);
boolean emptyTaskAdded = false;
for (Map.Entry<String, Map<String, List<List<String>>>> entry : tablesTopologyMap.entrySet()) {
AlterTableGroupSplitPartitionByHotValueSubTaskJobFactory subTaskJobFactory =
new AlterTableGroupSplitPartitionByHotValueSubTaskJobFactory(ddl,
(AlterTableGroupSplitPartitionByHotValuePreparedData) preparedData,
tablesPrepareData.get(entry.getKey()),
newPartitionsPhysicalPlansMap.get(entry.getKey()), tablesTopologyMap.get(entry.getKey()),
targetTablesTopology.get(entry.getKey()), sourceTablesTopology.get(entry.getKey()),
orderedTargetTablesLocations.get(entry.getKey()), targetPartitionName, false, executionContext);
ExecutableDdlJob subTask = subTaskJobFactory.create();
if (((AlterTableGroupSplitPartitionByHotValuePreparedData) preparedData).isSkipSplit()) {
return;
}
executableDdlJob.combineTasks(subTask);
executableDdlJob.addTaskRelationship(tailTask, subTask.getHead());
if (subTaskJobFactory.getCdcTableGroupDdlMarkTask() != null) {
if (!emptyTaskAdded) {
executableDdlJob.addTask(emptyTask);
emptyTaskAdded = true;
}
executableDdlJob.addTask(subTaskJobFactory.getCdcTableGroupDdlMarkTask());
executableDdlJob.addTaskRelationship(subTask.getTail(), emptyTask);
executableDdlJob.addTaskRelationship(emptyTask, subTaskJobFactory.getCdcTableGroupDdlMarkTask());
executableDdlJob.addTaskRelationship(subTaskJobFactory.getCdcTableGroupDdlMarkTask(), bringUpAlterTableGroupTasks.get(0));
} else {
executableDdlJob.addTaskRelationship(subTask.getTail(), bringUpAlterTableGroupTasks.get(0));
}
DdlTask dropUselessTableTask = ComplexTaskFactory
.CreateDropUselessPhyTableTask(schemaName, entry.getKey(), sourceTablesTopology.get(entry.getKey()),
executionContext);
executableDdlJob.addTask(dropUselessTableTask);
executableDdlJob
.addTaskRelationship(bringUpAlterTableGroupTasks.get(bringUpAlterTableGroupTasks.size() - 1),
dropUselessTableTask);
executableDdlJob.getExcludeResources().addAll(subTask.getExcludeResources());
}
}
@Override
protected void excludeResources(Set<String> resources) {
super.excludeResources(resources);
AlterTableGroupSplitPartitionByHotValuePreparedData splitPreparedData =
(AlterTableGroupSplitPartitionByHotValuePreparedData) preparedData;
if (StringUtils.isNotEmpty(splitPreparedData.getHotKeyPartitionName())) {
resources.add(concatWithDot(concatWithDot(preparedData.getSchemaName(), preparedData.getTableGroupName()),
splitPreparedData.getHotKeyPartitionName()));
}
}
}
|
pip-services3-gox/pip-services3-commons-gox
|
reflect/PropertyReflector.go
|
<filename>reflect/PropertyReflector.go
package reflect
import (
refl "reflect"
"strings"
"unicode"
"unicode/utf8"
)
/*
Helper class to perform property introspection and dynamic reading and writing.
This class has symmetric implementation across all languages supported by Pip.Services toolkit and used to support dynamic data processing.
Because all languages have different casing and case sensitivity rules, this PropertyReflector treats all property names as case insensitive.
Example:
myObj := MyObject{}
properties := PropertyReflector.GetPropertyNames()
PropertyReflector.HasProperty(myObj, "myProperty")
value := PropertyReflector.GetProperty(myObj, "myProperty")
PropertyReflector.SetProperty(myObj, "myProperty", 123)
*/
type TPropertyReflector struct{}
var PropertyReflector = &TPropertyReflector{}
func (c *TPropertyReflector) toFieldType(obj interface{}) refl.Type {
// Unwrap value
wrap, ok := obj.(IValueWrapper)
if ok {
obj = wrap.InnerValue()
}
// Move from pointer to real struct
typ := refl.TypeOf(obj)
if typ.Kind() == refl.Ptr {
typ = typ.Elem()
}
return typ
}
func (c *TPropertyReflector) toPropertyType(obj interface{}) refl.Type {
return refl.TypeOf(obj)
}
func (c *TPropertyReflector) matchField(field refl.StructField, name string) bool {
// Field must be public and match to name as case insensitive
r, _ := utf8.DecodeRuneInString(field.Name)
return unicode.IsUpper(r) &&
strings.ToLower(field.Name) == strings.ToLower(name)
}
func (c *TPropertyReflector) matchPropertyGetter(property refl.Method, name string) bool {
if property.Type.NumIn() != 1 || property.Type.NumOut() != 1 {
return false
}
// Method must be public and match to name as case insensitive
r, _ := utf8.DecodeRuneInString(property.Name)
return unicode.IsUpper(r) &&
strings.ToLower(property.Name) == strings.ToLower(name)
}
func (c *TPropertyReflector) matchPropertySetter(property refl.Method, name string) bool {
if property.Type.NumIn() != 2 || property.Type.NumOut() != 0 {
return false
}
// Method must be public and match to name as case insensitive
r, _ := utf8.DecodeRuneInString(property.Name)
name = "Set" + name
return unicode.IsUpper(r) &&
strings.ToLower(property.Name) == strings.ToLower(name)
}
// Checks if object has a property with specified name..
// Parameters:
// - obj interface{}
// an object to introspect.
// - name string
// a name of the property to check.
// Returns bool
// true if the object has the property and false if it doesn't.
func (c *TPropertyReflector) HasProperty(obj interface{}, name string) bool {
if obj == nil {
panic("Object cannot be nil")
}
if name == "" {
panic("Property name cannot be empty")
}
fieldType := c.toFieldType(obj)
if fieldType.Kind() == refl.Struct {
for index := 0; index < fieldType.NumField(); index++ {
field := fieldType.Field(index)
if c.matchField(field, name) {
return true
}
}
}
propType := c.toPropertyType(obj)
for index := 0; index < propType.NumMethod(); index++ {
method := propType.Method(index)
if c.matchPropertyGetter(method, name) {
return true
}
}
return false
}
//Gets value of object property specified by its name.
// Parameters:
// - obj interface{}
// an object to read property from.
// - name string
// a name of the property to get.
// Returns interface{}
// the property value or null if property doesn't exist or introspection failed.
func (c *TPropertyReflector) GetProperty(obj interface{}, name string) interface{} {
if obj == nil {
panic("Object cannot be nil")
}
if name == "" {
panic("Property name cannot be empty")
}
defer func() {
// Do nothing and return nil
recover()
}()
fieldType := c.toFieldType(obj)
if fieldType.Kind() == refl.Struct {
for index := 0; index < fieldType.NumField(); index++ {
field := fieldType.Field(index)
if c.matchField(field, name) {
val := refl.ValueOf(obj)
if val.Kind() == refl.Ptr {
val = val.Elem()
}
return val.Field(index).Interface()
}
}
}
propType := c.toPropertyType(obj)
for index := 0; index < propType.NumMethod(); index++ {
method := propType.Method(index)
if c.matchPropertyGetter(method, name) {
val := refl.ValueOf(obj)
return val.Method(index).Call([]refl.Value{})[0].Interface()
}
}
return nil
}
// Gets names of all properties implemented in specified object.
// Parameters:
// - obj interface{}
// an object to introspect.
// Returns []string
// a list with property names.
func (c *TPropertyReflector) GetPropertyNames(obj interface{}) []string {
if obj == nil {
panic("Object cannot be nil")
}
properties := []string{}
fieldType := c.toFieldType(obj)
if fieldType.Kind() == refl.Struct {
for index := 0; index < fieldType.NumField(); index++ {
field := fieldType.Field(index)
if c.matchField(field, field.Name) {
properties = append(properties, field.Name)
}
}
}
propType := c.toPropertyType(obj)
for index := 0; index < propType.NumMethod(); index++ {
method := propType.Method(index)
if c.matchPropertyGetter(method, method.Name) {
properties = append(properties, method.Name)
}
}
return properties
}
// Get values of all properties in specified object and returns them as a map.
// Parameters:
// - obj interface{}
// an object to get properties from.
// Returns map[string]interface{}
// a map, containing the names of the object's properties and their values.
func (c *TPropertyReflector) GetProperties(obj interface{}) map[string]interface{} {
if obj == nil {
panic("Object cannot be nil")
}
defer func() {
// Do nothing and return nil
recover()
}()
properties := map[string]interface{}{}
fieldType := c.toFieldType(obj)
if fieldType.Kind() == refl.Struct {
for index := 0; index < fieldType.NumField(); index++ {
field := fieldType.Field(index)
if c.matchField(field, field.Name) {
val := refl.ValueOf(obj)
if val.Kind() == refl.Ptr {
val = val.Elem()
}
properties[field.Name] = val.Field(index).Interface()
}
}
}
propType := c.toPropertyType(obj)
for index := 0; index < propType.NumMethod(); index++ {
method := propType.Method(index)
if c.matchPropertyGetter(method, method.Name) {
val := refl.ValueOf(obj)
properties[method.Name] = val.Method(index).Call([]refl.Value{})[0].Interface()
}
}
return properties
}
// Sets value of object property specified by its name.
// If the property does not exist or introspection fails this method doesn't do anything and doesn't any throw errors.
// Parameters:
// - obj interface{}
// an object to write property to.
// name string
// a name of the property to set.
// - value interface{}
// a new value for the property to set.
func (c *TPropertyReflector) SetProperty(obj interface{}, name string, value interface{}) {
if obj == nil {
panic("Object cannot be nil")
}
if name == "" {
panic("Property name cannot be empty")
}
defer func() {
// Do nothing and return nil
recover()
}()
fieldType := c.toFieldType(obj)
if fieldType.Kind() == refl.Struct {
for index := 0; index < fieldType.NumField(); index++ {
field := fieldType.Field(index)
if c.matchField(field, name) {
val := refl.ValueOf(obj)
if val.Kind() == refl.Ptr {
val = val.Elem()
}
val.Field(index).Set(refl.ValueOf(value))
return
}
}
}
propType := c.toPropertyType(obj)
for index := 0; index < propType.NumMethod(); index++ {
method := propType.Method(index)
if c.matchPropertySetter(method, name) {
val := refl.ValueOf(obj)
val.Method(index).Call([]refl.Value{refl.ValueOf(value)})
}
}
}
// Sets values of some (all) object properties.
// If some properties do not exist or introspection fails they are just silently skipped and no errors thrown.
// see
// SetProperty
// Parameters:
// - obj interface{}
// an object to write properties to.
// - values map[string]interface{}
// a map, containing property names and their values.
func (c *TPropertyReflector) SetProperties(obj interface{}, values map[string]interface{}) {
if values == nil || len(values) == 0 {
return
}
for key, value := range values {
c.SetProperty(obj, key, value)
}
}
|
lkszmn/spectrast
|
src/spectrast/SpectraSTCandidate.hpp
|
<filename>src/spectrast/SpectraSTCandidate.hpp
#ifndef SPECTRASTCANDIDATE_HPP_
#define SPECTRASTCANDIDATE_HPP_
#include "SpectraSTLibEntry.hpp"
#include "SpectraSTSearchParams.hpp"
#include "SpectraSTSimScores.hpp"
/*
Program : Spectrast
Author : <NAME> <<EMAIL>>
Date : 03.06.06
Copyright (C) 2006 <NAME>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
<NAME>
Institute for Systems Biology
401 Terry Avenue North
Seattle, WA 98109 USA
<EMAIL>
*/
/* Class: SpectraSTCandidate
*
* A container class which holds a candidate entry retrieved from the library.
* In addition to the actual library entry (which it references), it is also used to hold
* scoring information after the spectrum is compared to the query spectrum.
*
*
*/
class SpectraSTCandidate {
public:
SpectraSTCandidate(SpectraSTLibEntry* entry, SpectraSTSearchParams& params);
~SpectraSTCandidate();
// Simple accessor methods
SpectraSTLibEntry* getEntry() { return m_entry; };
double getSortKey() { return m_sortKey; }
SpectraSTSimScores& getSimScoresRef() { return m_simScores; }
// Output method that prints the peak list to a file
void printSpectrum(string spectrumFileName);
// Checks if the candidate's F value is above the threshold specified in the search parameters
bool passTopHitFvalThreshold();
bool passLowerHitsFvalThreshold();
// Methods for sorting
void setSortKey(double key) { m_sortKey = key; }
static bool sortPtrsDesc(SpectraSTCandidate* a, SpectraSTCandidate* b);
// Methods for recording similarity scores in library entry
// void recordDotInLibraryEntry();
private:
// m_entry - Pointer to the library entry object
// IMPORTANT NOTE:
// Since the library entries are cached (see SpectraSTMzLibIndex), the library entry object is NOT the property of SpectraSTCandidate. It remains
// the property of SpectraSTMzLibIndex, and WILL BE RE-USED by other searches (That's precisely the point of caching)!!
SpectraSTLibEntry* m_entry;
SpectraSTSearchParams& m_params;
SpectraSTSimScores m_simScores;
// m_sortKey - stores the value using which the candidates will be sorted to create the output list.
// This can be one of the fields of m_simScores, or it can be anything.
double m_sortKey;
};
#endif /*SPECTRASTCANDIDATE_HPP_*/
|
pengtaoman/webside
|
src/main/java/com/webside/business/mapper/InquiryMapper.java
|
package com.webside.business.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.webside.base.basemapper.BaseMapper;
import com.webside.business.model.InquiryDetailsEntity;
import com.webside.business.model.InquiryEntity;
public interface InquiryMapper extends BaseMapper<InquiryEntity, String>{
int insertDetailsBatch(List<InquiryDetailsEntity> list);
List<InquiryDetailsEntity> queryDetailsList(@Param("id")String id);
int deleteDetailsByInquiryId(@Param("inquiryId")String inquiryId);
}
|
mikiec84/blueprints
|
src/test/java/com/tinkerpop/blueprints/pgm/impls/rexster/RexsterGraphTest.java
|
<filename>src/test/java/com/tinkerpop/blueprints/pgm/impls/rexster/RexsterGraphTest.java<gh_stars>1-10
package com.tinkerpop.blueprints.pgm.impls.rexster;
import com.tinkerpop.blueprints.pgm.*;
import com.tinkerpop.blueprints.pgm.impls.GraphTest;
import java.lang.reflect.Method;
/**
* @author <NAME> (http://markorodriguez.com)
*/
public class RexsterGraphTest extends GraphTest {
public RexsterGraphTest() {
// intended to be used with TinkerGraph as the endpoint graph
this.allowsDuplicateEdges = true;
this.allowsSelfLoops = true;
this.ignoresSuppliedIds = false;
this.isPersistent = false;
this.isRDFModel = false;
this.supportsVertexIteration = true;
this.supportsEdgeIteration = true;
this.supportsVertexIndex = true;
this.supportsEdgeIndex = true;
}
public void testVertexTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new VertexTestSuite(this));
printTestPerformance("VertexTestSuite", this.stopWatch());
}
public void testEdgeTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new EdgeTestSuite(this));
printTestPerformance("EdgeTestSuite", this.stopWatch());
}
public void testGraphTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphTestSuite(this));
printTestPerformance("GraphTestSuite", this.stopWatch());
}
public void testIndexableGraphTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new IndexableGraphTestSuite(this));
printTestPerformance("IndexableGraphTestSuite", this.stopWatch());
}
public void testIndexTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new IndexTestSuite(this));
printTestPerformance("IndexTestSuite", this.stopWatch());
}
public void testAutomaticIndexTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new AutomaticIndexTestSuite(this));
printTestPerformance("AutomaticIndexTestSuite", this.stopWatch());
}
/*
TODO: Create a respective test case that doesn't require underscore prefixed properties
public void testGraphMLReaderTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphMLReaderTestSuite(this));
printTestPerformance("GraphMLReaderTestSuite", this.stopWatch());
}*/
public Graph getGraphInstance() {
return new RexsterGraph(this.getWorkingUri());
}
public void doTestSuite(final TestSuite testSuite) throws Exception {
String doTest = System.getProperty("testRexsterGraph");
if (doTest == null || doTest.equals("true")) {
this.resetGraph();
for (Method method : testSuite.getClass().getDeclaredMethods()) {
if (method.getName().startsWith("test")) {
System.out.println("Testing " + method.getName() + "...");
method.invoke(testSuite);
this.resetGraph();
}
}
}
}
private void resetGraph() {
IndexableGraph graph = new RexsterGraph(this.getWorkingUri());
graph.clear();
graph.createIndex(Index.VERTICES, Vertex.class, Index.Type.AUTOMATIC);
graph.createIndex(Index.EDGES, Edge.class, Index.Type.AUTOMATIC);
}
private String getWorkingUri() {
String uri = System.getProperty("rexsterGraphURI");
if (uri == null) {
uri = "http://localhost:8182/emptygraph";
}
return uri;
}
}
|
kyeonghopark/jgt-code
|
Volume_10/Number_2/Baerentzen2005/Libsrc/LDI/create_ldi.h
|
#ifndef __CREATE_LDI_H
#define __CREATE_LDI_H
#include "LDI.h"
namespace LDI
{
void create_ldi(LDISet& ldi_set);
}
#endif
|
hawaker/eladmin
|
eladmin-system/src/main/java/me/zhengjie/modules/activiti/rest/ModelerController.java
|
package me.zhengjie.modules.activiti.rest;
import com.alipay.api.domain.ModelQueryParam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.activiti.dto.ModelQueryCriteria;
import me.zhengjie.utils.PageUtil;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/activiti/model")
@Slf4j
public class ModelerController {
@Autowired
RepositoryService repositoryService;
@Autowired
ObjectMapper objectMapper;
/**
* 新建一个空模型
*
* @return
* @throws UnsupportedEncodingException
*/
@PostMapping("/create")
public ResponseEntity newModel(@RequestBody LinkedHashMap<String,String> map) throws UnsupportedEncodingException {
//初始化一个空模型
Model model = repositoryService.newModel();
String name=map.getOrDefault("name","new-process");
String description=map.getOrDefault("description","");
String key=map.getOrDefault("key","process");
int revision = 1;
ObjectNode modelNode = objectMapper.createObjectNode();
modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);
model.setName(name);
model.setKey(key);
model.setMetaInfo(modelNode.toString());
repositoryService.saveModel(model);
String id = model.getId();
//完善ModelEditorSource
ObjectNode editorNode = objectMapper.createObjectNode();
editorNode.put("id", "canvas");
editorNode.put("resourceId", "canvas");
ObjectNode stencilSetNode = objectMapper.createObjectNode();
stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
editorNode.put("stencilset", stencilSetNode);
repositoryService.addModelEditorSource(id, editorNode.toString().getBytes("utf-8"));
return new ResponseEntity<>(id,HttpStatus.OK);
}
@GetMapping("/import")
public Object importModel(@RequestParam String name, @RequestParam String path) throws Exception {
Resource resource = new ClassPathResource(path);
InputStream inputStream = resource.getInputStream();
// 创建转换对象
BpmnXMLConverter converter = new BpmnXMLConverter();
// 创建XMLStreamReader读取XML资源
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(inputStream);
// 把XML转换成BpmnModel对象
BpmnModel bpmnModel = converter.convertToBpmnModel(reader);
BpmnJsonConverter bpmnJsonConverter = new BpmnJsonConverter();
ObjectNode objectNode = bpmnJsonConverter.convertToJson(bpmnModel);
//初始化一个空模型
Model model = repositoryService.newModel();
String description = "";
int revision = 1;
String key = "process";
ObjectNode modelNode = objectMapper.createObjectNode();
modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);
model.setName(name);
model.setKey(key);
model.setMetaInfo(modelNode.toString());
repositoryService.saveModel(model);
String id = model.getId();
repositoryService.addModelEditorSource(id, objectNode.toString().getBytes("utf-8"));
return id;
}
/**
* 发布模型为流程定义
*
* @param id
* @return
* @throws Exception
*/
@PostMapping("{id}/deployment")
public Object deploy(@PathVariable("id") String id) throws Exception {
//获取模型
Model modelData = repositoryService.getModel(id);
byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
if (bytes == null) {
return false;
}
JsonNode modelNode = new ObjectMapper().readTree(bytes);
BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
if (model.getProcesses().size() == 0) {
return false;
}
byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
//发布流程
String processName = modelData.getName() + ".bpmn20.xml";
Deployment deployment = repositoryService.createDeployment()
.name(modelData.getName())
.addString(processName, new String(bpmnBytes, "UTF-8"))
.deploy();
modelData.setDeploymentId(deployment.getId());
repositoryService.saveModel(modelData);
return true;
}
@GetMapping("/{id}")
public Object getOne(@PathVariable("id") String id) {
Model model = repositoryService.createModelQuery().modelId(id).singleResult();
return model;
}
@GetMapping
public Object query(ModelQueryCriteria criteria, Pageable pageable) {
ModelQuery modelQuery=repositoryService.createModelQuery();
if (criteria.getId()!=null){
modelQuery.modelId(criteria.getId());
}
if (criteria.getName()!=null){
modelQuery.modelName(criteria.getName());
}
long count = modelQuery.count();
List<Model> list = modelQuery
.listPage(pageable.getPageSize() * pageable.getPageNumber(), pageable.getPageSize());
return new ResponseEntity<>(PageUtil.toPage(list,count),HttpStatus.OK);
}
@DeleteMapping("/{id}/delete")
public ResponseEntity deleteOne(@PathVariable("id") String id) {
repositoryService.deleteModel(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
kochetkov-ma/qa-tools
|
src/main/java/ru/iopump/qa/support/api/WithValue.java
|
package ru.iopump.qa.support.api;
import com.google.common.base.Objects;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import ru.iopump.qa.util.Str;
/**
* This object has some value and can give it. In common situation it's a {@link String} but it may be any other {@link Object}.
* And this object has special method {@link #hasValue} to check corresponding with this value and candidate value
* with special logic if at least one of these objects is {@link String}.
*/
public interface WithValue<T> {
/**
* This object has some value and can give it. In common situation it's a {@link String} but it may be any other {@link Object}.
* And this object has special method {@link #hasValue} to check corresponding with this value and candidate value
* with special logic if at least one of these objects is {@link String}.
*
* @return Objects value.
*/
@Nullable
T getValue();
/**
* Smart check value if equals to {@link #getValue()}. For string use {@link StringUtils#equalsAnyIgnoreCase}
*
* @param candidateValue Candidate object or {@link String}
* @return true - candidateValue corresponds to {@link #getValue()}.
*/
default boolean hasValue(@Nullable T candidateValue) {
if (getValue() instanceof String || candidateValue instanceof String) {
return StringUtils.equalsAnyIgnoreCase(Str.toStr(candidateValue), Str.toStr(getValue()));
}
return Objects.equal(getValue(), candidateValue);
}
}
|
hmrc/api-gatekeeper-frontend
|
app/services/DeveloperService.scala
|
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package services
import config.AppConfig
import connectors._
import javax.inject.Inject
import model._
import model.TopicOptionChoice._
import uk.gov.hmrc.http.HeaderCarrier
import scala.concurrent.{ExecutionContext, Future}
class DeveloperService @Inject()(appConfig: AppConfig,
developerConnector: DeveloperConnector,
sandboxApplicationConnector: SandboxApplicationConnector,
productionApplicationConnector: ProductionApplicationConnector)(implicit ec: ExecutionContext) {
def searchDevelopers(filter: Developers2Filter)(implicit hc: HeaderCarrier): Future[List[User]] = {
val unsortedResults: Future[List[User]] = (filter.maybeEmailFilter, filter.maybeApiFilter) match {
case (emailFilter, None) => developerConnector.searchDevelopers(emailFilter, filter.developerStatusFilter)
case (maybeEmailFilter, Some(apiFilter)) => {
for {
collaboratorEmails <- getCollaboratorsByApplicationEnvironments(filter.environmentFilter, maybeEmailFilter, apiFilter)
users <- developerConnector.fetchByEmails(collaboratorEmails)
filteredRegisteredUsers <- Future.successful(users.filter(user => collaboratorEmails.contains(user.email)))
filteredByDeveloperStatusUsers <- Future.successful(filteredRegisteredUsers.filter(filter.developerStatusFilter.isMatch))
} yield filteredByDeveloperStatusUsers
}
}
for {
results <- unsortedResults
} yield results.sortBy(_.email)
}
private def getCollaboratorsByApplicationEnvironments(environmentFilter : ApiSubscriptionInEnvironmentFilter,
maybeEmailFilter: Option[String],
apiFilter: ApiContextVersion)
(implicit hc: HeaderCarrier): Future[Set[String]] = {
val environmentApplicationConnectors = environmentFilter match {
case ProductionEnvironment => List(productionApplicationConnector)
case SandboxEnvironment => List(sandboxApplicationConnector)
case AnyEnvironment => List(productionApplicationConnector, sandboxApplicationConnector)
}
val allCollaboratorEmailsFutures: List[Future[List[String]]] = environmentApplicationConnectors
.map(_.searchCollaborators(apiFilter.context, apiFilter.version, maybeEmailFilter))
combine(allCollaboratorEmailsFutures).map(_.toSet)
}
def filterUsersBy(filter: ApiFilter[String], apps: List[Application])
(users: List[Developer]): List[Developer] = {
val registeredEmails = users.map(_.user.email)
type KEY = Tuple2[String, UserId]
def asKey(collaborator: Collaborator): KEY = ((collaborator.emailAddress, collaborator.userId))
def asUnregisteredUser(c: KEY): UnregisteredUser = UnregisteredUser(c._1, c._2)
def linkAppsAndCollaborators(apps: List[Application]): Map[KEY, Set[Application]] = {
apps.foldLeft(Map.empty[KEY, Set[Application]])((uMap, appResp) =>
appResp.collaborators.foldLeft(uMap)((m, c) => {
val userApps = m.getOrElse(asKey(c), Set.empty[Application]) + appResp
m + (asKey(c) -> userApps)
}))
}
lazy val unregisteredCollaborators: Map[KEY, Set[Application]] =
linkAppsAndCollaborators(apps).filterKeys(k => !registeredEmails.contains(k._1))
lazy val unregistered: Set[Developer] =
unregisteredCollaborators.map {
case (key,userApps) => Developer(asUnregisteredUser(key), userApps.toList)
}.toSet
lazy val (usersWithoutApps, usersWithApps) = users.partition(_.applications.isEmpty)
filter match {
case AllUsers => users ++ unregistered
case NoApplications => usersWithoutApps
case NoSubscriptions | OneOrMoreSubscriptions | OneOrMoreApplications | Value(_, _) => usersWithApps ++ unregistered
}
}
def filterUsersBy(filter: StatusFilter)(developers: List[Developer]): List[Developer] = {
filter match {
case AnyStatus => developers
case _ => developers.filter(d => filter == User.status(d.user))
}
}
def getDevelopersWithApps(apps: List[Application], users: List[User]): List[Developer] = {
def isACollaboratorForApp(user: User)(app: Application): Boolean = app.collaborators.find(_.emailAddress == user.email).isDefined
def collaboratingApps(user: User): List[Application] = {
apps.filter(isACollaboratorForApp(user))
}
users.map(u => {
Developer(u, collaboratingApps(u))
})
}
def fetchUsers(implicit hc: HeaderCarrier): Future[List[RegisteredUser]] = {
developerConnector.fetchAll.map(_.sortBy(_.sortField))
}
def seekUser(email: String)(implicit hc: HeaderCarrier): Future[Option[User]] = {
developerConnector.seekUserByEmail(email)
}
def fetchOrCreateUser(email: String)(implicit hc: HeaderCarrier): Future[User] = {
developerConnector.fetchOrCreateUser(email)
}
def fetchUser(email: String)(implicit hc: HeaderCarrier): Future[User] = {
developerConnector.fetchByEmail(email)
}
def fetchDeveloper(userId: UserId)(implicit hc: HeaderCarrier): Future[Developer] = fetchDeveloper(UuidIdentifier(userId))
def fetchDeveloper(developerId: DeveloperIdentifier)(implicit hc: HeaderCarrier): Future[Developer] =
for {
user <- developerConnector.fetchById(developerId)
sandboxApplications <- sandboxApplicationConnector.fetchApplicationsByUserId(user.userId)
productionApplications <- productionApplicationConnector.fetchApplicationsByUserId(user.userId)
} yield Developer(user, (sandboxApplications ++ productionApplications).distinct)
def fetchDevelopersByEmails(emails: Iterable[String])(implicit hc: HeaderCarrier): Future[List[RegisteredUser]] = {
developerConnector.fetchByEmails(emails)
}
def fetchDevelopersByEmailPreferences(topic: TopicOptionChoice, maybeApiCategory: Option[APICategory] = None)(implicit hc: HeaderCarrier): Future[List[RegisteredUser]] = {
developerConnector.fetchByEmailPreferences(topic, maybeApiCategory = maybeApiCategory.map(List(_)))
}
def fetchDevelopersByAPICategoryEmailPreferences(topic: TopicOptionChoice, apiCategory: APICategory)(implicit hc: HeaderCarrier) = {
developerConnector.fetchByEmailPreferences(topic, maybeApiCategory = Some(Seq(apiCategory)))
}
def fetchDevelopersBySpecificAPIEmailPreferences(topic: TopicOptionChoice, apiCategories: List[APICategory], apiNames: List[String])(implicit hc: HeaderCarrier) = {
developerConnector.fetchByEmailPreferences(topic, Some(apiNames), Some(apiCategories.distinct))
}
def removeMfa(developerId: DeveloperIdentifier, loggedInUser: String)(implicit hc: HeaderCarrier): Future[RegisteredUser] = {
developerConnector.removeMfa(developerId, loggedInUser)
}
def deleteDeveloper(developerId: DeveloperIdentifier, gatekeeperUserId: String)(implicit hc: HeaderCarrier): Future[(DeveloperDeleteResult, Developer)] = {
def fetchAdminsToEmail(email: String)(app: Application): Future[Set[String]] = {
if (app.deployedTo == "SANDBOX") {
Future.successful(Set.empty)
} else {
val appAdmins = app.admins.filterNot(_.emailAddress == email).map(_.emailAddress)
for {
users <- fetchDevelopersByEmails(appAdmins)
verifiedUsers = users.toSet.filter(_.verified)
adminsToEmail = verifiedUsers.map(_.email)
} yield adminsToEmail
}
}
def removeTeamMemberFromApp(email: String)(app: Application) = {
val connector = if (app.deployedTo == "PRODUCTION") productionApplicationConnector else sandboxApplicationConnector
for {
adminsToEmail <- fetchAdminsToEmail(email)(app)
result <- connector.removeCollaborator(app.id, email, gatekeeperUserId, adminsToEmail)
} yield result
}
fetchDeveloper(developerId).flatMap { developer =>
val email = developer.email
val (appsSoleAdminOn, appsTeamMemberOn) = developer.applications.partition(_.isSoleAdmin(email))
if (appsSoleAdminOn.isEmpty) {
for {
_ <- Future.traverse(appsTeamMemberOn)(removeTeamMemberFromApp(email))
result <- developerConnector.deleteDeveloper(DeleteDeveloperRequest(gatekeeperUserId, email))
} yield (result, developer)
} else {
Future.successful((DeveloperDeleteFailureResult, developer))
}
}
}
private def combine[T](futures: List[Future[List[T]]]): Future[List[T]] = Future.reduceLeft(futures)(_ ++ _)
}
|
IamMayankThakur/test-bigdata
|
adminmgr/media/code/python/map1/BD_665_962_725_mapper.py
|
#!/usr/bin/python3
import sys
import csv
for line in sys.stdin:
line = line.strip()
list_ = line.split(",")
try:
batsman = list_[4]
bowler = list_[6]
if(list_[9] == "caught" or list_[9] == "bowled" or list_[9] == "lbw" or list_[9] == "caught and bowled" or list_[9] == "stumped" ):
print('%s,%s,%d,%d'% (batsman,bowler,1,1))
else:
print('%s,%s,%d,%d'% (batsman,bowler,0,1))
except:
continue
|
smoorebox/box-ui-elements
|
src/icons/general/IconAlertBlank.js
|
// @flow
import * as React from 'react';
import AccessibleSVG from '../accessible-svg';
type Props = {
className?: string,
height?: number,
/** A text-only string describing the icon if it's not purely decorative for accessibility */
title?: string | React.Element<any>,
width?: number,
};
const IconAlertBlank = ({ className = '', height = 26, title, width = 26 }: Props) => (
<AccessibleSVG
className={`icon-alert-blank ${className}`}
height={height}
title={title}
viewBox="0 0 26 26"
width={width}
>
<defs>
<circle cx="8" cy="8" id="b" r="8" />
<filter filterUnits="objectBoundingBox" height="193.8%" id="a" width="193.8%" x="-46.9%" y="-46.9%">
<feMorphology in="SourceAlpha" operator="dilate" radius=".5" result="shadowSpreadOuter1" />
<feOffset in="shadowSpreadOuter1" result="shadowOffsetOuter1" />
<feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="2" />
<feColorMatrix
in="shadowBlurOuter1"
values="0 0 0 0 0.733285502 0 0 0 0 0.733285502 0 0 0 0 0.733285502 0 0 0 0.5 0"
/>
</filter>
</defs>
<g fill="none" fillRule="evenodd" transform="translate(5 5)">
<use fill="#000" filter="url(#a)" xlinkHref="#b" />
<use fill="#F7931D" xlinkHref="#b" />
</g>
</AccessibleSVG>
);
export default IconAlertBlank;
|
booknara/playground
|
src/test/java/com/booknara/problem/stack/BasicCalculatorTest.java
|
package com.booknara.problem.stack;
import org.junit.Assert;
import org.junit.Test;
public class BasicCalculatorTest {
@Test
public void calculate() {
BasicCalculator basicCalculator = new BasicCalculator();
Assert.assertEquals(92, basicCalculator.calculate(" 32 + 60"));
Assert.assertEquals(4, basicCalculator.calculate("2-1+3"));
Assert.assertEquals(55, basicCalculator.calculate(" (3+52 )"));
Assert.assertEquals(23, basicCalculator.calculate("(1+(4+5+2)-3)+(6+8)"));
Assert.assertEquals(-4, basicCalculator.calculate("1-(5)"));
}
}
|
ReliSA/crce-client
|
client-java/src/main/java/cz/zcu/kiv/crce/client/java/RecursiveJavaMetadataParser.java
|
<filename>client-java/src/main/java/cz/zcu/kiv/crce/client/java/RecursiveJavaMetadataParser.java
package cz.zcu.kiv.crce.client.java;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.ParametersAreNonnullByDefault;
import cz.zcu.kiv.jacc.javatypes.JClass;
import cz.zcu.kiv.jacc.javatypes.JField;
import cz.zcu.kiv.jacc.javatypes.JMethod;
import cz.zcu.kiv.jacc.javatypes.JPackage;
import cz.zcu.kiv.jacc.javatypes.JType;
import cz.zcu.kiv.crce.client.base.Constants;
import cz.zcu.kiv.crce.client.base.metadata.AttributeVO;
import cz.zcu.kiv.crce.client.base.metadata.GenericRequirementVO;
/**
* Recursive {@link JavaMetadataParser} implementation.
*
* Date: 24.11.15
*
* @author <NAME>
* @author <NAME>
*
*/
@ParametersAreNonnullByDefault
public class RecursiveJavaMetadataParser implements JavaMetadataParser {
@Override
public Set<GenericRequirementVO> parse(Set<JPackage> toParse) {
Map<String, GenericRequirementVO> packages = new HashMap<>();
String pckgName;
GenericRequirementVO pckg;
for (JPackage jPackage : toParse) {
pckgName = jPackage.getName();
pckg = packages.get(pckgName);
if(pckg == null) {
pckg = createPackage(pckgName);
packages.put(pckgName, pckg);
}
for (JClass jClass : jPackage.getJClasses()) {
pckg.getChildren().add(parseClass(jClass));
}
}
return new HashSet<>(packages.values());
}
@Override
public Set<JPackage> map(Set<GenericRequirementVO> requirements) {
throw new UnsupportedOperationException("Not supported yet!");
}
/**
*
* @param jClass class to be transformed into requirements
* @return requirements representing the given class
*/
private GenericRequirementVO parseClass(JClass jClass) {
boolean firstLevel = jClass.getOuterClass() == null;
GenericRequirementVO req;
if(firstLevel) {
req = new GenericRequirementVO();
req.setNamespace(Constants.NAMESPACE__JAVA_CLASS);
} else {
req = new GenericRequirementVO();
req.setNamespace(Constants.NAMESPACE__JAVA_INNER_CLASS);
}
List<AttributeVO> attributes = req.getAttributes();
attributes.add(new AttributeVO(Constants.ATTRIBUTE__NAME, jClass.getShortName()));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__ABSTRACT, jClass.getModifiers().isAbstract()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__ENUM, jClass.isEnum()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__INTERFACE, jClass.isInterface()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__ANNOTATION, jClass.isAnnotation()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__FINAL, jClass.getModifiers().isFinal()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__STATIC, jClass.getModifiers().isStatic()+"", Boolean.class));
for (JMethod jMethod : jClass.getMethods()) {
req.getChildren().add(parseMethod(jMethod));
}
for (JField jField : jClass.getFields()) {
req.getChildren().add(parseField(jField));
}
for (JClass aClass : jClass.getInnerClasses()) {
req.getChildren().add(parseClass(aClass));
}
return req;
}
/**
*
* @param jField field to be transformed into requirements
* @return requirements representing the given field
*/
private GenericRequirementVO parseField(JField jField) {
GenericRequirementVO req = new GenericRequirementVO();
req.setNamespace(Constants.NAMESPACE__JAVA_FIELD);
List<AttributeVO> attributes = req.getAttributes();
attributes.add(new AttributeVO(Constants.ATTRIBUTE__NAME, jField.getName()));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__FINAL, jField.getModifiers().isFinal()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__STATIC, jField.getModifiers().isStatic()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__VOLATILE, jField.getModifiers().isVolatile()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__TYPE, jField.getType().getName()));
return req;
}
/**
*
* @param jMethod method to be transformed into requirements
* @return requirements representing the given method
*/
private GenericRequirementVO parseMethod(JMethod jMethod) {
GenericRequirementVO req = new GenericRequirementVO();
req.setNamespace(Constants.NAMESPACE__JAVA_METHOD);
List<AttributeVO> attributes = req.getAttributes();
attributes.add(new AttributeVO(Constants.ATTRIBUTE__NAME, jMethod.getName()));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__CONSTRUCTOR, jMethod.isConstructor()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__ABSTRACT, jMethod.getModifiers().isAbstract()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__FINAL, jMethod.getModifiers().isFinal()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__STATIC, jMethod.getModifiers().isStatic()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__SYNCHRONIZED, jMethod.getModifiers().isSynchronized()+"", Boolean.class));
attributes.add(new AttributeVO(Constants.ATTRIBUTE__RETURN_TYPE, jMethod.getReturnType().getName()));
List<String> tmp = new LinkedList<>();
for (JType jType : jMethod.getParameterTypes()) {
tmp.add(jType.getName());
}
if(tmp.size() > 0){
attributes.add(new AttributeVO(Constants.ATTRIBUTE__PARAM_TYPES, tmp.toString(), List.class));
}
tmp = new LinkedList<>();
for (JType jType : jMethod.getExceptionTypes()) {
tmp.add(jType.getName());
}
if(tmp.size() > 0){
attributes.add(new AttributeVO(Constants.ATTRIBUTE__EXCEPTIONS, tmp.toString(), List.class));
}
return req;
}
/**
*
* @param packageName name of the package for which the requirements is created
* @return requirements representing the given package
*/
private GenericRequirementVO createPackage(String packageName) {
GenericRequirementVO req = new GenericRequirementVO();
req.setNamespace(Constants.NAMESPACE__JAVA_PACKAGE);
List<AttributeVO> attributes = req.getAttributes();
attributes.add(new AttributeVO(Constants.ATTRIBUTE__NAME, packageName));
return req;
}
}
|
McMurphy-Luo/leetcode
|
src/Longest Palindromic Substring.cpp
|
<gh_stars>0
#include "catch.hpp"
#include <string>
#include <vector>
using std::string;
using std::vector;
struct Palindrome {
size_t begin;
size_t end;
Palindrome()
: begin(0)
, end(0) {
}
};
class Solution {
public:
string longestPalindrome(string s) {
vector<Palindrome> palindromes_found;
for (size_t i = 0; i < s.size(); ++i) {
Palindrome one_item_found;
one_item_found.begin = i;
one_item_found.end = i;
palindromes_found.push_back(one_item_found);
if ((i + 1) < s.size() && s.at(i) == s.at(i + 1)) {
one_item_found.begin = i;
one_item_found.end = i + 1;
palindromes_found.push_back(one_item_found);
}
}
Palindrome longest_pralindrome;
longest_pralindrome.begin = 0;
longest_pralindrome.end = 0;
for (
vector<Palindrome>::const_iterator it = palindromes_found.begin();
it != palindromes_found.end();
++it
) {
Palindrome item = *it;
assert(item.begin == item.end || (item.end - item.begin) == 1);
size_t half_palindrome_length = 0;
while (true) {
if (
item.begin < half_palindrome_length
||
item.end + half_palindrome_length >= s.size()
) {
--half_palindrome_length;
break;
}
if (s.at(item.begin - half_palindrome_length) != s.at(item.end + half_palindrome_length)) {
--half_palindrome_length;
break;
}
++half_palindrome_length;
}
if ((longest_pralindrome.end - longest_pralindrome.begin) < (item.end - item.begin + 2 * half_palindrome_length)) {
longest_pralindrome.end = item.end + half_palindrome_length;
longest_pralindrome.begin = item.begin - half_palindrome_length;
}
}
return s.substr(longest_pralindrome.begin, longest_pralindrome.end - longest_pralindrome.begin + 1);
}
};
TEST_CASE("Test the solution for problem 'Longest Palindromic Substring'") {
string input_1 = "babad";
string output_1_1 = "bab";
string output_1_2 = "aba";
string input_2 = "cbbd";
string output_2 = "bb";
Solution sln_instance;
string output_1 = sln_instance.longestPalindrome(input_1);
CHECK((output_1 == output_1_1 || output_1 == output_1_2));
CHECK(sln_instance.longestPalindrome(input_2) == output_2);
}
|
poetix/fluvius
|
fluvius-core/src/main/java/com/codepoetics/fluvius/conditions/Conditions.java
|
package com.codepoetics.fluvius.conditions;
import com.codepoetics.fluvius.api.Condition;
import com.codepoetics.fluvius.api.functional.Predicate;
import com.codepoetics.fluvius.api.functional.ScratchpadPredicate;
import com.codepoetics.fluvius.api.scratchpad.Key;
import com.codepoetics.fluvius.api.scratchpad.Scratchpad;
import com.codepoetics.fluvius.predicates.Predicates;
import java.util.UUID;
/**
* Utility class for working with Conditions.
*/
public final class Conditions {
private Conditions() {
}
/**
* Create a Condition with the given description, which tests a Scratchpad with the given ScratchpadPredicate.
*
* @param description The description of the Condition.
* @param predicate The ScratchpadPredicate to apply to the Scratchpad.
* @return The constructed Condition.
*/
public static Condition fromPredicate(String description, ScratchpadPredicate predicate) {
return new PredicateCondition(description, predicate);
}
/**
* Create a Condition which tests whether a failure is recorded in the Scratchpad against the given {@link Key}.
* @param key The key to test.
* @return The constructed Condition.
*/
public static Condition keyRecordsFailure(Key<?> key) {
return fromPredicate("Failure recorded for key '" + key.getName() + "'", Predicates.isFailure(key));
}
/**
* Create a Condition which tests that the Scratchpad contains the expected value at the given Key.
*
* @param key The Key to test.
* @param expected The expected Key-value.
* @param <T> The type of the Key/value.
* @return The constructed Condition.
*/
public static <T> Condition keyEquals(Key<T> key, T expected) {
return fromPredicate(key.getName() + " = " + expected, Predicates.keyEquals(key, expected));
}
/**
* Create a Condition which tests that the Scratchpad contains a value matching the given predicate at the given Key.
*
* @param key The Key to test.
* @param description Description of the predicate to be applied to the key's value.
* @param predicate The predicate to use to test the key's value.
* @param <T> The type of the Key/value.
* @return The constructed Condition.
*/
public static <T> Condition keyMatches(Key<T> key, String description, Predicate<T> predicate) {
return fromPredicate(key.getName() + " " + description, Predicates.keyMatches(key, predicate));
}
private static final class PredicateCondition implements Condition {
private final String description;
private final ScratchpadPredicate predicate;
private PredicateCondition(String description, ScratchpadPredicate predicate) {
this.description = description;
this.predicate = predicate;
}
@Override
public String getDescription() {
return description;
}
@Override
public boolean test(UUID flowId, Scratchpad scratchpad) {
return predicate.test(scratchpad);
}
}
}
|
Alexander-Iv/otus-java-hw
|
hw15-messageSystem/hw15-0-ms/src/main/java/alexander/ivanov/messageSystem/services/FeService.java
|
package alexander.ivanov.messageSystem.services;
public interface FeService extends Service {
void auth(String name, String password);
void registration(String name, String password);
}
|
deveshpatel0101/data_structures_algorithms
|
algorithms/power_set/power_set.go
|
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
fmt.Println("\n-- Generating Power Set (Set of Subsets)--")
var value int
fmt.Print("\nEnter a value: ")
fmt.Scanf("%d\n", &value)
list := PowerSet(value)
fmt.Println("All possible subsets upto", value, "are:")
for i := 0; i < len(list); i++ {
str := strings.Split(list[i], "")
fmt.Println("{" + strings.Join(str, ", ") + "}")
}
}
// PowerSet generates a set of all subsets of a given integer
func PowerSet(n int) []string {
if n == 0 {
return []string{"0"}
}
list := PowerSet(n - 1)
newList := make([]string, 0)
str := strconv.Itoa(n)
newList = append(newList, list...)
newList = append(newList, str)
for i := 1; i < len(list); i++ {
newList = append(newList, list[i]+str)
}
return newList
}
|
ScalablyTyped/SlinkyTyped
|
g/gl-shader/src/main/scala/typingsSlinky/glShader/mod.scala
|
package typingsSlinky.glShader
import org.scalablytyped.runtime.StringDictionary
import org.scalajs.dom.raw.WebGLProgram
import org.scalajs.dom.raw.WebGLRenderingContext
import org.scalajs.dom.raw.WebGLShader
import typingsSlinky.glShader.anon.Attributes
import typingsSlinky.glShader.anon.Fragment
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object mod {
@JSImport("gl-shader", JSImport.Namespace)
@js.native
def apply(gl: WebGLRenderingContext, options: Attributes): Shader = js.native
@JSImport("gl-shader", JSImport.Namespace)
@js.native
def apply(gl: WebGLRenderingContext, vertex: String, fragment: String): Shader = js.native
@JSImport("gl-shader", JSImport.Namespace)
@js.native
def apply(
gl: WebGLRenderingContext,
vertex: String,
fragment: String,
uniforms: js.UndefOr[scala.Nothing],
attributes: js.Array[Parameter]
): Shader = js.native
@JSImport("gl-shader", JSImport.Namespace)
@js.native
def apply(gl: WebGLRenderingContext, vertex: String, fragment: String, uniforms: js.Array[Parameter]): Shader = js.native
@JSImport("gl-shader", JSImport.Namespace)
@js.native
def apply(
gl: WebGLRenderingContext,
vertex: String,
fragment: String,
uniforms: js.Array[Parameter],
attributes: js.Array[Parameter]
): Shader = js.native
@js.native
trait Attribute extends StObject {
var location: js.Array[Double] | Double = js.native
def pointer(): Double = js.native
def pointer(
`type`: js.UndefOr[scala.Nothing],
normalized: js.UndefOr[scala.Nothing],
stride: js.UndefOr[scala.Nothing],
offset: Double
): Double = js.native
def pointer(`type`: js.UndefOr[scala.Nothing], normalized: js.UndefOr[scala.Nothing], stride: Double): Double = js.native
def pointer(
`type`: js.UndefOr[scala.Nothing],
normalized: js.UndefOr[scala.Nothing],
stride: Double,
offset: Double
): Double = js.native
def pointer(`type`: js.UndefOr[scala.Nothing], normalized: Boolean): Double = js.native
def pointer(
`type`: js.UndefOr[scala.Nothing],
normalized: Boolean,
stride: js.UndefOr[scala.Nothing],
offset: Double
): Double = js.native
def pointer(`type`: js.UndefOr[scala.Nothing], normalized: Boolean, stride: Double): Double = js.native
def pointer(`type`: js.UndefOr[scala.Nothing], normalized: Boolean, stride: Double, offset: Double): Double = js.native
def pointer(`type`: Double): Double = js.native
def pointer(
`type`: Double,
normalized: js.UndefOr[scala.Nothing],
stride: js.UndefOr[scala.Nothing],
offset: Double
): Double = js.native
def pointer(`type`: Double, normalized: js.UndefOr[scala.Nothing], stride: Double): Double = js.native
def pointer(`type`: Double, normalized: js.UndefOr[scala.Nothing], stride: Double, offset: Double): Double = js.native
def pointer(`type`: Double, normalized: Boolean): Double = js.native
def pointer(`type`: Double, normalized: Boolean, stride: js.UndefOr[scala.Nothing], offset: Double): Double = js.native
def pointer(`type`: Double, normalized: Boolean, stride: Double): Double = js.native
def pointer(`type`: Double, normalized: Boolean, stride: Double, offset: Double): Double = js.native
}
@js.native
trait Parameter extends StObject {
var name: String = js.native
var `type`: String = js.native
}
object Parameter {
@scala.inline
def apply(name: String, `type`: String): Parameter = {
val __obj = js.Dynamic.literal(name = name.asInstanceOf[js.Any])
__obj.updateDynamic("type")(`type`.asInstanceOf[js.Any])
__obj.asInstanceOf[Parameter]
}
@scala.inline
implicit class ParameterMutableBuilder[Self <: Parameter] (val x: Self) extends AnyVal {
@scala.inline
def setName(value: String): Self = StObject.set(x, "name", value.asInstanceOf[js.Any])
@scala.inline
def setType(value: String): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
}
}
@js.native
trait Shader extends StObject {
val attributes: StringDictionary[Attribute with js.Array[_]] = js.native
def bind(): Unit = js.native
def dispose(): Unit = js.native
val fragShader: WebGLShader = js.native
val gl: WebGLRenderingContext = js.native
val program: WebGLProgram = js.native
var uniforms: StringDictionary[js.Any] = js.native
def update(obj: Fragment): Unit = js.native
def update(vertex: String, fragment: String): Unit = js.native
def update(
vertex: String,
fragment: String,
uniforms: js.UndefOr[scala.Nothing],
attributes: js.Array[Parameter]
): Unit = js.native
def update(vertex: String, fragment: String, uniforms: js.Array[Parameter]): Unit = js.native
def update(vertex: String, fragment: String, uniforms: js.Array[Parameter], attributes: js.Array[Parameter]): Unit = js.native
val vertShader: WebGLShader = js.native
}
}
|
Uniandes-isis2603/s2_CentroDeportivo
|
s2_centrodeportivo-api/src/main/java/co/edu/uniandes/csw/centrodeportivo/dtos/EspecialistaDetailDTO.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.csw.centrodeportivo.dtos;
import co.edu.uniandes.csw.centrodeportivo.entities.DeportistaEntity;
import co.edu.uniandes.csw.centrodeportivo.entities.EspecialistaEntity;
import co.edu.uniandes.csw.centrodeportivo.entities.ObjetivoEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Clase que extiende de {@link EspecialistaDTO} para manejar las relaciones entre los
* EspecialistaDTO y otros DTOs. Para conocer el contenido de un Especialista vaya a la
* documentacion de {@link EspecialistaDTO}
* @author <NAME>
*/
public class EspecialistaDetailDTO extends EspecialistaDTO implements Serializable {
/*
* Esta lista de tipo DeportistaDTO contiene los deportistas que estan asociados a un especialista
*/
private List<DeportistaDTO> deportistas;
/*
* Esta lista de tipo ObjetivoDTO contiene los objetivos que estan asociados a un especialista
*/
private List<ObjetivoDTO> objetivos;
/**
* Constructor por defecto
*/
public EspecialistaDetailDTO()
{
}
/**
* Constructor para transformar un Entity a un DTO
*
* @param especialistaEntity La entidad del especialista para transformar a DTO.
*/
public EspecialistaDetailDTO(EspecialistaEntity especialistaEntity) {
super(especialistaEntity);
if (especialistaEntity != null) {
if (especialistaEntity.getDeportistas() != null) {
deportistas = new ArrayList<>();
for (DeportistaEntity entityDeportista : especialistaEntity.getDeportistas()) {
deportistas.add(new DeportistaDTO(entityDeportista));
}
}
if (especialistaEntity.getObjetivos() != null) {
objetivos = new ArrayList<>();
for (ObjetivoEntity entityObjetivo : especialistaEntity.getObjetivos()) {
objetivos.add(new ObjetivoDTO(entityObjetivo));
}
}
}
}
/**
* Convierte un objeto EspecialistaDetailDTO a EspecialistaEntity incluyendo los
* atributos de EspecialistaDTO.
* @return Nuevo objeto EspecialistaEntity.
*/
@Override
public EspecialistaEntity toEntity() {
EspecialistaEntity especialistaEntity = super.toEntity();
if (deportistas != null) {
List<DeportistaEntity> deportistasEntity = new ArrayList<>();
for (DeportistaDTO dtoDeportista : deportistas) {
deportistasEntity.add(dtoDeportista.toEntity());
}
especialistaEntity.setDeportistas(deportistasEntity);
}
if (objetivos != null) {
List<ObjetivoEntity> objetivosEntity = new ArrayList<>();
for (ObjetivoDTO dtoObjetivo : objetivos) {
objetivosEntity.add(dtoObjetivo.toEntity());
}
especialistaEntity.setObjetivos(objetivosEntity);
}
return especialistaEntity;
}
/**
* Devuelve la lista de deportistas del especialista.
*
* @return Los deportistas del especialista
*/
public List<DeportistaDTO> getDeportistas()
{
return deportistas;
}
/**
* Modifica la lista de deportistas del especialista.
*
* @param deportistas las deportistas a modificar
*/
public void setDeportistas(List<DeportistaDTO> deportistas)
{
this.deportistas = deportistas;
}
/**
* Devuelve la lista de objetivos del especialista.
*
* @return Los objetivos del especialista
*/
public List<ObjetivoDTO> getObjetivos()
{
return objetivos;
}
/**
* Modifica la lista de máquinas del seguimiento.
*
* @param objetivos los objetivos a modificar
*/
public void setObjetivos(List<ObjetivoDTO> objetivos)
{
this.objetivos = objetivos;
}
/**
* Retorna el string del DTO
* @return string
*/
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
|
ElegastVZW/mock-xrm
|
src/retrieveMultipleWrapperMemo.js
|
<filename>src/retrieveMultipleWrapperMemo.js
import memoize from './utility/memoize';
import retrieveMultipleWrapper from './retrieveMultipleWrapper';
const retrieveMultipleWrapperMemo = memoize(retrieveMultipleWrapper);
export default retrieveMultipleWrapperMemo;
|
doyaGu/C0501Q_HWJL01
|
sdk/sdk/share/ucl/acc/acc_lib.h
|
/* ACC -- Automatic Compiler Configuration
Copyright (C) 1996-2004 <NAME>
All Rights Reserved.
This software is a copyrighted work licensed under the terms of
the GNU General Public License. Please consult the file "ACC_LICENSE"
for details.
<NAME>
<<EMAIL>>
http://www.oberhumer.com/
*/
#ifndef __ACC_LIB_H_INCLUDED
#define __ACC_LIB_H_INCLUDED 1
#if !defined(__ACCLIB_FUNCNAME)
# define __ACCLIB_FUNCNAME(f) f
#endif
#if !defined(ACCLIB_EXTERN)
# define ACCLIB_EXTERN(r,f) extern r __ACCLIB_FUNCNAME(f)
#endif
#if !defined(__ACCLIB_CONST_CAST_RETURN)
#if (ACC_CC_GNUC)
# define __ACCLIB_CONST_CAST_RETURN(type,var) \
{ union { type a; const type b; } u; u.b = (var); return u.a; }
#else
# define __ACCLIB_CONST_CAST_RETURN(type,var) return (type) (var);
#endif
#endif
#if (ACC_OS_WIN64)
# define acclib_handle_t acc_int64l_t
# define acclib_uhandle_t acc_uint64l_t
#elif (ACC_ARCH_IA32 && ACC_CC_MSC && (_MSC_VER >= 1300))
typedef __w64 long acclib_handle_t;
typedef __w64 unsigned long acclib_uhandle_t;
# define acclib_handle_t acclib_handle_t
# define acclib_uhandle_t acclib_uhandle_t
#else
# define acclib_handle_t long
# define acclib_uhandle_t unsigned long
#endif
/*************************************************************************
// wrap <ctype.h>
**************************************************************************/
#if 0
ACCLIB_EXTERN(int, acc_ascii_digit) (int);
ACCLIB_EXTERN(int, acc_ascii_islower) (int);
ACCLIB_EXTERN(int, acc_ascii_isupper) (int);
ACCLIB_EXTERN(int, acc_ascii_tolower) (int);
ACCLIB_EXTERN(int, acc_ascii_toupper) (int);
ACCLIB_EXTERN(int, acc_ascii_utolower) (int);
ACCLIB_EXTERN(int, acc_ascii_utoupper) (int);
#endif
#define acc_ascii_isdigit(c) (((unsigned)(c) - 48) < 10)
#define acc_ascii_islower(c) (((unsigned)(c) - 97) < 26)
#define acc_ascii_isupper(c) (((unsigned)(c) - 65) < 26)
#define acc_ascii_tolower(c) ((int)(c) + (acc_ascii_isupper(c) << 5))
#define acc_ascii_toupper(c) ((int)(c) - (acc_ascii_islower(c) << 5))
#define acc_ascii_utolower(c) acc_ascii_tolower((unsigned char)(c))
#define acc_ascii_utoupper(c) acc_ascii_toupper((unsigned char)(c))
/*************************************************************************
// huge pointer layer
**************************************************************************/
#ifndef acc_hsize_t
#if (ACC_HAVE_MM_HUGE_PTR)
# define acc_hsize_t unsigned long
# define acc_hvoid_p void __huge *
# define acc_hchar_p char __huge *
# define acc_hchar_pp char __huge * __huge *
# define acc_hbyte_p unsigned char __huge *
#else
# define acc_hsize_t size_t
# define acc_hvoid_p void *
# define acc_hchar_p char *
# define acc_hchar_pp char **
# define acc_hbyte_p unsigned char *
#endif
#endif
#ifndef ACC_FILE_P
#define ACC_FILE_P FILE *
#endif
/* halloc */
ACCLIB_EXTERN(acc_hvoid_p, acc_halloc) (acc_hsize_t);
ACCLIB_EXTERN(void, acc_hfree) (acc_hvoid_p);
/* dos_alloc */
#if (ACC_OS_DOS16 || ACC_OS_OS216)
ACCLIB_EXTERN(void __far*, acc_dos_alloc) (unsigned long);
ACCLIB_EXTERN(int, acc_dos_free) (void __far*);
#endif
/* string */
ACCLIB_EXTERN(int, acc_hmemcmp) (const acc_hvoid_p, const acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_hmemcpy) (acc_hvoid_p, const acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_hmemmove) (acc_hvoid_p, const acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_hmemset) (acc_hvoid_p, int, acc_hsize_t);
/* string */
ACCLIB_EXTERN(acc_hsize_t, acc_hstrlen) (const acc_hchar_p);
ACCLIB_EXTERN(int, acc_hstrcmp) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(int, acc_hstrncmp)(const acc_hchar_p, const acc_hchar_p, acc_hsize_t);
ACCLIB_EXTERN(int, acc_ascii_hstricmp) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(int, acc_ascii_hstrnicmp)(const acc_hchar_p, const acc_hchar_p, acc_hsize_t);
ACCLIB_EXTERN(int, acc_ascii_hmemicmp) (const acc_hvoid_p, const acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrstr) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_ascii_hstristr) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hvoid_p, acc_hmemmem) (const acc_hvoid_p, acc_hsize_t, const acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_ascii_hmemimem) (const acc_hvoid_p, acc_hsize_t, const acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrcpy) (acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrcat) (acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hsize_t, acc_hstrlcpy) (acc_hchar_p, const acc_hchar_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hsize_t, acc_hstrlcat) (acc_hchar_p, const acc_hchar_p, acc_hsize_t);
ACCLIB_EXTERN(int, acc_hstrscpy) (acc_hchar_p, const acc_hchar_p, acc_hsize_t);
ACCLIB_EXTERN(int, acc_hstrscat) (acc_hchar_p, const acc_hchar_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrccpy) (acc_hchar_p, const acc_hchar_p, int);
ACCLIB_EXTERN(acc_hvoid_p, acc_hmemccpy) (acc_hvoid_p, const acc_hvoid_p, int, acc_hsize_t);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrchr) (const acc_hchar_p, int);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrrchr) (const acc_hchar_p, int);
ACCLIB_EXTERN(acc_hchar_p, acc_ascii_hstrichr) (const acc_hchar_p, int);
ACCLIB_EXTERN(acc_hchar_p, acc_ascii_hstrrichr) (const acc_hchar_p, int);
ACCLIB_EXTERN(acc_hvoid_p, acc_hmemchr) (const acc_hvoid_p, int, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_hmemrchr) (const acc_hvoid_p, int, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_ascii_hmemichr) (const acc_hvoid_p, int, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_ascii_hmemrichr) (const acc_hvoid_p, int, acc_hsize_t);
ACCLIB_EXTERN(acc_hsize_t, acc_hstrspn) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hsize_t, acc_hstrrspn) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hsize_t, acc_hstrcspn) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hsize_t, acc_hstrrcspn) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrpbrk) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrrpbrk) (const acc_hchar_p, const acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrsep) (acc_hchar_pp, const acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_hstrrsep) (acc_hchar_pp, const acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_ascii_hstrlwr) (acc_hchar_p);
ACCLIB_EXTERN(acc_hchar_p, acc_ascii_hstrupr) (acc_hchar_p);
ACCLIB_EXTERN(acc_hvoid_p, acc_ascii_hmemlwr) (acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hvoid_p, acc_ascii_hmemupr) (acc_hvoid_p, acc_hsize_t);
/* stdio */
ACCLIB_EXTERN(acc_hsize_t, acc_hfread) (ACC_FILE_P, acc_hvoid_p, acc_hsize_t);
ACCLIB_EXTERN(acc_hsize_t, acc_hfwrite) (ACC_FILE_P, const acc_hvoid_p, acc_hsize_t);
/* io */
#if (ACC_HAVE_MM_HUGE_PTR)
ACCLIB_EXTERN(long, acc_hread) (int, acc_hvoid_p, long);
ACCLIB_EXTERN(long, acc_hwrite) (int, const acc_hvoid_p, long);
#endif
ACCLIB_EXTERN(long, acc_safe_hread) (int, acc_hvoid_p, long);
ACCLIB_EXTERN(long, acc_safe_hwrite) (int, const acc_hvoid_p, long);
/*************************************************************************
// wrap filename limits
**************************************************************************/
/* maximum length of full pathname (excl. '\0') */
#if !defined(ACC_FN_PATH_MAX)
#if (ACC_OS_DOS16 || ACC_OS_WIN16)
# define ACC_FN_PATH_MAX 143
#elif (ACC_OS_DOS32 || ACC_OS_OS2 || ACC_OS_OS216 || ACC_OS_WIN32 || ACC_OS_WIN64)
# define ACC_FN_PATH_MAX 259
#elif (ACC_OS_TOS)
# define ACC_FN_PATH_MAX 259
#endif
#endif
#if !defined(ACC_FN_PATH_MAX)
/* arbitrary limit for acclib implementation */
# define ACC_FN_PATH_MAX 1024
#endif
/* maximum length of a filename (a single path component) (excl. '\0') */
#if !defined(ACC_FN_NAME_MAX)
#if (ACC_OS_DOS16 || ACC_OS_WIN16)
# define ACC_FN_NAME_MAX 12
#elif (ACC_OS_TOS && (ACC_CC_PUREC || ACC_CC_TURBOC))
# define ACC_FN_NAME_MAX 12
#elif (ACC_OS_DOS32 && ACC_CC_GNUC) && defined(__DJGPP__)
#elif (ACC_OS_DOS32)
# define ACC_FN_NAME_MAX 12
#endif
#endif
#if !defined(ACC_FN_NAME_MAX)
# define ACC_FN_NAME_MAX ACC_FN_PATH_MAX
#endif
#define ACC_FNMATCH_NOESCAPE 1
#define ACC_FNMATCH_PATHNAME 2
#define ACC_FNMATCH_PATHSTAR 4
#define ACC_FNMATCH_PERIOD 8
#define ACC_FNMATCH_ASCII_CASEFOLD 16
ACCLIB_EXTERN(int, acc_fnmatch) (const acc_hchar_p, const acc_hchar_p, int);
/*************************************************************************
// wrap <dirent.h>
**************************************************************************/
#undef __ACCLIB_USE_OPENDIR
#if (HAVE_DIRENT_H || ACC_CC_WATCOMC)
# define __ACCLIB_USE_OPENDIR 1
# if (ACC_OS_DOS32 && defined(__BORLANDC__))
# elif (ACC_OS_DOS32 && ACC_CC_GNUC) && defined(__DJGPP__)
# elif (ACC_OS_OS2 || ACC_OS_OS216)
# elif (ACC_OS_TOS && ACC_CC_GNUC)
# elif (ACC_OS_WIN32 && !defined(ACC_HAVE_WINDOWS_H))
# elif (ACC_OS_DOS16 || ACC_OS_DOS32 || ACC_OS_OS2 || ACC_OS_OS216 || ACC_OS_TOS || ACC_OS_WIN16 || ACC_OS_WIN32 || ACC_OS_WIN64)
# undef __ACCLIB_USE_OPENDIR
# endif
#endif
typedef struct
{
#if defined(__ACCLIB_USE_OPENDIR)
void *u_dirp; /* private */
# if (ACC_CC_WATCOMC)
unsigned short f_time;
unsigned short f_date;
unsigned long f_size;
# endif
char f_name[ACC_FN_NAME_MAX+1];
#elif (ACC_OS_WIN32 || ACC_OS_WIN64)
acclib_handle_t u_handle; /* private */
unsigned f_attr;
unsigned f_size_low;
unsigned f_size_high;
char f_name[ACC_FN_NAME_MAX+1];
#elif (ACC_OS_DOS16 || ACC_OS_DOS32 || ACC_OS_TOS || ACC_OS_WIN16)
char u_dta[21]; /* private */
unsigned char f_attr;
unsigned short f_time;
unsigned short f_date;
unsigned short f_size_low;
unsigned short f_size_high;
char f_name[ACC_FN_NAME_MAX+1];
char u_dirp; /* private */
#else
void *u_dirp; /* private */
char f_name[ACC_FN_NAME_MAX+1];
#endif
} acc_dir_t;
#ifndef acc_dir_p
#define acc_dir_p acc_dir_t *
#endif
ACCLIB_EXTERN(int, acc_opendir) (acc_dir_p, const char*);
ACCLIB_EXTERN(int, acc_readdir) (acc_dir_p);
ACCLIB_EXTERN(int, acc_closedir) (acc_dir_p);
/*************************************************************************
// wrap misc
**************************************************************************/
#if (ACC_CC_GNUC) && (defined(__CYGWIN__) || defined(__MINGW32__))
# define acc_alloca(x) __builtin_alloca((x))
#elif (ACC_CC_BORLANDC) && defined(__linux__)
/* FIXME: alloca does not work */
#elif (HAVE_ALLOCA)
# define acc_alloca(x) alloca((x))
#endif
#if (ACC_OS_DOS32 && ACC_CC_GNUC) && defined(__DJGPP__)
# define acc_stackavail() stackavail()
#elif (ACC_ARCH_IA16 && ACC_CC_BORLANDC && (__BORLANDC__ >= 0x0410))
# define acc_stackavail() stackavail()
#elif (ACC_ARCH_IA16 && ACC_CC_BORLANDC && (__BORLANDC__ >= 0x0400))
# if (ACC_OS_WIN16) && (ACC_MM_TINY || ACC_MM_SMALL || ACC_MM_MEDIUM)
# else
# define acc_stackavail() stackavail()
# endif
#elif ((ACC_ARCH_IA16 || ACC_ARCH_IA32) && (ACC_CC_DMC || ACC_CC_SYMANTECC))
# define acc_stackavail() stackavail()
#elif ((ACC_ARCH_IA16) && ACC_CC_MSC && (_MSC_VER >= 700))
# define acc_stackavail() _stackavail()
#elif ((ACC_ARCH_IA16) && ACC_CC_MSC)
# define acc_stackavail() stackavail()
#elif ((ACC_ARCH_IA16 || ACC_ARCH_IA32) && ACC_CC_TURBOC && (__TURBOC__ >= 0x0450))
# define acc_stackavail() stackavail()
#elif (ACC_ARCH_IA16 && ACC_CC_TURBOC && (__TURBOC__ >= 0x0400))
ACC_EXTERN_C size_t __cdecl stackavail(void);
# define acc_stackavail() stackavail()
#elif ((ACC_ARCH_IA16 || ACC_ARCH_IA32) && (ACC_CC_WATCOMC))
# define acc_stackavail() stackavail()
#elif (ACC_ARCH_IA16 && ACC_CC_ZORTECHC)
# define acc_stackavail() _chkstack()
#endif
ACCLIB_EXTERN(acclib_handle_t, acc_get_osfhandle) (int);
ACCLIB_EXTERN(int, acc_isatty) (int);
ACCLIB_EXTERN(int, acc_mkdir) (const char*, unsigned);
ACCLIB_EXTERN(int, acc_response) (int*, char***);
ACCLIB_EXTERN(int, acc_set_binmode) (int, int);
ACCLIB_EXTERN(acc_int32l_t, acc_muldiv32) (acc_int32l_t, acc_int32l_t, acc_int32l_t);
ACCLIB_EXTERN(acc_uint32l_t, acc_umuldiv32) (acc_uint32l_t, acc_uint32l_t, acc_uint32l_t);
ACCLIB_EXTERN(void, acc_wildargv) (int*, char***);
/*************************************************************************
// uclock (real, i.e. "wall" clock)
**************************************************************************/
#if defined(acc_int32e_t)
ACCLIB_EXTERN(int, acc_tsc_read) (acc_uint32e_t*);
ACCLIB_EXTERN(int, acc_tsc_read_add) (acc_uint32e_t*);
#endif
typedef struct { /* all private */
acclib_handle_t h;
int mode;
#if (ACC_HAVE_WINDOWS_H) && defined(acc_int64l_t)
double qpf;
#endif
} acc_uclock_handle_t;
typedef struct { /* all private */
union {
acc_uint32l_t t32;
#if !(ACC_OS_DOS16 || ACC_OS_WIN16)
double td;
# if defined(acc_int64l_t)
acc_int64l_t t64;
# endif
#endif
} ticks;
#if (ACC_HAVE_WINDOWS_H) && defined(acc_int64l_t)
acc_int64l_t qpc;
#endif
} acc_uclock_t;
#ifndef acc_uclock_handle_p
#define acc_uclock_handle_p acc_uclock_handle_t *
#endif
#ifndef acc_uclock_p
#define acc_uclock_p acc_uclock_t *
#endif
ACCLIB_EXTERN(int, acc_uclock_open) (acc_uclock_handle_p);
ACCLIB_EXTERN(int, acc_uclock_close) (acc_uclock_handle_p);
ACCLIB_EXTERN(void, acc_uclock_read) (acc_uclock_handle_p, acc_uclock_p);
ACCLIB_EXTERN(double, acc_uclock_get_elapsed) (acc_uclock_handle_p, const acc_uclock_p, const acc_uclock_p);
/*************************************************************************
// performance counters (virtual clock)
**************************************************************************/
#if defined(acc_int64l_t)
typedef struct { /* all private */
void* h;
unsigned cpu_type, cpu_features, cpu_khz, cpu_nrctrs;
const char* cpu_name;
} acc_perfctr_handle_t;
typedef struct {
acc_uint64l_t tsc;
#if (ACC_OS_POSIX_LINUX)
acc_uint64l_t pmc[18];
#else
acc_uint64l_t pmc[1];
#endif
} acc_perfctr_clock_t;
#ifndef acc_perfctr_handle_p
#define acc_perfctr_handle_p acc_perfctr_handle_t *
#endif
#ifndef acc_perfctr_clock_p
#define acc_perfctr_clock_p acc_perfctr_clock_t *
#endif
ACCLIB_EXTERN(int, acc_perfctr_open) (acc_perfctr_handle_p);
ACCLIB_EXTERN(int, acc_perfctr_close) (acc_perfctr_handle_p);
ACCLIB_EXTERN(void, acc_perfctr_read) (acc_perfctr_handle_p, acc_perfctr_clock_p);
ACCLIB_EXTERN(double, acc_perfctr_get_elapsed) (acc_perfctr_handle_p, const acc_perfctr_clock_p, const acc_perfctr_clock_p);
ACCLIB_EXTERN(double, acc_perfctr_get_elapsed_tsc) (acc_perfctr_handle_p, acc_uint64l_t);
#endif
/*************************************************************************
// Big Endian / Little Endian
**************************************************************************/
ACCLIB_EXTERN(unsigned, acc_get_be16) (const acc_hvoid_p);
ACCLIB_EXTERN(acc_uint32l_t, acc_get_be24) (const acc_hvoid_p);
ACCLIB_EXTERN(acc_uint32l_t, acc_get_be32) (const acc_hvoid_p);
ACCLIB_EXTERN(void, acc_set_be16) (acc_hvoid_p, unsigned);
ACCLIB_EXTERN(void, acc_set_be24) (acc_hvoid_p, acc_uint32l_t);
ACCLIB_EXTERN(void, acc_set_be32) (acc_hvoid_p, acc_uint32l_t);
ACCLIB_EXTERN(unsigned, acc_get_le16) (const acc_hvoid_p);
ACCLIB_EXTERN(acc_uint32l_t, acc_get_le24) (const acc_hvoid_p);
ACCLIB_EXTERN(acc_uint32l_t, acc_get_le32) (const acc_hvoid_p);
ACCLIB_EXTERN(void, acc_set_le16) (acc_hvoid_p, unsigned);
ACCLIB_EXTERN(void, acc_set_le24) (acc_hvoid_p, acc_uint32l_t);
ACCLIB_EXTERN(void, acc_set_le32) (acc_hvoid_p, acc_uint32l_t);
#if defined(acc_uint64l_t)
ACCLIB_EXTERN(acc_uint64l_t, acc_get_be64) (const acc_hvoid_p);
ACCLIB_EXTERN(void, acc_set_be64) (acc_hvoid_p, acc_uint64l_t);
ACCLIB_EXTERN(acc_uint64l_t, acc_get_le64) (const acc_hvoid_p);
ACCLIB_EXTERN(void, acc_set_le64) (acc_hvoid_p, acc_uint64l_t);
#endif
/* inline versions */
#if (ACC_ARCH_AMD64 || ACC_ARCH_IA32)
# define ACC_GET_LE16(p) (* (const unsigned short *) (p))
# define ACC_GET_LE32(p) (* (const acc_uint32e_t *) (p))
# define ACC_SET_LE16(p,v) (* (unsigned short *) (p) = (unsigned short) (v))
# define ACC_SET_LE32(p,v) (* (acc_uint32e_t *) (p) = (acc_uint32e_t) (v))
#endif
#if (ACC_ARCH_AMD64)
# define ACC_GET_LE64(p) (* (const acc_uint64l_t *) (p))
# define ACC_SET_LE64(p,v) (* (acc_uint64l_t *) (p) = (acc_uint64l_t) (v))
#endif
/*************************************************************************
// getopt
**************************************************************************/
typedef struct {
const char* name;
int has_arg;
int* flag;
int val;
} acc_getopt_longopt_t;
#ifndef acc_getopt_longopt_p
#define acc_getopt_longopt_p acc_getopt_longopt_t *
#endif
typedef struct {
int go_argc;
char** go_argv;
const char* go_shortopts;
const acc_getopt_longopt_p longopts;
#if (ACC_BROKEN_CDECL_ALT_SYNTAX)
int __acc_cdecl_va (*go_error)(const char *, ...);
#else
int (__acc_cdecl_va *go_error)(const char *, ...);
#endif
} acc_getopt_t;
#ifndef acc_getopt_p
#define acc_getopt_p acc_getopt_t *
#endif
ACCLIB_EXTERN(void, acc_getopt_init) (acc_getopt_p);
ACCLIB_EXTERN(int, acc_getopt) (acc_getopt_p);
ACCLIB_EXTERN(void, acc_getopt_close)(acc_getopt_p);
/*************************************************************************
// rand
**************************************************************************/
typedef struct { /* all private */
acc_uint32l_t seed;
} acc_rand31_t;
#ifndef acc_rand31_p
#define acc_rand31_p acc_rand31_t *
#endif
ACCLIB_EXTERN(void, acc_srand31) (acc_rand31_p, acc_uint32l_t);
ACCLIB_EXTERN(acc_uint32l_t, acc_rand31) (acc_rand31_p);
#if defined(acc_uint64l_t)
typedef struct { /* all private */
acc_uint64l_t seed;
} acc_rand48_t;
#ifndef acc_rand48_p
#define acc_rand48_p acc_rand48_t *
#endif
ACCLIB_EXTERN(void, acc_srand48) (acc_rand48_p, acc_uint32l_t);
ACCLIB_EXTERN(acc_uint32l_t, acc_rand48) (acc_rand48_p);
ACCLIB_EXTERN(acc_uint32l_t, acc_rand48_r32) (acc_rand48_p);
#endif
#if defined(acc_uint64l_t)
typedef struct { /* all private */
acc_uint64l_t seed;
} acc_rand64_t;
#ifndef acc_rand64_p
#define acc_rand64_p acc_rand64_t *
#endif
ACCLIB_EXTERN(void, acc_srand64) (acc_rand64_p, acc_uint64l_t);
ACCLIB_EXTERN(acc_uint32l_t, acc_rand64) (acc_rand64_p);
ACCLIB_EXTERN(acc_uint32l_t, acc_rand64_r32) (acc_rand64_p);
#endif
typedef struct { /* all private */
unsigned n;
acc_uint32l_t s[624];
} acc_randmt_t;
#ifndef acc_randmt_p
#define acc_randmt_p acc_randmt_t *
#endif
ACCLIB_EXTERN(void, acc_srandmt) (acc_randmt_p, acc_uint32l_t);
ACCLIB_EXTERN(acc_uint32l_t, acc_randmt) (acc_randmt_p);
ACCLIB_EXTERN(acc_uint32l_t, acc_randmt_r32) (acc_randmt_p);
#endif /* already included */
/*
vi:ts=4:et
*/
|
bstasyszyn/fabric-peer-ext
|
pkg/peer/init_test.go
|
<reponame>bstasyszyn/fabric-peer-ext
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package peer
import (
"os"
"testing"
"github.com/hyperledger/fabric/extensions/collections/storeprovider"
"github.com/hyperledger/fabric/extensions/gossip/blockpublisher"
"github.com/stretchr/testify/require"
extconfig "github.com/trustbloc/fabric-peer-ext/pkg/config"
statemocks "github.com/trustbloc/fabric-peer-ext/pkg/gossip/state/mocks"
"github.com/trustbloc/fabric-peer-ext/pkg/mocks"
"github.com/trustbloc/fabric-peer-ext/pkg/resource"
)
func TestInitialize(t *testing.T) {
defer removeDBPath(t)
// Ensure that the provider instances are instantiated and registered as a resource
require.NotNil(t, blockpublisher.ProviderInstance)
require.NotNil(t, storeprovider.NewProviderFactory())
require.NotPanics(t, Initialize)
require.NoError(t, resource.Mgr.Initialize(
&mocks.LedgerProvider{},
&mocks.GossipProvider{},
&mocks.IdentityDeserializerProvider{},
&mocks.IdentifierProvider{},
&mocks.IdentityProvider{},
&statemocks.CCEventMgrProvider{},
))
}
func removeDBPath(t testing.TB) {
removePath(t, extconfig.GetTransientDataLevelDBPath())
}
func removePath(t testing.TB, path string) {
if err := os.RemoveAll(path); err != nil {
t.Fatalf(err.Error())
}
}
|
liuboshuo/LSDevelopmentIOS
|
DevelopmentIOS/Common/Utils/PopMenuView/PopMenuViewTableViewDelegate.h
|
//
// PopMenuViewTableViewDelegate.h
// TestPopView
//
// Created by 刘硕 on 16/4/18.
// Copyright © 2016年 刘硕. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "PopMenuView.h"
#import "PopMenuTableViewCell.h"
#define kNumber 6
#define kPopCellHeight 40
typedef void(^tableViewDidSelectAtIndexPath)(NSIndexPath *indexPath);
@interface PopMenuViewTableViewDelegate : NSObject<UITableViewDelegate>
/**
* 对 cell 代理初始化
*/
- (instancetype) initWithDidSelectRowAtIndexPath:(tableViewDidSelectAtIndexPath)tableViewDidSelectRowAtIndexPath;
@end
|
johnkerl/scripts-math
|
pythonlib/bin/rube_misc_tests.py
|
<filename>pythonlib/bin/rube_misc_tests.py
#!/usr/bin/python -Wall
# ================================================================
# Copyright (c) <NAME> 2007
# <EMAIL>
# ================================================================
from rube_m import *
# ----------------------------------------------------------------
def rube_test_1():
print piece_equal('UFR', 'FRU')
print piece_equal('FUR', 'FUR')
print piece_equal('FUR', 'FU')
print
print move_on_face('U+', 'F')
print move_on_corner_piece('F', 'URF')
print move_on_corner_piece('F', 'URL')
print moves_on_piece(['U', 'F', 'R'], 'UFR')
print
print moves_on_piece(['F', 'F', 'F', 'F'], 'UFR')
print moves_on_piece(['F'], 'UFR')
print moves_on_piece(['F'], 'UF')
print
print moves_on_pieces(['F'], ['UFR', 'UF'])
print moves_on_pieces(['F', 'F'], ['UFR', 'UF'])
print moves_on_pieces(['F', 'F', 'F'], ['UFR', 'UF'])
print moves_on_pieces(['F', 'F', 'F', 'F'], ['UFR', 'UF'])
print
print "<<", sign_of_rotation('UFR', 'UFL'), ">>"
print "<<", sign_of_rotation('UFR', 'UFR'), ">>"
print "<<", sign_of_rotation('UFR', 'URF'), ">>"
print "<<", sign_of_rotation('FUR', 'FRU'), ">>"
print "<<", sign_of_rotation('UFR', 'UR'), ">>"
print
print "FIND CYCLE:"
print find_cycle(['U', 'L'], 'UFR')
print
print "FIND CYCLES:"
print find_cycles(['U'], ['UFR', 'UFL', 'DFR', 'DFL'])
print find_cycles(['U', 'L'], ['UFR', 'UFL'])
print find_cycles(['F', 'R', 'B', 'L'], ['UF', 'UL', 'UFR', 'UFL'])
print
print "DELETE 1-CYCLES:"
print delete_1_cycles(find_cycles(['U'], ['UFR', 'UFL', 'DFR', 'DFL']))
print delete_1_cycles(find_cycles(['U', 'L'], ['UFR', 'UFL']))
print delete_1_cycles(find_cycles(['F', 'R', 'B', 'L'], ['UF', 'UL', 'UFR', 'UFL']))
print
print "CYCLE DECOMPOSITION:"
print cycle_decomposition(["F"])
print cycle_decomposition(["F", "R"])
print cycle_decomposition(["F", "R", "B", "L"])
print cycle_decomposition(["F2", "R2"])
print cycle_decomposition(["F2"])
print cycle_decomposition(["F2", "B2"])
print
print "PRINT CYCLE DECOMPOSITION:"
print_cycle_decomposition(["F"])
print_cycle_decomposition(["F", "R"])
print_cycle_decomposition(["F", "R", "B", "L"])
print_cycle_decomposition(["F2", "R2"])
print_cycle_decomposition(["F2"])
print_cycle_decomposition(["F2", "B2"])
print
print "IMAGES:"
print images_of_all_pieces(["F"])
print images_of_all_pieces(["F", "R"])
print images_of_all_pieces(["F", "R", "B", "L"])
print images_of_all_pieces(["F2", "R2"])
print images_of_all_pieces(["F2"])
print images_of_all_pieces(["F2", "B2"])
bot_tri_rot = ["L-", "R+", "F+", "L+", "R-", "D2", "L-", "R+", "F+", "L+", "R-" ]
print images_of_all_pieces(bot_tri_rot)
print
print "ORDERS:"
print order(["F"])
print order(["F", "R"])
print order(["F", "R", "B", "L"])
print order(["F2", "R2"])
print order(["F2"])
print order(["F2", "B2"])
bot_tri_rot = ["L-", "R+", "F+", "L+", "R-", "D2", "L-", "R+", "F+", "L+", "R-" ]
print order(bot_tri_rot)
print
rube_test_1()
|
impedimentToProgress/UCI-BlueChip
|
snapgear_linux/user/pppd/pppd/plugins/librad.c
|
/*
* librad.c - RADIUS protocol library.
*
* (C) Copyright 2001-2002, <NAME> (<EMAIL>)
* (C) Copyright 2001, Lineo Inc. (www.lineo.com)
* (C) Copyright 2002, SnapGear (www.snapgear.com)
*/
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <md5.h>
#include <magic.h>
#include "radius.h"
#include "librad.h"
#define RESEND_TIMEOUT 3
#define RESEND_COUNT 10
#define RADIUS_ID_FILE "/var/log/radius.id"
#define RADIUS_SESSIONID_FILE "/var/log/radius.sessionid"
static u_char
radius_id(void)
{
int fd, n;
u_char id;
fd = open(RADIUS_ID_FILE, O_RDWR|O_CREAT, 0644);
if (fd < 0) {
syslog(LOG_ERR, "RADIUS: open %s failed: %m", RADIUS_ID_FILE);
return magic();
}
if (flock(fd, LOCK_EX) != 0) {
syslog(LOG_ERR, "RADIUS: flock %s failed: %m", RADIUS_ID_FILE);
}
n = read(fd, &id, 1);
if (n < 1) {
id = magic();
} else {
id++;
}
lseek(fd, 0L, SEEK_SET);
write(fd, &id, 1);
flock(fd, LOCK_UN);
close(fd);
return id;
}
u_int
radius_sessionid(void)
{
int fd, n;
u_char sessionid;
fd = open(RADIUS_SESSIONID_FILE, O_RDWR|O_CREAT, 0644);
if (fd < 0) {
syslog(LOG_ERR, "RADIUS: open %s failed: %m", RADIUS_SESSIONID_FILE);
return magic();
}
if (flock(fd, LOCK_EX) != 0) {
syslog(LOG_ERR, "RADIUS: flock %s failed: %m", RADIUS_SESSIONID_FILE);
}
n = read(fd, &sessionid, sizeof(sessionid));
if (n < sizeof(sessionid)) {
sessionid = magic();
} else {
sessionid++;
}
lseek(fd, 0L, SEEK_SET);
write(fd, &sessionid, sizeof(sessionid));
flock(fd, LOCK_UN);
close(fd);
return sessionid;
}
/* If string is NULL, a 'value' attrib is added,
* otherwise a 'string' attrib is added. */
struct radius_attrib *
radius_add_attrib(
struct radius_attrib **list, u_long vendor, u_char type,
u_int value, char *string, u_int length)
{
struct radius_attrib *attrib, **p;
attrib = (struct radius_attrib*)malloc(sizeof(*attrib));
if (attrib == NULL) {
syslog(LOG_ERR, "RADIUS: out of memory for attribute");
return NULL;
}
attrib->type = type;
attrib->next = NULL;
if (string != NULL) {
attrib->length = length;
if (attrib->length > AUTH_STRING_LEN) {
attrib->length = AUTH_STRING_LEN;
}
memcpy(attrib->u.string, string, attrib->length);
attrib->u.string[attrib->length] = '\0';
}
else {
attrib->length = sizeof(attrib->u.value);
attrib->u.value = htonl(value);
}
attrib->vendor = vendor;
for (p = list; *p != NULL; p = &((*p)->next));
*p = attrib;
return attrib;
}
void
radius_free_attrib(struct radius_attrib *list)
{
struct radius_attrib *p;
while (list != NULL) {
p = list->next;
free(list);
list = p;
}
}
static void
radius_random_vector(u_char *vector, int length)
{
u_int i;
while (length > 0) {
i = magic();
memcpy(vector, &i, (length<sizeof(i)) ? length : sizeof(i));
vector += sizeof(i);
length -= sizeof(i);
}
}
static void
radius_calc_vector(
char *secret, u_char *buf, int len,
u_char *vector_in, u_char *vector_out)
{
int header_len;
int secret_len;
MD5_CTX context;
header_len = ((AUTH_HDR*)buf)->vector - buf;
secret_len = strlen(secret);
MD5Init(&context);
MD5Update(&context, buf, header_len);
MD5Update(&context, vector_in, AUTH_VECTOR_LEN);
MD5Update(&context, buf + header_len + AUTH_VECTOR_LEN,
len - header_len - AUTH_VECTOR_LEN);
MD5Update(&context, secret, secret_len);
MD5Final(vector_out, &context);
}
static void
radius_encrypt_attrib(
char *secret, u_char *vector,
u_char *to, u_char *from, int length,
u_char *salt, int salt_length)
{
int secret_len;
int i;
MD5_CTX context;
secret_len = strlen(secret);
while (length > 0) {
MD5Init(&context);
MD5Update(&context, secret, secret_len);
MD5Update(&context, vector, AUTH_VECTOR_LEN);
if (salt && salt_length) {
MD5Update(&context, salt, salt_length);
salt = NULL;
}
MD5Final(to, &context);
for (i=0; i<AUTH_VECTOR_LEN && length>0; i++, length--) {
to[i] ^= from[i];
}
vector = to;
to += AUTH_VECTOR_LEN;
from += AUTH_VECTOR_LEN;
}
}
static void
radius_decrypt_attrib(
char *secret, u_char *vector,
u_char *to, u_char *from, int length,
u_char *salt, int salt_length)
{
int secret_len;
int i;
MD5_CTX context;
secret_len = strlen(secret);
while (length > 0) {
MD5Init(&context);
MD5Update(&context, secret, secret_len);
MD5Update(&context, vector, AUTH_VECTOR_LEN);
if (salt && salt_length) {
MD5Update(&context, salt, salt_length);
salt = NULL;
}
MD5Final(to, &context);
for (i=0; i<AUTH_VECTOR_LEN && length>0; i++, length--) {
to[i] ^= from[i];
}
vector = from;
to += AUTH_VECTOR_LEN;
from += AUTH_VECTOR_LEN;
}
}
/* Returns: encryption salt length, or -1 for no encryption */
static int
radius_attrib_salt_length(struct radius_attrib *attrib)
{
int encrypt = -1;
if (attrib->vendor == PW_VENDOR_NONE) {
switch (attrib->type) {
case PW_PASSWORD:
encrypt = 0;
break;
}
}
else if (attrib->vendor == PW_VENDOR_MICROSOFT) {
switch (attrib->type) {
case PW_MS_CHAP_MPPE_KEYS:
encrypt = 0;
break;
case PW_MS_MPPE_SEND_KEY:
case PW_MS_MPPE_RECV_KEY:
encrypt = 2;
break;
}
}
if (encrypt > attrib->length)
encrypt = -1;
return encrypt;
}
#define RADIUS_ENCRYPT_ATTRIB_LEN(l) \
(((l) + AUTH_VECTOR_LEN - 1) & ~(AUTH_VECTOR_LEN-1))
static int
radius_attrib_length(struct radius_attrib *attrib)
{
int length, salt;
length = 2;
salt = radius_attrib_salt_length(attrib);
if (salt >= 0)
length += salt + RADIUS_ENCRYPT_ATTRIB_LEN(attrib->length - salt);
else
length += attrib->length;
if (attrib->vendor != PW_VENDOR_NONE)
length += 2 + sizeof(attrib->vendor);
return length;
}
/* Return: success: 0, error: -1 */
static int
radius_get_attrib_vendor(struct radius_attrib ***next, u_long vendor,
u_char *buf, int len, char *secret, u_char *vector)
{
u_char from_type, from_length;
u_long from_vendor;
struct radius_attrib *attrib;
int salt;
while (len >= 2) {
from_type = *buf++;
from_length = *buf++;
if (from_length < 2 || from_length > len) {
syslog(LOG_ERR, "RADIUS: received attribute with invalid length");
return -1;
}
len -= from_length;
from_length -= 2;
if (from_type == PW_VENDOR_SPECIFIC && vendor == PW_VENDOR_NONE) {
if (from_length < sizeof(from_vendor)) {
syslog(LOG_ERR, "RADIUS: received attribute with invalid length");
return -1;
}
memcpy(&from_vendor, buf, sizeof(from_vendor));
from_vendor = ntohl(from_vendor);
buf += sizeof(from_vendor);
from_length -= sizeof(from_vendor);
if (radius_get_attrib_vendor(
next, from_vendor, buf, from_length, secret, vector) < 0)
return -1;
}
else {
attrib = (struct radius_attrib*)malloc(sizeof(*attrib));
if (attrib == NULL) {
syslog(LOG_ERR, "RADIUS: out of memory for attribute");
return -1;
}
attrib->vendor = vendor;
attrib->type = from_type;
attrib->length = from_length;
salt = radius_attrib_salt_length(attrib);
if (salt >= 0) {
memcpy(attrib->u.string, buf, salt);
radius_decrypt_attrib(secret, vector, attrib->u.string+salt,
buf+salt, attrib->length-salt,
buf, salt);
}
else {
memcpy(attrib->u.string, buf, attrib->length);
}
attrib->u.string[attrib->length] = '\0';
attrib->next = NULL;
**next = attrib;
*next = &attrib->next;
}
buf += from_length;
}
return 0;
}
/* Return: success: 0, error: -1 */
static int
radius_get_attrib(struct radius_attrib **list, u_char *buf, int len,
char *secret, u_char *vector)
{
struct radius_attrib **next;
next = list;
*next = NULL;
if (radius_get_attrib_vendor(&next, PW_VENDOR_NONE, buf, len,
secret, vector) < 0) {
radius_free_attrib(*list);
*list = NULL;
return -1;
}
return 0;
}
/* Return: success: length, error: -1 */
static int
radius_put_attrib(u_char *buf, struct radius_attrib *attrib,
char *secret, u_char *vector)
{
int length, total, salt;
u_long vendor;
total = length = radius_attrib_length(attrib);
if (attrib->vendor != PW_VENDOR_NONE) {
*buf++ = PW_VENDOR_SPECIFIC;
*buf++ = total;
vendor = htonl(attrib->vendor);
memcpy(buf, &vendor, sizeof(vendor));
buf += sizeof(vendor);
length -= 2 + sizeof(vendor);
}
*buf++ = attrib->type;
*buf++ = length;
salt = radius_attrib_salt_length(attrib);
if (salt >= 0) {
if (secret == NULL || vector == NULL) {
syslog(LOG_ERR, "RADIUS: no vector to encrypt attribute");
return -1;
}
memcpy(buf, attrib->u.string, salt);
radius_encrypt_attrib(secret, vector, buf+salt,
attrib->u.string+salt, attrib->length-salt,
attrib->u.string, salt);
}
else {
memcpy(buf, attrib->u.string, attrib->length);
}
return total;
}
/* Return: success: length, fatal error: -1, error: 0 */
static int
radius_recv(int s, char *secret, u_char *sendbuf,
u_char *recvbuf, int maxrecvlen, struct sockaddr_in *saremote)
{
struct sockaddr_in safrom;
int recvlen, fromlen;
u_char vector[AUTH_VECTOR_LEN];
AUTH_HDR *sendheader, *recvheader;
sendheader = (AUTH_HDR*)sendbuf;
recvheader = (AUTH_HDR*)recvbuf;
fromlen = sizeof(safrom);
recvlen = recvfrom(s, recvbuf, maxrecvlen, 0,
(struct sockaddr*)&safrom, &fromlen);
if (recvlen < 0) {
syslog(LOG_ERR, "RADIUS: recvfrom: %m");
return -1;
}
if (safrom.sin_addr.s_addr != saremote->sin_addr.s_addr) {
syslog(LOG_WARNING, "RADIUS: received unexpected packet from server %s", inet_ntoa(safrom.sin_addr));
return 0;
}
if (recvlen == 0) {
syslog(LOG_WARNING, "RADIUS: received zero length packet from server %s", inet_ntoa(safrom.sin_addr));
return 0;
}
if (recvlen < ntohs(recvheader->length)) {
syslog(LOG_WARNING, "RADIUS: received packet with invalid length from server %s", inet_ntoa(safrom.sin_addr));
return 0;
}
recvlen = ntohs(recvheader->length);
if ((sendheader->code == PW_AUTHENTICATION_REQUEST
&& recvheader->code != PW_AUTHENTICATION_ACK
&& recvheader->code != PW_AUTHENTICATION_REJECT
&& recvheader->code != PW_ACCESS_CHALLENGE)
|| (sendheader->code == PW_ACCOUNTING_REQUEST
&& recvheader->code != PW_ACCOUNTING_RESPONSE)) {
syslog(LOG_WARNING, "RADIUS: received unexpected packet with code %d from server %s", recvheader->code, inet_ntoa(safrom.sin_addr));
return 0;
}
if (sendheader->id != recvheader->id) {
syslog(LOG_WARNING, "RADIUS: received packet with mismatched id from server %s", inet_ntoa(safrom.sin_addr));
return 0;
}
radius_calc_vector(secret, recvbuf, recvlen,
((AUTH_HDR*)sendbuf)->vector, vector);
if (memcmp(((AUTH_HDR*)recvbuf)->vector, vector,
AUTH_VECTOR_LEN) != 0) {
syslog(LOG_WARNING, "RADIUS: received packet with invalid authenticator from server %s", inet_ntoa(safrom.sin_addr));
return 0;
}
return recvlen;
}
/* Send with timeouts/retries */
/* Return: success: length, error: -1 */
static int
radius_send(
u_long host, int port, char *secret,
u_char *sendbuf, int sendlen, u_char *recvbuf, int maxrecvlen)
{
int s;
struct sockaddr_in salocal, saremote;
fd_set set;
struct timeval timeout;
int ret, recvlen, sendcount;
s = socket(PF_INET, SOCK_DGRAM, 0);
if (s < 0) {
syslog(LOG_ERR, "RADIUS: open socket failed: %m");
return -1;
}
memset(&salocal, 0, sizeof(salocal));
salocal.sin_family = AF_INET;
salocal.sin_addr.s_addr = htonl(INADDR_ANY);
salocal.sin_port = 0;
if (bind(s, (struct sockaddr*)&salocal, sizeof(salocal)) < 0) {
syslog(LOG_ERR, "RADIUS: bind socket failed: %m");
close(s);
return -1;
}
memset(&saremote, 0, sizeof(saremote));
saremote.sin_family = AF_INET;
saremote.sin_addr.s_addr = htonl(host);
saremote.sin_port = htons(port);
if (sendto(s, sendbuf, sendlen, 0,
(struct sockaddr*)&saremote, sizeof(saremote)) < 0) {
syslog(LOG_ERR, "RADIUS: sendto failed: %m");
close(s);
return -1;
}
sendcount = 1;
while (sendcount < 10) {
FD_ZERO(&set);
FD_SET(s, &set);
timeout.tv_sec = RESEND_TIMEOUT;
timeout.tv_usec = 0;
ret = select(s+1, &set, NULL, NULL, &timeout);
if (ret < 0) {
syslog(LOG_ERR, "RADIUS: select failed: %m");
close(s);
return -1;
}
if (ret == 0) {
/* Timed out so resend */
if (sendcount > 3) {
syslog(LOG_WARNING, "RADIUS: server %s not responding",
inet_ntoa(saremote.sin_addr));
}
if (sendto(s, sendbuf, sendlen, 0,
(struct sockaddr*)&saremote, sizeof(saremote)) < 0) {
syslog(LOG_ERR, "RADIUS: sendto failed: %m");
close(s);
return -1;
}
sendcount++;
}
else if (FD_ISSET(s, &set)) {
recvlen = radius_recv(s, secret, sendbuf,
recvbuf, maxrecvlen, &saremote);
if (recvlen != 0) { /* either -1 , or positive */
close(s);
return recvlen;
}
}
}
close(s);
syslog(LOG_ERR, "RADIUS: maximum retries reached for server %s",
inet_ntoa(saremote.sin_addr));
return -1;
}
int
radius_send_access_request(
u_long host, int port, char *secret,
struct radius_attrib *attriblist,struct radius_attrib **recvattriblist)
{
struct radius_attrib *attrib;
int attriblen, sendlen, recvlen;
u_char *sendbuf, *p;
u_char recvbuf[1024];
AUTH_HDR *header;
attriblen = 0;
for (attrib = attriblist; attrib != NULL; attrib = attrib->next)
attriblen += radius_attrib_length(attrib);
sendlen = AUTH_HDR_LEN + attriblen;
sendbuf = (u_char*)malloc(sendlen);
if (sendbuf == NULL) {
syslog(LOG_ERR, "RADIUS: out of memory for access request");
return -1;
}
header = (AUTH_HDR*)sendbuf;
header->code = PW_AUTHENTICATION_REQUEST;
header->id = radius_id();
header->length = htons(sendlen);
radius_random_vector(header->vector, sizeof(header->vector));
p = sendbuf + AUTH_HDR_LEN;
for (attrib = attriblist; attrib != NULL; attrib = attrib->next) {
attriblen = radius_put_attrib(p, attrib, secret, header->vector);
if (attriblen < 0) {
free(sendbuf);
return -1;
}
p += attriblen;
}
recvlen = radius_send(host, port, secret, sendbuf, sendlen,
recvbuf, sizeof(recvbuf));
if (recvlen <= 0) {
free(sendbuf);
return -1;
}
if (radius_get_attrib(recvattriblist,
recvbuf + AUTH_HDR_LEN, recvlen - AUTH_HDR_LEN,
secret, header->vector) < 0) {
free(sendbuf);
return -1;
}
free(sendbuf);
return ((AUTH_HDR*)recvbuf)->code;
}
int
radius_send_account_request(
u_long host, int port, char *secret,
struct radius_attrib *attriblist,struct radius_attrib **recvattriblist)
{
struct radius_attrib *attrib;
int attriblen, sendlen, recvlen;
u_char *sendbuf, *p;
u_char recvbuf[1024];
AUTH_HDR *header;
attriblen = 0;
for (attrib = attriblist; attrib != NULL; attrib = attrib->next)
attriblen += radius_attrib_length(attrib);
sendlen = AUTH_HDR_LEN + attriblen;
sendbuf = (u_char*)malloc(sendlen);
if (sendbuf == NULL) {
syslog(LOG_ERR, "RADIUS: out of memory for account request");
return -1;
}
header = (AUTH_HDR*)sendbuf;
header->code = PW_ACCOUNTING_REQUEST;
header->id = radius_id();
header->length = htons(sendlen);
memset(header->vector, 0, AUTH_VECTOR_LEN);
p = sendbuf + AUTH_HDR_LEN;
for (attrib = attriblist; attrib != NULL; attrib = attrib->next) {
attriblen = radius_put_attrib(p, attrib, secret, NULL);
if (attriblen < 0) {
free(sendbuf);
return -1;
}
p += attriblen;
}
radius_calc_vector(secret, sendbuf, sendlen,
((AUTH_HDR*)sendbuf)->vector, ((AUTH_HDR*)sendbuf)->vector);
recvlen = radius_send(host, port, secret, sendbuf, sendlen,
recvbuf, sizeof(recvbuf));
free(sendbuf);
if (recvlen <= 0) {
return -1;
}
if (radius_get_attrib(recvattriblist,
recvbuf + AUTH_HDR_LEN, recvlen - AUTH_HDR_LEN,
secret, NULL) < 0) {
return -1;
}
return ((AUTH_HDR*)recvbuf)->code;
}
|
rh101/engine-x
|
core/renderer/CCMeshCommand.h
|
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
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.
****************************************************************************/
#pragma once
#include <unordered_map>
#include "renderer/CCRenderCommand.h"
#include "renderer/CCRenderState.h"
#include "renderer/backend/ProgramState.h"
#include "renderer/backend/Types.h"
#include "renderer/CCCustomCommand.h"
#include "math/CCMath.h"
NS_CC_BEGIN
class GLProgramState;
class EventListenerCustom;
class EventCustom;
class Material;
// it is a common mesh
class CC_DLL MeshCommand : public CustomCommand
{
public:
// using PrimitiveType = backend::PrimitiveType;
/**
Buffer usage of vertex/index buffer. If the contents is not updated every frame,
then use STATIC, other use DYNAMIC.
*/
using BufferUsage = backend::BufferUsage;
/**
The index format determine the size for index data. U_SHORT is enough for most
cases.
*/
using IndexFormat = backend::IndexFormat;
MeshCommand();
virtual ~MeshCommand();
MeshCommand(const MeshCommand&) = default;
MeshCommand(MeshCommand&&) = default;
MeshCommand& operator=(MeshCommand&&) = default;
MeshCommand& operator=(const MeshCommand&) = default;
/**
Init function. The render command will be in 2D mode.
@param globalZOrder GlobalZOrder of the render command.
*/
void init(float globalZOrder);
void init(float globalZOrder, const Mat4& transform);
#if CC_ENABLE_CACHE_TEXTURE_DATA
void listenRendererRecreated(EventCustom* event);
#endif
protected:
#if CC_ENABLE_CACHE_TEXTURE_DATA
EventListenerCustom* _rendererRecreatedListener;
#endif
};
NS_CC_END
|
AnilKumarBejjanki/drools
|
kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/KnowledgeSourceCompiler.java
|
/*
* 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.kie.dmn.core.compiler;
import org.kie.dmn.core.impl.DMNModelImpl;
import org.kie.dmn.model.api.DRGElement;
import org.kie.dmn.model.api.KnowledgeSource;
public class KnowledgeSourceCompiler implements DRGElementCompiler {
@Override
public boolean accept(DRGElement de) {
return de instanceof KnowledgeSource;
}
@Override
public void compileNode(DRGElement de, DMNCompilerImpl compiler, DMNModelImpl model) {
// don't do anything as KnowledgeSource is a documentation element
// without runtime semantics
}
}
|
SMYALTAMASH/sunbird-learning-platform
|
platform-core/graph-engine/module/graph-common/src/main/java/org/sunbird/graph/common/BaseRequestRouter.java
|
package org.sunbird.graph.common;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.sunbird.common.Platform;
import org.sunbird.common.dto.Request;
import org.sunbird.common.dto.Response;
import org.sunbird.common.dto.ResponseParams;
import org.sunbird.common.dto.ResponseParams.StatusType;
import org.sunbird.common.exception.ClientException;
import org.sunbird.common.exception.MiddlewareException;
import org.sunbird.common.exception.ResourceNotFoundException;
import org.sunbird.common.exception.ResponseCode;
import org.sunbird.common.exception.ServerException;
import org.sunbird.graph.common.enums.GraphHeaderParams;
import org.sunbird.graph.common.exception.GraphEngineErrorCodes;
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
import akka.dispatch.OnFailure;
import akka.dispatch.OnSuccess;
import akka.pattern.Patterns;
import scala.concurrent.Future;
public abstract class BaseRequestRouter extends UntypedActor {
protected long timeout = Platform.config.hasPath("akka.request_timeout") ? (Platform.config.getLong("akka.request_timeout") * 1000): 30000;
private static final Logger perfLogger = LogManager.getLogger("PerformanceTestLogger");
protected abstract void initActorPool();
protected abstract ActorRef getActorFromPool(Request request);
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof String) {
if (StringUtils.equalsIgnoreCase("init", message.toString())) {
// initializes the actor pool for actors
initActorPool();
getSender().tell("initComplete", getSelf());
} else {
getSender().tell(message, getSelf());
}
} else if (message instanceof Request) {
// routes the incoming Request to API actor. All forward calls
// are "ask" calls and this actor throws an timeout exception after
// the configured timeout.
Request request = (Request) message;
long startTime = System.currentTimeMillis();
request.getContext().put(GraphHeaderParams.start_time.name(), startTime);
perfLogger.info(request.getContext().get(GraphHeaderParams.scenario_name.name()) + ","
+ request.getContext().get(GraphHeaderParams.request_id.name()) + "," + request.getManagerName() + ","
+ request.getOperation() + ",STARTTIME," + startTime);
ActorRef parent = getSender();
try {
ActorRef actorRef = getActorFromPool(request);
Future<Object> future = Patterns.ask(actorRef, request, timeout);
handleFuture(request, future, parent);
} catch (Exception e) {
handleException(request, e, parent);
}
} else if (message instanceof Response) {
// do nothing
} else {
unhandled(message);
}
}
protected void handleFuture(final Request request, Future<Object> future, final ActorRef parent) {
future.onSuccess(new OnSuccess<Object>() {
@Override
public void onSuccess(Object arg0) throws Throwable {
parent.tell(arg0, getSelf());
long endTime = System.currentTimeMillis();
long exeTime = endTime - (Long) request.getContext().get(GraphHeaderParams.start_time.name());
Response res = (Response) arg0;
ResponseParams params = res.getParams();
// PlatformLogger.log(request.getRequestId() + " | " + request.getManagerName() + "," + request.getOperation() + ", SUCCESS, " + params.toString());
perfLogger.info(request.getContext().get(GraphHeaderParams.scenario_name.name()) + ","
+ request.getContext().get(GraphHeaderParams.request_id.name()) + "," + request.getManagerName() + ","
+ request.getOperation() + ",ENDTIME," + endTime);
perfLogger.info(request.getContext().get(GraphHeaderParams.scenario_name.name()) + ","
+ request.getContext().get(GraphHeaderParams.request_id.name()) + "," + request.getManagerName() + ","
+ request.getOperation() + "," + params.getStatus() + "," + exeTime);
}
}, getContext().dispatcher());
future.onFailure(new OnFailure() {
@Override
public void onFailure(Throwable e) throws Throwable {
handleException(request, e, parent);
}
}, getContext().dispatcher());
}
protected void handleException(final Request request, Throwable e, final ActorRef parent) {
// PlatformLogger.log(request.getRequestId() + " | " + request.getManagerName() + "," + request.getOperation() , e.getMessage(), LoggerEnum.WARN.name());
Response response = new Response();
ResponseParams params = new ResponseParams();
params.setStatus(StatusType.failed.name());
if (e instanceof MiddlewareException) {
MiddlewareException mwException = (MiddlewareException) e;
params.setErr(mwException.getErrCode());
} else {
params.setErr(GraphEngineErrorCodes.ERR_SYSTEM_EXCEPTION.name());
}
params.setErrmsg(e.getMessage());
response.setParams(params);
setResponseCode(response, e);
parent.tell(response, getSelf());
long exeTime = System.currentTimeMillis() - (Long) request.getContext().get(GraphHeaderParams.start_time.name());
perfLogger.info(request.getContext().get(GraphHeaderParams.scenario_name.name()) + ","
+ request.getContext().get(GraphHeaderParams.request_id.name()) + "," + request.getManagerName() + ","
+ request.getOperation() + ",ERROR," + exeTime);
}
public static Map<String, Method> getMethodMap(Class<?> cls) {
if (null != cls) {
Map<String, Method> map = new HashMap<String, Method>();
Method[] methods = cls.getDeclaredMethods();
if (null != methods && methods.length > 0) {
for (Method method : methods) {
Class<?>[] parameters = method.getParameterTypes();
Class<?> returnType = method.getReturnType();
if (returnType.getCanonicalName() == "void") {
if (null != parameters && parameters.length == 1) {
if (StringUtils.equals(Request.class.getName(), parameters[0].getCanonicalName()))
map.put(method.getName(), method);
}
}
}
}
return map;
}
return null;
}
private void setResponseCode(Response res, Throwable e) {
if (e instanceof ClientException) {
res.setResponseCode(ResponseCode.CLIENT_ERROR);
} else if (e instanceof ServerException) {
res.setResponseCode(ResponseCode.SERVER_ERROR);
} else if (e instanceof ResourceNotFoundException) {
res.setResponseCode(ResponseCode.RESOURCE_NOT_FOUND);
} else {
res.setResponseCode(ResponseCode.SERVER_ERROR);
}
}
}
|
chozen2see/terria
|
node_modules/terriajs/dist/ReactViews/Custom/SOSChartCustomComponent.js
|
<reponame>chozen2see/terria<gh_stars>0
import createGuid from "terriajs-cesium/Source/Core/createGuid";
import CommonStrata from "../../Models/Definition/CommonStrata";
import ChartCustomComponent from "./ChartCustomComponent";
export default class SOSChartCustomComponent extends ChartCustomComponent {
constructor() {
super(...arguments);
this.constructShareableCatalogItem = async (id, context, sourceReference) => this.createItemReference(context.catalogItem);
}
get name() {
return "sos-chart";
}
get attributes() {
let attributes = super.attributes;
attributes.push("name");
return attributes;
}
constructCatalogItem(id, context, sourceReference) {
var _a;
return (_a = context.catalogItem) === null || _a === void 0 ? void 0 : _a.duplicateModel(createGuid());
}
setTraitsFromAttrs(item, attrs, sourceIndex) {
var _a, _b;
const featureOfInterestId = attrs.identifier;
const featureName = attrs.name;
const units = (_a = item.selectedObservable) === null || _a === void 0 ? void 0 : _a.units;
item.setTrait(CommonStrata.user, "showAsChart", true);
item.setTrait(CommonStrata.user, "name", featureName || item.name);
item.setTrait(CommonStrata.user, "chartFeatureOfInterestIdentifier", featureOfInterestId);
(_b = item
.addObject(CommonStrata.user, "columns", "values")) === null || _b === void 0 ? void 0 : _b.setTrait(CommonStrata.user, "units", units);
}
parseNodeAttrs(nodeAttrs) {
const parsed = super.parseNodeAttrs(nodeAttrs);
parsed.name = nodeAttrs["name"];
return parsed;
}
}
//# sourceMappingURL=SOSChartCustomComponent.js.map
|
strolch-li/strolch
|
li.strolch.privilege/src/main/java/li/strolch/privilege/handler/SimpleLdapPrivilegeHandler.java
|
<filename>li.strolch.privilege/src/main/java/li/strolch/privilege/handler/SimpleLdapPrivilegeHandler.java<gh_stars>1-10
package li.strolch.privilege.handler;
import static li.strolch.privilege.base.PrivilegeConstants.*;
import static li.strolch.utils.helper.StringHelper.isEmpty;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import java.util.*;
import li.strolch.privilege.helper.LdapHelper;
import li.strolch.privilege.policy.PrivilegePolicy;
import li.strolch.utils.dbc.DBC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleLdapPrivilegeHandler extends BaseLdapPrivilegeHandler {
protected static final Logger logger = LoggerFactory.getLogger(SimpleLdapPrivilegeHandler.class);
private Locale defaultLocale;
private String adminUsers;
private Map<String, Set<String>> rolesForLdapGroups;
private String organisation;
private String location;
private String realm;
@Override
public synchronized void initialize(Map<String, String> parameterMap, EncryptionHandler encryptionHandler,
PasswordStrengthHandler passwordStrengthHandler, PersistenceHandler persistenceHandler,
UserChallengeHandler userChallengeHandler, SingleSignOnHandler ssoHandler,
Map<String, Class<PrivilegePolicy>> policyMap) {
super.initialize(parameterMap, encryptionHandler, passwordStrengthHandler, persistenceHandler,
userChallengeHandler, ssoHandler, policyMap);
this.organisation = parameterMap.getOrDefault(ORGANISATION, "");
this.location = parameterMap.getOrDefault(LOCATION, "");
this.realm = parameterMap.getOrDefault(REALM, "");
this.defaultLocale = parameterMap.containsKey("defaultLocale") ?
Locale.forLanguageTag(parameterMap.get("defaultLocale")) :
Locale.getDefault();
this.adminUsers = parameterMap.get("adminUsers");
this.rolesForLdapGroups = getLdapGroupToRolesMappingFromConfig(parameterMap);
}
@Override
protected String getFirstName(String username, Attributes attrs) throws NamingException {
String value = getLdapString(attrs, "givenName");
return isEmpty(value) ? username : value;
}
@Override
protected String getLastName(String username, Attributes attrs) throws NamingException {
String value = getLdapString(attrs, "sn");
return isEmpty(value) ? username : value;
}
@Override
protected Map<String, String> buildProperties(String username, Attributes attrs, Set<String> ldapGroups,
Set<String> strolchRoles) throws NamingException {
Map<String, String> properties = new HashMap<>();
properties.put(ORGANISATION, this.organisation);
properties.put(LOCATION, this.location);
properties.put(REALM, this.realm);
return properties;
}
@Override
protected Locale getLocale(Attributes attrs) {
return this.defaultLocale;
}
@Override
protected Set<String> getLdapGroups(String username, Attributes attrs) throws NamingException {
Set<String> ldapGroups = LdapHelper.getLdapGroups(attrs);
logger.info("User " + username + " has LDAP Groups: ");
ldapGroups.forEach(s -> logger.info("- " + s));
return ldapGroups;
}
@Override
protected Set<String> mapToStrolchRoles(String username, Set<String> ldapGroups) {
Set<String> strolchRoles = new HashSet<>();
for (String ldapRole : ldapGroups) {
Set<String> foundStrolchRoles = this.rolesForLdapGroups.get(ldapRole);
if (foundStrolchRoles != null)
strolchRoles.addAll(foundStrolchRoles);
}
// see if this is an admin user
if (this.adminUsers.contains(username))
strolchRoles = this.rolesForLdapGroups.get("admin");
return strolchRoles;
}
private Map<String, Set<String>> getLdapGroupToRolesMappingFromConfig(Map<String, String> params) {
String rolesForLdapGroups = params.get("rolesForLdapGroups");
DBC.PRE.assertNotEmpty("No roles mapping for ldap directory groups defined (param: rolesForLdapGroups)",
rolesForLdapGroups);
// rolesForLdapGroups = admin=StrolchAdmin,UserPrivileges;user=UserPrivileges
String[] ldapGroupRoles = rolesForLdapGroups.split(";");
Map<String, Set<String>> result = new HashMap<>();
for (String ldapGroupRole : ldapGroupRoles) {
ldapGroupRole = ldapGroupRole.trim();
String[] splitGroupRoles = ldapGroupRole.split("=");
String ldapGroupName = splitGroupRoles[0];
String[] strolchRoles = splitGroupRoles[1].split(",");
Set<String> roleNames = new HashSet<>();
for (String strolchRole : strolchRoles) {
roleNames.add(strolchRole.trim());
}
result.put(ldapGroupName, roleNames);
}
return result;
}
}
|
jacktionary/ManekiNeko
|
ManekiNeko/Classes/Business/Task/Subviews/MNUserRedpackView.h
|
//
// MNUserRedpackView.h
// ManekiNeko
//
// Created by JackCheng on 16/2/24.
// Copyright © 2016年 HardTime. All rights reserved.
//
#import "MNBaseView.h"
@interface MNUserRedpackView : MNBaseView
@property (nonatomic, strong) void(^confirmRedPackCallBack)(NSString *invitedID, NSString *redpackAmount);
@end
|
xhh4215/ShopApp
|
hi-ui/src/main/java/com/example/hi/banner/core/HiBannerAdapter.java
|
package com.example.hi.banner.core;
import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import java.util.List;
/***
*
*/
public class HiBannerAdapter extends PagerAdapter {
private Context mContext;
private SparseArray<HiBannerViewHolder> mCacheViews = new SparseArray<>();
private IHiBanner.OnBannerClickListener onBannerClickListener;
private IBindAdapter adapter;
private List<? extends HiBannerMo> models;
/***
* 是否开启自动轮播
*/
private boolean mAutoPlay = true;
/***
* 非自动轮播情况是是否循环切换
*/
private boolean mLoop = true;
private int mLayoutResId = -1;
public HiBannerAdapter(Context context) {
this.mContext = context;
}
public void setBannerData(@NonNull List<? extends HiBannerMo> models) {
this.models = models;
//初始化数据
initCacheView();
notifyDataSetChanged();
}
public void setOnBannerClickListener(IHiBanner.OnBannerClickListener onBannerClickListener) {
this.onBannerClickListener = onBannerClickListener;
}
public void setBindAdapter(IBindAdapter adapter) {
this.adapter = adapter;
}
public void setLayoutResId(@LayoutRes int mLayoutResId) {
this.mLayoutResId = mLayoutResId;
}
public void setAutoPlay(boolean mAutoPlay) {
this.mAutoPlay = mAutoPlay;
}
public void setLoop(boolean mLoop) {
this.mLoop = mLoop;
}
@Override
public int getCount() {
//无限轮播的关键点
return mAutoPlay ? Integer.MAX_VALUE : (mLoop ? Integer.MAX_VALUE : getRealCount());
}
/***
* 获取初次显示的item的位置
* @return
*/
public int getFirstItem() {
return Integer.MAX_VALUE / 2 - (Integer.MAX_VALUE / 2) % getRealCount();
}
/***
* 获取真是的页面的数量
* @return
*/
public int getRealCount() {
return models == null ? 0 : models.size();
}
private void initCacheView() {
mCacheViews = new SparseArray<>();
for (int i = 0; i < models.size(); i++) {
HiBannerViewHolder viewHolder = new HiBannerAdapter.HiBannerViewHolder(createRootView(LayoutInflater.from(mContext), null));
mCacheViews.put(i, viewHolder);
}
}
private View createRootView(LayoutInflater layoutInflater, ViewGroup parent) {
if (mLayoutResId == -1) {
throw new IllegalArgumentException("you must be set layoutid first");
}
return layoutInflater.inflate(mLayoutResId, parent, false);
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
int realPosition = position;
if (getRealCount() > 0) {
realPosition = position % getRealCount();
}
HiBannerViewHolder viewHolder = mCacheViews.get(realPosition);
if (container.equals(viewHolder.rootView.getParent())) {
container.removeView(viewHolder.rootView);
}
//数据绑定
onBind(viewHolder, models.get(realPosition), realPosition);
if (viewHolder.rootView.getParent() != null) {
((ViewGroup) viewHolder.rootView.getParent()).removeView(viewHolder.rootView);
}
container.addView(viewHolder.rootView);
return viewHolder.rootView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
}
@Override
public int getItemPosition(@NonNull Object object) {
//让item每次都刷新
return POSITION_NONE;
}
protected void onBind(@NonNull final HiBannerAdapter.HiBannerViewHolder viewHolder, @NonNull final HiBannerMo mo, final int position) {
viewHolder.rootView.setOnClickListener(v -> {
if (onBannerClickListener != null) {
onBannerClickListener.onBannerClick(viewHolder, mo, position);
}
});
if (adapter != null) {
adapter.onBind(viewHolder, mo, position);
}
}
public static class HiBannerViewHolder {
private SparseArray<View> viewSparseArray;
View rootView;
public View getRootView() {
return rootView;
}
public HiBannerViewHolder(View rootView) {
this.rootView = rootView;
}
public <V extends View> V findViewById(int id) {
if (!(rootView instanceof ViewGroup)) {
return (V) rootView;
}
if (this.viewSparseArray == null) {
viewSparseArray = new SparseArray<>(1);
}
V childView = (V) viewSparseArray.get(id);
if (childView == null) {
childView = rootView.findViewById(id);
this.viewSparseArray.put(id, childView);
}
return childView;
}
}
}
|
dangilman/LenstronomyWrapper
|
lenstronomywrapper/Sampler/run.py
|
import os
from lenstronomywrapper.Sampler.utilities import *
from lenstronomywrapper.Utilities.misc import create_directory
from lenstronomywrapper.LensSystem.quad_lens import QuadLensSystem
from lenstronomywrapper.Utilities.data_util import approx_theta_E
import dill
from lenstronomywrapper.Utilities.parameter_util import kwargs_e1e2_to_polar, kwargs_gamma1gamma2_to_polar
from time import time
from lenstronomywrapper.Optimization.quad_optimization.hierarchical import HierarchicalOptimization
from lenstronomywrapper.Utilities.misc import write_lensdata
from pyHalo.preset_models import WDMGeneral, CDM
def run(job_index, chain_ID, output_path, path_to_folder,
test_mode=False):
t_start = time()
output_path += chain_ID + '/'
path_to_folder += chain_ID
if not os.path.exists(output_path):
print('creating directory '+ output_path)
create_directory(output_path)
if not os.path.exists(output_path):
create_directory(output_path)
keywords_master = load_keywords(path_to_folder, job_index)
if test_mode:
keywords_master['verbose'] = True
readout_path = output_path + 'chain_' + str(job_index) + '/'
if not os.path.exists(readout_path):
create_directory(readout_path)
readout_steps = keywords_master['readout_steps']
N_computed = 0
write_header = True
write_mode = 'w'
if os.path.exists(readout_path + 'fluxes.txt'):
fluxes_computed = np.loadtxt(readout_path + 'fluxes.txt')
N_computed = int(fluxes_computed.shape[0])
write_header = False
write_mode = 'a'
Nsamples = keywords_master['Nsamples']
n_run = Nsamples - N_computed
if n_run <= 0:
print('job index '+str(job_index) + ' finished.')
return
else:
print('running job index '+str(job_index) + ', '+str(n_run) + ' realizations remaining')
############ Extract and organize key word arguments ###############
prior_list_realization, \
prior_list_macromodel, \
prior_list_source, \
prior_list_cosmo = \
build_priors(keywords_master['params_to_vary'])
data_to_fit_init = LensedQuasar(keywords_master['x_image'], keywords_master['y_image'],
keywords_master['fluxes'])
write_lensdata(readout_path + 'lensdata.txt', data_to_fit_init.x,
data_to_fit_init.y, data_to_fit_init.m,
[0.] * 4)
theta_E_approx = approx_theta_E(data_to_fit_init.x, data_to_fit_init.y)
############################ EVERYTHING BELOW THIS IS SAMPLED IN A FOR LOOP ############################
kwargs_macro = []
initial_pso = True
kwargs_macro_ref = None
fluxes_computed = None
parameters_sampled = None
if 'save_best_realization' in keywords_master.keys():
assert 'fluxes' in keywords_master.keys(), "must specify target fluxes if saving best realizations"
save_best_realization = keywords_master['save_best_realization']
if os.path.exists(readout_path + 'best_realization'):
f = open(readout_path + 'best_realization', 'rb')
best_realization = dill.load(f)
f.close()
current_best_statistic = best_realization.statistic
print('starting from best statistic of: ', current_best_statistic)
else:
current_best_statistic = 1e+6
else:
save_best_realization = False
readout_best = False
counter = 0
while counter < n_run:
setup = simulation_setup(keywords_master, prior_list_realization, prior_list_cosmo,
prior_list_macromodel, prior_list_source, kwargs_macro_ref)
(kwargs_rendering,
realization_samples,
zlens,
zsource,
lens_source_sampled, \
macromodel,
macro_samples,
constrain_params,
source_samples,
data_to_fit, \
optimization_settings,
optimization_routine,
params_sampled) = setup
kwargs_rendering['cone_opening_angle'] = kwargs_rendering['opening_angle_factor'] * \
theta_E_approx
optimization_settings['initial_pso'] = initial_pso
assert 'routine' in keywords_master['keywords_optimizer'].keys()
if keywords_master['verbose']:
for key in params_sampled.keys():
print(key + ': ' + str(params_sampled[key]))
print('zlens', zlens)
print('zsource', zsource)
print('Einstein radius', theta_E_approx)
readout_macro = True
if 'preset_model' in keywords_master.keys():
if keywords_master['preset_model'] == 'WDMLovell2020':
realization_initial = WDMGeneral(zlens, zsource, **kwargs_rendering)
elif keywords_master['preset_model'] == 'CDM':
realization_initial = CDM(zlens, zsource, **kwargs_rendering)
else:
raise Exception('no other preset model recognized')
else:
raise Exception('must specify preset model')
lens_system = QuadLensSystem.shift_background_auto(data_to_fit, macromodel, zsource,
realization_initial, None, particle_swarm_init=True,
opt_routine=optimization_routine, constrain_params=constrain_params,
verbose=keywords_master['verbose'])
settings_class = keywords_master['keywords_optimizer']['settings_class']
if keywords_master['verbose']:
print('realization has '+str(len(realization_initial.halos))+' halos in total')
if 'check_bad_fit' in keywords_master.keys():
check_bad_fit = keywords_master['check_bad_fit']
else:
check_bad_fit = False
hierarchical_opt = HierarchicalOptimization(lens_system, settings_class=settings_class)
kwargs_lens_fit, lensModel_fit, _ = hierarchical_opt.optimize(
data_to_fit, optimization_routine, constrain_params, keywords_master['verbose'],
check_bad_fit=check_bad_fit)
if kwargs_lens_fit is None:
continue
if 'grid_axis_ratio' in keywords_master.keys():
grid_axis_ratio = keywords_master['grid_axis_ratio']
else:
grid_axis_ratio = 0.5
if 'grid_rmax' in keywords_master:
grid_rmax = keywords_master['grid_rmax']
else:
grid_rmax = None
if keywords_master['source_model'] == 'GAUSSIAN':
if 'fixed_aperture_size' not in keywords_master.keys():
keywords_master['fixed_aperture_size'] = False
magnification_function = lens_system.quasar_magnification
magnification_function_kwargs = {'x': data_to_fit.x, 'y': data_to_fit.y,
'source_fwhm_pc': source_samples['source_fwhm_pc'],
'lens_model': lensModel_fit, 'kwargs_lensmodel': kwargs_lens_fit, 'normed': True,
'grid_axis_ratio': grid_axis_ratio, 'grid_rmax': grid_rmax,
'grid_resolution_rescale': 3., 'source_light_model': 'SINGLE_GAUSSIAN'}
elif keywords_master['source_model'] == 'DOUBLE_GAUSSIAN':
magnification_function = lens_system.quasar_magnification
magnification_function_kwargs = {'x': data_to_fit.x, 'y': data_to_fit.y,
'source_fwhm_pc': source_samples['source_fwhm_pc'],
'lens_model': lensModel_fit, 'kwargs_lensmodel': kwargs_lens_fit,
'grid_axis_ratio': grid_axis_ratio, 'grid_rmax': grid_rmax,
'normed': True, 'grid_resolution_rescale': 2., 'source_model': 'DOUBLE_GAUSSIAN',
'dx': source_samples['dx'], 'dy': source_samples['dy'],
'amp_scale': source_samples['amp_scale'],
'size_scale': source_samples['size_scale']}
else:
raise Exception('source model '+str(keywords_master['source_model']) + ' not recognized')
flux_ratios_fit = magnification_function(**magnification_function_kwargs)
if test_mode:
if 'grid_rmax' in keywords_master.keys():
grid_rmax = keywords_master['grid_rmax']
else:
grid_rmax = None
if keywords_master['source_model'] == 'DOUBLE_GAUSSIAN':
kwargs_magnification_finite = {'dx': source_samples['dx'], 'dy': source_samples['dy'],
'amp_scale': source_samples['amp_scale'],
'size_scale': source_samples['size_scale']}
else:
kwargs_magnification_finite = {}
print('flux ratios: ', flux_ratios_fit)
print('flux ratios measured: ', np.array(keywords_master['fluxes']))
cols = ['k', 'r', 'm', 'g']
import matplotlib.pyplot as plt
for i in range(0, 4):
plt.scatter(data_to_fit.x[i], data_to_fit.y[i], color=cols[i], marker='+')
plt.annotate(flux_ratios_fit[i], color=cols[i], xy=(data_to_fit.x[i], data_to_fit.y[i]))
plt.annotate(np.array(keywords_master['fluxes'])[i], color=cols[i], xy=(data_to_fit.x[i], data_to_fit.y[i]-0.15))
plt.show()
lens_system.plot_images(data_to_fit.x, data_to_fit.y, source_samples['source_fwhm_pc'],
lensModel_fit,
kwargs_lens_fit,
grid_resolution=None,
grid_resolution_rescale=2,
grid_rmax=grid_rmax,
source_model=keywords_master['source_model'], **kwargs_magnification_finite)
a=input('continue')
flux_ratios_fit = np.round(flux_ratios_fit, 5)
kwargs_macro_ref = lens_system.macromodel.kwargs
if readout_macro:
comp1 = kwargs_e1e2_to_polar(lens_system.macromodel.components[0].kwargs[0])
comp2 = kwargs_gamma1gamma2_to_polar(lens_system.macromodel.components[0].kwargs[1])
kwargs_macro_new = {}
for key in comp1.keys():
kwargs_macro_new[key] = comp1[key]
for key in comp2.keys():
kwargs_macro_new[key] = comp2[key]
kwargs_macro.append(kwargs_macro_new)
if keywords_master['verbose']:
print('flux_ratios_fit:', flux_ratios_fit)
print('n remaining: ', keywords_master['Nsamples'] - (counter + 1))
header = ''
parameters = []
for name in params_sampled.keys():
header += name + ' '
parameters.append(params_sampled[name])
parameters = np.array(parameters)
if save_best_realization:
fluxes_measured = np.array(keywords_master['fluxes'])
df = flux_ratios_fit[1:]/flux_ratios_fit[0] - fluxes_measured[1:]/fluxes_measured[0]
new_statistic = np.sum(np.sqrt(df ** 2))
if test_mode or keywords_master['verbose']:
print('new statistic: ', new_statistic)
print('current best statistic: ', current_best_statistic)
if new_statistic < current_best_statistic:
readout_best = True
print('storing new realization...')
current_best_statistic = new_statistic
best_realization = SavedRealization(data_to_fit.x, data_to_fit.y, lensModel_fit,
kwargs_lens_fit, flux_ratios_fit,
new_statistic, parameters)
if fluxes_computed is None and parameters_sampled is None:
fluxes_computed = flux_ratios_fit
parameters_sampled = parameters
else:
fluxes_computed = np.vstack((fluxes_computed, flux_ratios_fit))
parameters_sampled = np.vstack((parameters_sampled, parameters))
readout_condition_1 = np.logical_and(fluxes_computed is not None, (counter+1) % readout_steps == 0)
readout_condition_2 = counter == n_run - 1
if readout_condition_1 or readout_condition_2:
t_end = time()
t_ellapsed = t_end - t_start
sampling_rate = fluxes_computed.shape[0] / t_ellapsed
readout(readout_path, kwargs_macro, fluxes_computed, parameters_sampled,
header, write_header, write_mode, sampling_rate, readout_macro)
fluxes_computed, parameters_sampled = None, None
kwargs_macro = []
write_mode = 'a'
write_header = False
t_start = time()
if save_best_realization and readout_best:
f = open(readout_path + 'best_realization', 'wb')
dill.dump(best_realization, f)
f.close()
counter += 1
return
class SavedRealization(object):
def __init__(self, image_x, image_y, lensmodel_instance, kwargs_lens_fit, fluxes_modeled,
statistic, params):
self.image_x, self.image_y = image_x, image_y
self.lensmodel = lensmodel_instance
self.kwargs = kwargs_lens_fit
self.fluxes_modeled = fluxes_modeled
self.statistic = statistic
self.params = params
|
felder/Tools
|
scripts/ucjeps/cspace-fims-integration/extractFromAuthority.py
|
<reponame>felder/Tools
import xml.etree.ElementTree as ET
import sys, csv, codecs
reload(sys)
sys.setdefaultencoding('utf-8')
if len(sys.argv) < 3:
print ""
print "reads a CSpace authority XML file and outputs CSIDs, displayNames, and refNames as a .csv file"
print ""
print "if a 3rd argument is present, it is assumed to be a list of displaynames to be used to filter the output"
print ""
print "if duplicate displaynames are seen this are output to stdout"
print ""
print "usage: python %s <authorityfile.xml> <outputfile.csv> <optionallistofname.txt > listofdups.txt" % sys.argv[0]
print ""
print "e.g: python %s organization.xml organization.csv orgnames_to_extract.txt > listofdups.txt" % sys.argv[0]
print ""
print "columns are: sequence numbder, csid, displayname, refname"
print ""
exit(1)
def extract_tag(xml, tag):
element = xml.find('.//%s' % tag)
return element.text
xData = []
try:
cspaceXML = ET.parse(sys.argv[1])
root = cspaceXML.getroot()
items = cspaceXML.findall('.//list-item')
for i in items:
csid = i.find('.//csid')
csid = csid.text
try:
termDisplayName = extract_tag(i, 'termDisplayName')
refName = extract_tag(i, 'refName')
updated_at = extract_tag(i, 'updatedAt')
except:
print 'could not get termDisplayName or refName or updatedAt from %s' % csid
continue
xData.append([csid, termDisplayName, refName, updated_at])
del items, root, cspaceXML
except:
raise
for row in csv.reader(codecs.open(sys.argv[1], 'r', "utf-8"), delimiter='\t'):
# csid displayname refname noauthorname majorgroup
xData.append([row[0], row[1], row[2], 'n.d.'])
cspaceCSV = csv.writer(codecs.open(sys.argv[2], 'w', "utf-8"), delimiter='\t')
entities = {}
numberofitems = len(xData)
# if numberofitems > numberWanted:
# items = items[:numberWanted]
if len(sys.argv) >= 4:
file_of_names2check = csv.reader(codecs.open(sys.argv[3], 'r', "utf-8"), delimiter='\t')
names2check = [line[0].strip() for line in file_of_names2check]
check_names = True
else:
check_names = False
name_dict = {}
for sequence_number, i in enumerate(xData):
[csid, termDisplayName, refName, updated_at] = i
# if we were given a specific list of names, only write those ones out
if check_names:
if termDisplayName not in names2check:
continue
else:
pass
if termDisplayName in name_dict:
print '%s (%s) already seen as %s' % (termDisplayName, refName, name_dict[termDisplayName])
else:
name_dict[termDisplayName] = refName
cspaceCSV.writerow([sequence_number, csid, termDisplayName, refName, updated_at])
|
Sollertix/PnP
|
Samples/OfficeGraph.Demo.App/OfficeGraph.Demo.App/Scripts/App.js
|
<filename>Samples/OfficeGraph.Demo.App/OfficeGraph.Demo.App/Scripts/App.js
'use strict';
(function ($) {
$(document).ready(loadEverything);
function loadEverything() {
var isDialog = getQueryStringParameterByName('IsDlg');
if (isDialog == '1') {
$("#globalNavBox").hide();
}
var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?Querytext='*'" +
"&Properties='GraphQuery:ACTOR(ME\\, action\\:1019),GraphRankingModel:{\"features\"\\:[{\"function\"\\:\"EdgeWeight\"}]}'" +
"&RankingModelId='0c77ded8-c3ef-466d-929d-905670ea1d72'" +
"&SelectProperties='Title,UserName,Path'" +
"&RowLimit=10";
$.ajax({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=nometadata" },
success: function (data) {
var results = [];
$(data.PrimaryQueryResult.RelevantResults.Table.Rows).each(function (i, e) {
var o = {};
$(e.Cells).each(function (ii, ee) {
if (ee.Key == 'Title')
o.title = ee.Value;
else if (ee.Key == 'UserName')
o.username = ee.Value;
else if (ee.Key == 'Path')
o.path = ee.Value;
});
//build an image
o.pic = _spPageContextInfo.webAbsoluteUrl + '/_layouts/15/userphoto.aspx?size=m&url=' + PictureUrl(o.username);
results.push(o);
})
RenderEverything(results);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + " : " + errorThrown);
}
});
}
function PictureUrl(username) {
var host = window.location.host.replace(".sharepoint.com", "");
host = host.substring(0, host.lastIndexOf("-"));
var url = 'https://' + host + '-my.sharepoint.com/User%20Photos/Profile%20Pictures/' + username.replace("@", "_").replace(/\./g,'_') + "_MThumb.jpg";
return encodeURIComponent(url);
}
function RenderEverything(results) {
var previewsContainer = $("#OGPreviews");
$(results).each(function (i, e) {
var theImg = $("<a target='_blank' href='" + e.path + "'><img src=" + e.pic + " title='" + e.title + "'></img></a>");
previewsContainer.append(theImg);
})
}
function getQueryStringParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
})(jQuery);
|
KaiH0717/Kaguya
|
Source/Engine/Core/RHI/D3D12/D3D12CommandList.h
|
#pragma once
#include "D3D12Common.h"
#include "D3D12ResourceStateTracker.h"
class D3D12CommandQueue;
class D3D12CommandAllocator
{
public:
explicit D3D12CommandAllocator(ID3D12Device* Device, D3D12_COMMAND_LIST_TYPE Type);
operator ID3D12CommandAllocator*() const noexcept { return CommandAllocator.Get(); }
[[nodiscard]] bool IsReady() const { return SyncHandle.IsComplete(); }
[[nodiscard]] D3D12SyncHandle GetSyncHandle() const { return SyncHandle; }
[[nodiscard]] bool HasValidSyncHandle() const { return static_cast<bool>(SyncHandle); }
void SetSyncPoint(const D3D12SyncHandle& SyncHandle) noexcept
{
assert(SyncHandle);
this->SyncHandle = SyncHandle;
}
void Reset() const
{
assert(IsReady());
VERIFY_D3D12_API(CommandAllocator->Reset());
}
private:
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> CommandAllocator;
D3D12SyncHandle SyncHandle;
};
class D3D12CommandListHandle : public D3D12LinkedDeviceChild
{
public:
D3D12CommandListHandle() noexcept = default;
explicit D3D12CommandListHandle(D3D12LinkedDevice* Parent, D3D12_COMMAND_LIST_TYPE Type);
~D3D12CommandListHandle();
// Non-copyable but movable
D3D12CommandListHandle(const D3D12CommandListHandle&) = delete;
D3D12CommandListHandle& operator=(const D3D12CommandListHandle&) = delete;
D3D12CommandListHandle(D3D12CommandListHandle&& D3D12CommandListHandle) noexcept;
D3D12CommandListHandle& operator=(D3D12CommandListHandle&& D3D12CommandListHandle) noexcept;
[[nodiscard]] ID3D12CommandList* GetCommandList() const { return GraphicsCommandList.Get(); }
[[nodiscard]] ID3D12GraphicsCommandList* GetGraphicsCommandList() const { return GraphicsCommandList.Get(); }
[[nodiscard]] ID3D12GraphicsCommandList4* GetGraphicsCommandList4() const { return GraphicsCommandList4.Get(); }
[[nodiscard]] ID3D12GraphicsCommandList6* GetGraphicsCommandList6() const { return GraphicsCommandList6.Get(); }
#ifdef NVIDIA_NSIGHT_AFTERMATH
[[nodiscard]] GFSDK_Aftermath_ContextHandle GetAftermathContextHandle() const { return AftermathContextHandle; }
#endif
ID3D12GraphicsCommandList* operator->() const { return GetGraphicsCommandList(); }
void Close();
void Reset(D3D12CommandAllocator* CommandAllocator);
void SetSyncPoint(const D3D12SyncHandle& SyncHandle) const noexcept { CommandAllocator->SetSyncPoint(SyncHandle); }
// Get the command list resource state associate with this resource
CResourceState& GetResourceState(D3D12Resource* Resource);
// Resolve resource barriers that are needed before this command list is executed
std::vector<D3D12_RESOURCE_BARRIER> ResolveResourceBarriers();
void TransitionBarrier(
D3D12Resource* Resource,
D3D12_RESOURCE_STATES State,
UINT Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES);
void AliasingBarrier(D3D12Resource* BeforeResource, D3D12Resource* AfterResource);
void UAVBarrier(D3D12Resource* Resource);
void FlushResourceBarriers();
bool AssertResourceState(D3D12Resource* Resource, D3D12_RESOURCE_STATES State, UINT Subresource);
private:
D3D12_COMMAND_LIST_TYPE Type;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> GraphicsCommandList;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList4> GraphicsCommandList4;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList6> GraphicsCommandList6;
#ifdef D3D12_DEBUG_RESOURCE_STATES
Microsoft::WRL::ComPtr<ID3D12DebugCommandList> DebugCommandList;
#endif
#ifdef NVIDIA_NSIGHT_AFTERMATH
GFSDK_Aftermath_ContextHandle AftermathContextHandle = nullptr;
#endif
D3D12CommandAllocator* CommandAllocator;
D3D12ResourceStateTracker ResourceStateTracker;
ResourceBarrierBatch ResourceBarrierBatch;
};
|
cchamberlain/powerapi
|
src/lib/redux/modules/redux-idle-monitor.js
|
import configure from 'redux-idle-monitor'
import { push } from 'react-router-redux'
import { packageName, IS_BROWSER } from '../../../config'
import { setText } from '../actions/visual'
export const IDLESTATUS_INACTIVE = 'INACTIVE'
export const IDLE_STATUSES = [ IDLESTATUS_INACTIVE
]
export const idleStatusDelay = idleStatus => (dispatch, getState) => 30000
export const activeStatusAction = (dispatch, getState) => {
dispatch(setText({ subtitle: 'manager'}))
}
export const idleStatusAction = idleStatus => (dispatch, getState) => {
dispatch(setText({ subtitle: idleStatus.replace(/_/g, ' ') }))
}
const opts = { appName: packageName, IDLE_STATUSES, idleStatusDelay, activeStatusAction, idleStatusAction }
const { reducer, actions, middleware } = configure(opts)
export { actions, middleware }
export default reducer
|
javashop/pangu
|
src/test/java/com/enation/pangu/PluginParseTest.java
|
<filename>src/test/java/com/enation/pangu/PluginParseTest.java
package com.enation.pangu;
import com.enation.pangu.enums.PluginPathTypeEnum;
import com.enation.pangu.mapper.PluginMapper;
import com.enation.pangu.service.ExecutorManager;
import com.enation.pangu.utils.ScriptUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;
import org.yaml.snakeyaml.Yaml;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;
import static java.lang.System.out;
/**
* 执行器插件测试
*
* @author kingapex
* @version 1.0
* @since 7.1.0
* 2020/11/2
*/
@RunWith(SpringRunner.class)
@SpringBootTest()
@ComponentScan("com.enation.pangu")
public class PluginParseTest {
/**
* 插件解析测试
* @throws ScriptException
*/
@Test
public void pluginParse() throws ScriptException {
Map env = new HashMap();
env.put("username", "kingapex");
env.put("password", "<PASSWORD>");
env.put("url", "gitxx.com");
env.put("dir", "/opt");
// String script = ScriptUtil.renderScript("port_checker.yml", env, "plugin/port_checker");
String script = ScriptUtil.renderScript("git_clone.yml", env, "executor", PluginPathTypeEnum.resource.value());
Yaml yaml = new Yaml();
Iterable<Object> result = yaml.loadAll(script);
result.forEach(( v)->{
Map map = (Map)v;
out.println(map);
});
}
/**
* 部署yml文件解析测试
*/
@Test
public void deploymentParse() {
Map env = new HashMap();
String script = ScriptUtil.renderScript("b2b2c_set.yml", env, "set", PluginPathTypeEnum.resource.value());
Yaml yaml = new Yaml();
Iterable<Object> result = yaml.loadAll(script);
result.forEach(( v)->{
Map map = (Map)v;
out.println(map);
});
}
@Autowired
ExecutorManager executorManager;
@Autowired
PluginMapper pluginMapper;
// @Test
// public void listTest() {
// List<PluginMetaDataVO> list = executorManager.list();
//
// for (PluginMetaDataVO plugin : list) {
// out.println(plugin.getName());
//
// Plugin pluginDo = new Plugin();
// pluginDo.setPluginId(plugin.getId());
// pluginDo.setName(plugin.getName());
// pluginDo.setAuthor(plugin.getAuthor());
// pluginDo.setAuthorUrl(plugin.getAuthorUrl());
// pluginDo.setDesc(plugin.getDesc());
// pluginDo.setKind(PluginType.executor.name());
// pluginDo.setPath(plugin.getPath());
//
// pluginMapper.insert(pluginDo);
// }
// }
}
|
NimBuzz01/Project-Miika_SDGP
|
miika_nlu/venv/Lib/site-packages/torch/include/ATen/ops/histc_native.h
|
#pragma once
// @generated by tools/codegen/gen.py from NativeFunction.h
#include <c10/core/Scalar.h>
#include <c10/core/Storage.h>
#include <c10/core/TensorOptions.h>
#include <c10/util/Deprecated.h>
#include <c10/util/Optional.h>
#include <c10/core/QScheme.h>
#include <ATen/core/Reduction.h>
#include <ATen/core/Tensor.h>
#include <tuple>
#include <vector>
namespace at {
namespace native {
TORCH_API at::Tensor histogram_histc_cpu(const at::Tensor & self, int64_t bins=100, const at::Scalar & min=0, const at::Scalar & max=0);
TORCH_API at::Tensor & histogram_histc_cpu_out(const at::Tensor & self, int64_t bins, const at::Scalar & min, const at::Scalar & max, at::Tensor & out);
TORCH_API at::Tensor _histc_cuda(const at::Tensor & self, int64_t bins=100, const at::Scalar & min=0, const at::Scalar & max=0);
TORCH_API at::Tensor & _histc_out_cuda(const at::Tensor & self, int64_t bins, const at::Scalar & min, const at::Scalar & max, at::Tensor & out);
} // namespace native
} // namespace at
|
internet-com/basecoin
|
cmd/basecoin/commands/start.go
|
package commands
import (
"fmt"
"os"
"path"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/tendermint/abci/server"
eyesApp "github.com/tendermint/merkleeyes/app"
eyes "github.com/tendermint/merkleeyes/client"
"github.com/tendermint/tmlibs/cli"
cmn "github.com/tendermint/tmlibs/common"
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
"github.com/tendermint/tendermint/node"
"github.com/tendermint/tendermint/proxy"
"github.com/tendermint/tendermint/types"
"github.com/tendermint/basecoin/app"
)
var StartCmd = &cobra.Command{
Use: "start",
Short: "Start basecoin",
RunE: startCmd,
}
// TODO: move to config file
const EyesCacheSize = 10000
//nolint
const (
FlagAddress = "address"
FlagEyes = "eyes"
FlagWithoutTendermint = "without-tendermint"
)
func init() {
flags := StartCmd.Flags()
flags.String(FlagAddress, "tcp://0.0.0.0:46658", "Listen address")
flags.String(FlagEyes, "local", "MerkleEyes address, or 'local' for embedded")
flags.Bool(FlagWithoutTendermint, false, "Only run basecoin abci app, assume external tendermint process")
// add all standard 'tendermint node' flags
tcmd.AddNodeFlags(StartCmd)
}
func startCmd(cmd *cobra.Command, args []string) error {
rootDir := viper.GetString(cli.HomeFlag)
meyes := viper.GetString(FlagEyes)
// Connect to MerkleEyes
var eyesCli *eyes.Client
if meyes == "local" {
eyesApp.SetLogger(logger.With("module", "merkleeyes"))
eyesCli = eyes.NewLocalClient(path.Join(rootDir, "data", "merkleeyes.db"), EyesCacheSize)
} else {
var err error
eyesCli, err = eyes.NewClient(meyes)
if err != nil {
return errors.Errorf("Error connecting to MerkleEyes: %v\n", err)
}
}
// Create Basecoin app
basecoinApp := app.NewBasecoin(eyesCli)
basecoinApp.SetLogger(logger.With("module", "app"))
// register IBC plugn
basecoinApp.RegisterPlugin(NewIBCPlugin())
// register all other plugins
for _, p := range plugins {
basecoinApp.RegisterPlugin(p.newPlugin())
}
// if chain_id has not been set yet, load the genesis.
// else, assume it's been loaded
if basecoinApp.GetState().GetChainID() == "" {
// If genesis file exists, set key-value options
genesisFile := path.Join(rootDir, "genesis.json")
if _, err := os.Stat(genesisFile); err == nil {
err := basecoinApp.LoadGenesis(genesisFile)
if err != nil {
return errors.Errorf("Error in LoadGenesis: %v\n", err)
}
} else {
fmt.Printf("No genesis file at %s, skipping...\n", genesisFile)
}
}
chainID := basecoinApp.GetState().GetChainID()
if viper.GetBool(FlagWithoutTendermint) {
logger.Info("Starting Basecoin without Tendermint", "chain_id", chainID)
// run just the abci app/server
return startBasecoinABCI(basecoinApp)
} else {
logger.Info("Starting Basecoin with Tendermint", "chain_id", chainID)
// start the app with tendermint in-process
return startTendermint(rootDir, basecoinApp)
}
}
func startBasecoinABCI(basecoinApp *app.Basecoin) error {
// Start the ABCI listener
addr := viper.GetString(FlagAddress)
svr, err := server.NewServer(addr, "socket", basecoinApp)
if err != nil {
return errors.Errorf("Error creating listener: %v\n", err)
}
svr.SetLogger(logger.With("module", "abci-server"))
svr.Start()
// Wait forever
cmn.TrapSignal(func() {
// Cleanup
svr.Stop()
})
return nil
}
func startTendermint(dir string, basecoinApp *app.Basecoin) error {
cfg, err := tcmd.ParseConfig()
if err != nil {
return err
}
// Create & start tendermint node
privValidator := types.LoadOrGenPrivValidator(cfg.PrivValidatorFile(), logger)
n := node.NewNode(cfg, privValidator, proxy.NewLocalClientCreator(basecoinApp), logger.With("module", "node"))
_, err = n.Start()
if err != nil {
return err
}
// Trap signal, run forever.
n.RunForever()
return nil
}
|
chrwhit/azure-sdk-for-java
|
sdk/datafactory/azure-resourcemanager-datafactory/src/main/java/com/azure/resourcemanager/datafactory/models/LookupActivity.java
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.datafactory.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.List;
/** Lookup activity. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonTypeName("Lookup")
@JsonFlatten
@Fluent
public class LookupActivity extends ExecutionActivity {
@JsonIgnore private final ClientLogger logger = new ClientLogger(LookupActivity.class);
/*
* Dataset-specific source properties, same as copy activity source.
*/
@JsonProperty(value = "typeProperties.source", required = true)
private CopySource source;
/*
* Lookup activity dataset reference.
*/
@JsonProperty(value = "typeProperties.dataset", required = true)
private DatasetReference dataset;
/*
* Whether to return first row or all rows. Default value is true. Type:
* boolean (or Expression with resultType boolean).
*/
@JsonProperty(value = "typeProperties.firstRowOnly")
private Object firstRowOnly;
/**
* Get the source property: Dataset-specific source properties, same as copy activity source.
*
* @return the source value.
*/
public CopySource source() {
return this.source;
}
/**
* Set the source property: Dataset-specific source properties, same as copy activity source.
*
* @param source the source value to set.
* @return the LookupActivity object itself.
*/
public LookupActivity withSource(CopySource source) {
this.source = source;
return this;
}
/**
* Get the dataset property: Lookup activity dataset reference.
*
* @return the dataset value.
*/
public DatasetReference dataset() {
return this.dataset;
}
/**
* Set the dataset property: Lookup activity dataset reference.
*
* @param dataset the dataset value to set.
* @return the LookupActivity object itself.
*/
public LookupActivity withDataset(DatasetReference dataset) {
this.dataset = dataset;
return this;
}
/**
* Get the firstRowOnly property: Whether to return first row or all rows. Default value is true. Type: boolean (or
* Expression with resultType boolean).
*
* @return the firstRowOnly value.
*/
public Object firstRowOnly() {
return this.firstRowOnly;
}
/**
* Set the firstRowOnly property: Whether to return first row or all rows. Default value is true. Type: boolean (or
* Expression with resultType boolean).
*
* @param firstRowOnly the firstRowOnly value to set.
* @return the LookupActivity object itself.
*/
public LookupActivity withFirstRowOnly(Object firstRowOnly) {
this.firstRowOnly = firstRowOnly;
return this;
}
/** {@inheritDoc} */
@Override
public LookupActivity withLinkedServiceName(LinkedServiceReference linkedServiceName) {
super.withLinkedServiceName(linkedServiceName);
return this;
}
/** {@inheritDoc} */
@Override
public LookupActivity withPolicy(ActivityPolicy policy) {
super.withPolicy(policy);
return this;
}
/** {@inheritDoc} */
@Override
public LookupActivity withName(String name) {
super.withName(name);
return this;
}
/** {@inheritDoc} */
@Override
public LookupActivity withDescription(String description) {
super.withDescription(description);
return this;
}
/** {@inheritDoc} */
@Override
public LookupActivity withDependsOn(List<ActivityDependency> dependsOn) {
super.withDependsOn(dependsOn);
return this;
}
/** {@inheritDoc} */
@Override
public LookupActivity withUserProperties(List<UserProperty> userProperties) {
super.withUserProperties(userProperties);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
@Override
public void validate() {
super.validate();
if (source() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property source in model LookupActivity"));
} else {
source().validate();
}
if (dataset() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property dataset in model LookupActivity"));
} else {
dataset().validate();
}
}
}
|
defc0n1/shoppe_promo
|
vendor/cache/gems/builder-3.2.2/test/preload.rb
|
#!/usr/bin/env ruby
#--
# Portions copyright 2004 by <NAME> (<EMAIL>).
# Portions copyright 2005 by <NAME> (<EMAIL>).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
# We are defining method_added in Kernel and Object so that when
# BlankSlate overrides them later, we can verify that it correctly
# calls the older hooks.
module Kernel
class << self
attr_reader :k_added_names
alias_method :preload_method_added, :method_added
def method_added(name)
preload_method_added(name)
@k_added_names ||= []
@k_added_names << name
end
end
end
class Object
class << self
attr_reader :o_added_names
alias_method :preload_method_added, :method_added
def method_added(name)
preload_method_added(name)
@o_added_names ||= []
@o_added_names << name
end
end
end
|
rwth-acis/mobsos-query-visualization
|
src/main/i5/las2peer/services/mobsos/queryVisualization/database/SQLFilterManager.java
|
package i5.las2peer.services.mobsos.queryVisualization.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import i5.las2peer.api.Context;
import i5.las2peer.api.logging.MonitoringEvent;
import i5.las2peer.api.security.Agent;
import i5.las2peer.services.mobsos.queryVisualization.QueryVisualizationService;
import i5.las2peer.services.mobsos.queryVisualization.encoding.ModificationType;
import i5.las2peer.services.mobsos.queryVisualization.encoding.VisualizationType;
/**
* SQLFilterManager.java <br>
* This class manages custom created filters of a user.
*/
public class SQLFilterManager {
private FilterMap userFilterMap = new FilterMap();
private HashMap<StringPair, String> loadedFilterValues = new HashMap<>();
private SQLDatabase storageDatabase;
/*************** "service" helper methods *************************/
/**
* get the currently active agent
*
* @return active agent
*/
protected Agent getActiveAgent() {
return Context.get().getMainAgent();
}
/**
* write a log message
*
* @param message Message that will be logged
*/
protected void logMessage(String message) {
Context.get().monitorEvent(MonitoringEvent.SERVICE_MESSAGE, this.getClass().getName() + ": " + message);
}
/**************************
* end of service helper methods
************************************/
/**
* Constructor
*
* @param storageDatabase database for the storage
* @param user User id
*/
public SQLFilterManager(SQLDatabase storageDatabase, String user) {
this.storageDatabase = storageDatabase;
if (user == null || user.isEmpty()) {
// get the user's security object which contains the database
// information
user = Context.get().getMainAgent().getIdentifier();
}
SQLFilterSettings[] settings = null;
try {
Connection c = storageDatabase.getConnection();
PreparedStatement p = c.prepareStatement("SELECT * FROM FILTERS WHERE USER = ?;");
p.setString(1, user);
ResultSet set = p.executeQuery();
settings = SQLFilterSettings.fromResultSet(set);
c.close();
} catch (Exception e) {
logMessage("Failed to get the users' SQL settings from the database! " + e.getMessage());
}
if (settings == null || settings.length <= 0) {
// there no database settings available yet...
} else {
for (SQLFilterSettings setting : settings) {
userFilterMap.put(setting.getKey(), setting);
}
}
}
public SQLFilterManager(SQLDatabase storageDatabase) {
this(storageDatabase, null);
}
public boolean addFilter(String databaseKey, String filterName, String sqlQuery) throws Exception {
StringPair filterKey = new StringPair(databaseKey, filterName);
try {
// TODO: sanity checks for the parameters
if (filterExists(databaseKey, filterName)) {
throw new Exception("Filter " + filterKey + " already exists!");
}
Connection c = storageDatabase.getConnection();
SQLFilterSettings filterSettings = new SQLFilterSettings(databaseKey, filterName, sqlQuery);
PreparedStatement p = c.prepareStatement(
"INSERT INTO `FILTERS` (`KEY`, `QUERY`, `USER`, `DB_KEY`) VALUES (?, ?, ?, ?);");
p.setString(1, filterName);
p.setString(2, sqlQuery);
p.setString(3, Context.get().getMainAgent().getIdentifier());
p.setString(4, databaseKey);
p.executeUpdate();
userFilterMap.put(filterSettings.getKey(), filterSettings);
c.close();
return true;
} catch (Exception e) {
e.printStackTrace();
logMessage(e.getMessage());
throw e;
}
}
public void databaseDeleted(String dbKey) {
for (SQLFilterSettings f : userFilterMap.values()) {
if (f.getDatabaseKey().equals(dbKey)) {
try {
deleteFilter(f.getDatabaseKey(), f.getName());
} catch (Exception e) {
}
}
}
}
public boolean deleteFilter(String dbKey, String filterName) throws Exception {
StringPair filterKey = new StringPair(dbKey, filterName);
try {
if (!filterExists(dbKey, filterName)) {
// throw new Exception("Filter with key " + filterKey + " does
// not exists!");
return false;
}
if (userFilterMap != null && userFilterMap.containsKey(filterKey)) {
// delete from hash map
Connection c = storageDatabase.getConnection();
PreparedStatement s = c
.prepareStatement("DELETE FROM `FILTERS` WHERE `KEY` = ? AND `DB_KEY` = ? AND `USER` = ?");
s.setString(1, filterName);
s.setString(2, dbKey);
s.setString(3, Context.get().getMainAgent().getIdentifier());
s.executeUpdate();
userFilterMap.remove(filterKey);
c.close();
}
return true;
} catch (Exception e) {
e.printStackTrace();
logMessage(e.getMessage());
throw e;
}
}
public boolean filterExists(String db, String key) {
return filterExists(new StringPair(db, key));
}
public boolean filterExists(StringPair key) {
try {
return (userFilterMap.get(key) != null);
} catch (Exception e) {
e.printStackTrace();
logMessage(e.getMessage());
}
return false;
}
public int getFilterCount() {
return this.userFilterMap.size();
}
public List<StringPair> getFilterKeyList() {
try {
LinkedList<StringPair> keyList = new LinkedList<>();
Iterator<StringPair> iterator = this.userFilterMap.keySet().iterator();
while (iterator.hasNext()) {
keyList.add(iterator.next());
}
return keyList;
} catch (Exception e) {
e.printStackTrace();
logMessage(e.getMessage());
}
return null;
}
public SQLFilterSettings getFilter(String dbKey, String filterName) {
StringPair filterKey = new StringPair(dbKey, filterName);
SQLFilterSettings filterSettings = userFilterMap.get(filterKey);
if (filterSettings == null) {
return null;
}
return filterSettings;
}
public String getFilterValues(String dbKey, String filterName, VisualizationType visualizationTypeIndex,
QueryVisualizationService agent) throws Exception {
StringPair filterKey = new StringPair(dbKey, filterName);
try {
String filterValues = loadedFilterValues
.get(new StringPair(dbKey, filterName + ":" + visualizationTypeIndex));
if (filterValues == null) {
// load them
SQLFilterSettings filterSettings = userFilterMap.get(filterKey);
if (filterSettings == null) {
// the requested filter is not known/defined
throw new DoesNotExistException(
"The requested filter is not known/configured! Requested:" + filterKey);
}
// get the filter values from the database...
String query = filterSettings.getQuery();
String databaseKey = filterSettings.getDatabaseKey();
filterValues = agent.createQueryString(query, null, databaseKey, true,
ModificationType.IDENTITIY.ordinal(), visualizationTypeIndex, null, false);
// store/cache the filter values (note: the output format is
// added in case the values for the same filter are requested
// multiple times but in different output formats)
loadedFilterValues.put(new StringPair(dbKey, filterName + ":" + visualizationTypeIndex), filterValues);
}
return filterValues;
} catch (Exception e) {
e.printStackTrace();
logMessage(e.getMessage());
throw e;
}
}
}
|
bowen0701/python-algorithms-data-structures
|
alg_arithmetic_series.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""Arithmetic series: 1 + 2 + 3 + ... + n."""
def arithmetic_series_recur(n):
"""Arithmetic series by recursion.
Time complexity: O(n).
Space complexity: O(n)
"""
# Base case.
if n <= 1:
return n
return n + arithmetic_series_recur(n - 1)
def _arithmetic_series_memo(n, T):
# Base case.
if n <= 1:
return n
if T[n]:
return T[n]
T[n] = n + _arithmetic_series_memo(n - 1, T)
return T[n]
def arithmetic_series_memo(n):
"""Arithmetic series by recursion.
Time complexity: O(n).
Space complexity: O(n)
"""
T = [0 for _ in range(n + 1)]
return _arithmetic_series_memo(n, T)
def arithmetic_series_dp(n):
"""Arithmetic series by bottom-up DP.
Time complexity: O(n).
Space complexity: O(n)
"""
T = [0 for _ in range(n + 1)]
T[0] = 0
T[1] = 1
for k in range(2, n + 1):
T[k] = k + T[k - 1]
return T[n]
def arithmetic_series_iter(n):
"""Arithmetic series by bottom-up DP w/ optimized space.
Time complexity: O(n).
Space complexity: O(1)
"""
s = 0
for x in range(1, n + 1):
s += x
return s
def arithmetic_series(n):
"""Arithmetic series by Gauss sum formula.
Time complexity: O(1).
Space complexity: O(1)
"""
return (1 + n) * n / 2
def main():
import time
start_time = time.time()
print('By recursion: {}'.format(arithmetic_series_recur(100)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('By memo: {}'.format(arithmetic_series_memo(100)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('By DP: {}'.format(arithmetic_series_dp(100)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('By iteration: {}'.format(arithmetic_series_iter(100)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('By Gauss sum: {}'.format(arithmetic_series(100)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
|
luzhongyang/DongTai-webapi
|
iast/views/log_export.py
|
<filename>iast/views/log_export.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:owefsad
# software: PyCharm
# project: lingzhi-webapi
from django.contrib.admin.models import LogEntry
from django.http import HttpResponse
from django.utils.encoding import escape_uri_path
from import_export import resources
from rest_framework.generics import GenericAPIView
from django.utils.translation import gettext_lazy as _
from dongtai.endpoint import R
class LogResurce(resources.ModelResource):
def get_export_headers(self):
return [
u'时间', u'用户', u'操作记录'
]
class Meta:
model = LogEntry
fields = ('user', 'action_time', 'change_message')
class ExportMixin(object):
@staticmethod
def attachment_response(export_data, filename='download.xls', content_type='application/vnd.ms-excel'):
"""
- https://segmentfault.com/q/1010000009719860
- https://blog.csdn.net/qq_34309753/article/details/99628474
:param export_data:
:param filename:
:param content_type:
:return:
"""
response = HttpResponse(export_data, content_type=content_type)
response['content_type'] = content_type
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(filename))
return response
def get(self, request):
ids = request.query_params.get('ids')
if ids:
ids = [int(id.strip()) for id in ids.split(',')]
user = request.user
if user.is_talent_admin():
queryset = LogEntry.objects.filter(id__in=ids).filter()
else:
queryset = LogEntry.objects.filter(id__in=ids, user=user).filter()
resources = self.resource_class()
export_data = resources.export(queryset, False)
return ExportMixin.attachment_response(getattr(export_data, 'xls'), filename='用户操作日志.xls')
else:
return R.failure(status=202, msg=_('Export failed, error message: Log id should not be empty'))
class LogExport(ExportMixin, GenericAPIView):
resource_class = LogResurce
|
zbowling/mojo
|
shell/url_response_disk_cache_loader.h
|
<reponame>zbowling/mojo<gh_stars>1-10
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_URL_RESPONSE_DISK_CACHE_LOADER_H_
#define SHELL_URL_RESPONSE_DISK_CACHE_LOADER_H_
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/task_runner.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "services/url_response_disk_cache/url_response_disk_cache_app.h"
#include "shell/application_manager/application_loader.h"
namespace shell {
class URLResponseDiskCacheLoader : public ApplicationLoader {
public:
URLResponseDiskCacheLoader(scoped_refptr<base::TaskRunner> task_runner,
mojo::URLResponseDiskCacheDelegate* delegate);
~URLResponseDiskCacheLoader() override;
private:
// ApplicationLoader overrides:
void Load(
const GURL& url,
mojo::InterfaceRequest<mojo::Application> application_request) override;
mojo::URLResponseDiskCacheApp url_response_disk_cache_;
scoped_ptr<mojo::ApplicationImpl> application_;
DISALLOW_COPY_AND_ASSIGN(URLResponseDiskCacheLoader);
};
} // namespace shell
#endif // SHELL_URL_RESPONSE_DISK_CACHE_LOADER_H_
|
sschum/Mica2015
|
src/main/java/de/tarent/mica/maze/model/Field.java
|
package de.tarent.mica.maze.model;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Field {
private final Coord coord;
private Set<Type> types = new HashSet<>();
public Field(Coord coord, Type...types) {
this(coord, Arrays.asList(types));
}
public Field(Coord coord, Collection<Type> types) {
this.coord = coord;
this.types = new HashSet<>(types);
purge();
validate();
}
private void purge() {
Iterator<Type> iter = types.iterator();
while(iter.hasNext()){
if(iter.next() == null){
iter.remove();
}
}
}
private void validate() {
boolean isWay = hasButton() || hasPlayer();
if(isWay){
types.add(Type.WAY);
}
}
public boolean hasPlayer(){
return getPlayerType() != null;
}
public boolean hasButton(){
return getButtonType() != null;
}
public boolean isWall() {
for(Type t : getTypes()){
if(t == Type.WALL){
return true;
}
}
return false;
}
public Coord getCoord() {
return coord;
}
public Collection<Type> getTypes() {
return types;
}
public Type getPlayerType() {
for(Type t : types){
if(t.isPlayer()){
return t;
}
}
return null;
}
public Type getButtonType() {
for(Type t : types){
if(t.isButton()){
return t;
}
}
return null;
}
public void removeButton() {
Iterator<Type> iter = types.iterator();
while(iter.hasNext()){
if(iter.next().isButton()){
iter.remove();
}
}
}
public void setButton(Type button) {
removeButton();
types.add(button);
}
public void removePlayer() {
Iterator<Type> iter = types.iterator();
while(iter.hasNext()){
if(iter.next().isPlayer()){
iter.remove();
}
}
}
public void setPlayer(Type playerType) {
removePlayer();
types.add(playerType);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((coord == null) ? 0 : coord.hashCode());
result = prime * result + ((types == null) ? 0 : types.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Field other = (Field) obj;
if (coord == null) {
if (other.coord != null)
return false;
} else if (!coord.equals(other.coord))
return false;
if (types == null) {
if (other.types != null)
return false;
} else if (!types.equals(other.types))
return false;
return true;
}
@Override
public String toString() {
return coord + " " + types;
}
}
|
invader777/tleaf
|
src/render/index.js
|
<gh_stars>10-100
'use strict';
var handlebars = require('handlebars');
var _ = require('lodash');
var config = require('../config');
var template = require('../template');
var helpers = require('./helpers');
////////
module.exports = render;
////////
function render(source, data) {
var env = handlebars.create();
registerPartials(env);
registerHelpers(env);
var compiledTemplate = env.compile(source, {
noEscape: true
});
var result = compiledTemplate(data);
var indent = config.template.indent;
if (_.isNumber(indent)) {
indent = _.repeat(' ', indent);
}
if (indent !== '\t') {
result = result.replace(/\t/g, indent);
}
return result;
}
////////
function registerHelpers(env) {
_.forEach(helpers, function (fn, name) {
env.registerHelper(name, fn);
});
}
function registerPartials(env) {
var partials = {};
_.forEach(config.dependencies.process, function (name) {
var source = template.dependency(name);
partials[name] = source;
});
_.forEach(partials, function (source, name) {
env.registerPartial(name, source);
});
}
|
laocaixw/DesignModeLearning
|
src/com/laocaixw/designmode/prototype/Demo.java
|
package com.laocaixw.designmode.prototype;
public class Demo {
public static void main(String[] args) {
ConcretePrototype c1 = new ConcretePrototype();
c1.setType("Type-A");
c1.setName("Name-1");
c1.show();
ConcretePrototype c2 = (ConcretePrototype) c1.clone();
c2.setName("Name-2");
c2.show();
c1.setType("Type-B");
c1.show();
c2.show();
}
}
|
fughz/fx_info_reader
|
lib/fx_info_reader/lion_fx_client.rb
|
<reponame>fughz/fx_info_reader<filename>lib/fx_info_reader/lion_fx_client.rb
# coding: utf-8
require 'open-uri'
require 'nokogiri'
class FxInfoReader::LionFxClient
def get_swap_point_list()
charset = nil
html = open("http://hirose-fx.co.jp/index.php?aid=Sw_Lion") do |f|
charset = f.charset
f.read
end
doc = Nokogiri::HTML.parse(html, nil, charset)
swap_point_list = FxInfoReader::SwapPointList.new
doc.xpath("//*[@id='h3_text']/div[1]/div/table").each do |node|
node.css('tr').each do |row|
elements = row.css('td')
pair_elem = elements.shift
next if pair_elem.nil?
begin
elements.shift # day
short_elem = elements.shift
long_elem = elements.shift
spoint = FxInfoReader::SwapPoint.new(
Float(short_elem.text), Float(long_elem.text), 1000)
swap_point_list.set(pair_elem.text, spoint)
rescue
next
end
end
end
return swap_point_list
end
end
|
July1921/go-zero
|
core/utils/uuid.go
|
<reponame>July1921/go-zero
package utils
import "github.com/google/uuid"
// NewUuid returns a uuid string.
func NewUuid() string {
return uuid.New().String()
}
|
ZXVentures/brewgorithm_devkit
|
tests/language/test/test_cleaning.py
|
<gh_stars>1-10
import unittest
import brewgorithm
clean_word = brewgorithm.language.cleaning.clean_word
filter_nulls = brewgorithm.language.cleaning.filter_nulls
class TestCleaning(unittest.TestCase):
"""Test the cleaning functions."""
def test_clean_word(self):
"""Test that a word gets cleaned."""
word1, clean1 = 'abc', 'abc'
word2, clean2 = '--def_-gh13', 'def_gh13'
self.assertEqual(clean_word(word1), clean1)
self.assertEqual(clean_word(word2), clean2)
def test_filter_nulls(self):
"""Test that nulls are filtered out."""
test1 = None
test2 = '<null>'
test3 = '13'
self.assertEqual(filter_nulls(test1), 0)
self.assertEqual(filter_nulls(test2), 0)
self.assertEqual(filter_nulls(test3), float(test3))
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.