repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
asmfstatoil/neqsim
|
src/main/java/neqsim/thermo/phase/PhaseDesmukhMather.java
|
<reponame>asmfstatoil/neqsim<filename>src/main/java/neqsim/thermo/phase/PhaseDesmukhMather.java
package neqsim.thermo.phase;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import neqsim.thermo.component.ComponentDesmukhMather;
import neqsim.thermo.component.ComponentGEInterface;
/**
* <p>
* PhaseDesmukhMather class.
* </p>
*
* @author <NAME>
* @version $Id: $Id
*/
public class PhaseDesmukhMather extends PhaseGE {
private static final long serialVersionUID = 1000;
double GE = 0.0;
double[][] aij;
double[][] bij;
static Logger logger = LogManager.getLogger(PhaseDesmukhMather.class);
/**
* <p>
* Constructor for PhaseDesmukhMather.
* </p>
*/
public PhaseDesmukhMather() {
super();
}
/** {@inheritDoc} */
@Override
public void addcomponent(String componentName, double moles, double molesInPhase,
int compNumber) {
super.addcomponent(molesInPhase);
componentArray[compNumber] =
new ComponentDesmukhMather(componentName, moles, molesInPhase, compNumber);
}
/** {@inheritDoc} */
@Override
public void init(double totalNumberOfMoles, int numberOfComponents, int initType, int phase,
double beta) {
super.init(totalNumberOfMoles, numberOfComponents, initType, phase, beta);
if (initType != 0) {
phaseTypeName = phase == 0 ? "liquid" : "gas";
}
setMolarVolume(0.980e-3 * getMolarMass() * 1e5);
Z = pressure * getMolarVolume() / (R * temperature);
}
/** {@inheritDoc} */
@Override
public void setMixingRule(int type) {
super.setMixingRule(type);
this.aij = new double[numberOfComponents][numberOfComponents];
this.bij = new double[numberOfComponents][numberOfComponents];
neqsim.util.database.NeqSimDataBase database = new neqsim.util.database.NeqSimDataBase();
for (int k = 0; k < getNumberOfComponents(); k++) {
String component_name = getComponents()[k].getComponentName();
for (int l = k; l < getNumberOfComponents(); l++) {
try {
if (k == l) {
if (getComponents()[l].getComponentName().equals("MDEA")
&& getComponents()[k].getComponentName().equals("MDEA")) {
aij[k][l] = -0.0828487;
this.aij[l][k] = this.aij[k][l];
}
} else {
int templ = l, tempk = k;
// database = new util.database.NeqSimDataBase();
java.sql.ResultSet dataSet = database
.getResultSet("SELECT * FROM inter WHERE (comp1='" + component_name
+ "' AND comp2='" + getComponents()[l].getComponentName()
+ "') OR (comp1='" + getComponents()[l].getComponentName()
+ "' AND comp2='" + component_name + "')");
dataSet.next();
if (dataSet.getString("comp1").trim()
.equals(getComponents()[l].getComponentName())) {
templ = k;
tempk = l;
}
this.aij[k][l] = Double.parseDouble(dataSet.getString("aijDesMath"));
this.bij[k][l] = Double.parseDouble(dataSet.getString("bijDesMath"));
this.aij[l][k] = this.aij[k][l];
this.bij[l][k] = this.bij[k][l];
// System.out.println("aij " + this.aij[l][k]);
dataSet.close();
// database.getConnection().close();
}
} catch (Exception e) {
String err = e.toString();
logger.info("comp names " + component_name);
logger.error(err);
}
}
}
}
/**
* <p>
* Setter for the field <code>aij</code>.
* </p>
*
* @param alpha an array of {@link double} objects
*/
public void setAij(double[][] alpha) {
for (int i = 0; i < alpha.length; i++) {
System.arraycopy(aij[i], 0, this.aij[i], 0, alpha[0].length);
}
}
/**
* <p>
* Setter for the field <code>bij</code>.
* </p>
*
* @param Dij an array of {@link double} objects
*/
public void setBij(double[][] Dij) {
for (int i = 0; i < Dij.length; i++) {
System.arraycopy(bij[i], 0, this.bij[i], 0, Dij[0].length);
}
}
/**
* <p>
* getBetaDesMatij.
* </p>
*
* @param i a int
* @param j a int
* @return a double
*/
public double getBetaDesMatij(int i, int j) {
return aij[i][j] + bij[i][j] * temperature;
}
/**
* <p>
* Getter for the field <code>aij</code>.
* </p>
*
* @param i a int
* @param j a int
* @return a double
*/
public double getAij(int i, int j) {
return aij[i][j];
}
/**
* <p>
* Getter for the field <code>bij</code>.
* </p>
*
* @param i a int
* @param j a int
* @return a double
*/
public double getBij(int i, int j) {
return bij[i][j];
}
/** {@inheritDoc} */
@Override
public double getExessGibbsEnergy(PhaseInterface phase, int numberOfComponents,
double temperature, double pressure, int phasetype) {
GE = 0;
for (int i = 0; i < numberOfComponents; i++) {
GE += phase.getComponents()[i].getx()
* Math.log(((ComponentDesmukhMather) componentArray[i]).getGamma(phase,
numberOfComponents, temperature, pressure, phasetype));
}
// System.out.println("ge " + GE);
return R * temperature * numberOfMolesInPhase * GE;// phase.getNumberOfMolesInPhase()*
}
/** {@inheritDoc} */
@Override
public double getGibbsEnergy() {
return R * temperature * numberOfMolesInPhase * (GE + Math.log(pressure));
}
/** {@inheritDoc} */
@Override
public double getExessGibbsEnergy() {
// double GE = getExessGibbsEnergy(this, numberOfComponents, temperature,
// pressure, phaseType);
return GE;
}
/** {@inheritDoc} */
@Override
public double getActivityCoefficient(int k, int p) {
return ((ComponentGEInterface) getComponent(k)).getGamma();
}
/** {@inheritDoc} */
@Override
public double getActivityCoefficient(int k) {
return ((ComponentGEInterface) getComponent(k)).getGamma();
}
/**
* <p>
* getIonicStrength.
* </p>
*
* @return a double
*/
public double getIonicStrength() {
double ionStrength = 0.0;
for (int i = 0; i < numberOfComponents; i++) {
ionStrength += getComponent(i).getMolality(this)
* Math.pow(getComponent(i).getIonicCharge(), 2.0);
// getComponent(i).getMolarity(this)*Math.pow(getComponent(i).getIonicCharge(),2.0);
}
return 0.5 * ionStrength;
}
/**
* <p>
* getSolventWeight.
* </p>
*
* @return a double
*/
public double getSolventWeight() {
double moles = 0.0;
for (int i = 0; i < numberOfComponents; i++) {
if (getComponent(i).getReferenceStateType().equals("solvent")) {
moles += getComponent(i).getNumberOfMolesInPhase() * getComponent(i).getMolarMass();
}
}
return moles;
}
/**
* <p>
* getSolventDensity.
* </p>
*
* @return a double
*/
public double getSolventDensity() {
double moles = 0.0;
return 1020.0;
}
/**
* <p>
* getSolventMolarMass.
* </p>
*
* @return a double
*/
public double getSolventMolarMass() {
double molesMass = 0.0, moles = 0.0;
for (int i = 0; i < numberOfComponents; i++) {
if (getComponent(i).getReferenceStateType().equals("solvent")) {
molesMass +=
getComponent(i).getNumberOfMolesInPhase() * getComponent(i).getMolarMass();
moles = getComponent(i).getNumberOfMolesInPhase();
}
}
return molesMass / moles;
}
}
|
sjohnson-sage/carbon
|
src/components/heading/heading.component.js
|
<reponame>sjohnson-sage/carbon
import React from "react";
import PropTypes from "prop-types";
import styledSystemPropTypes from "@styled-system/prop-types";
import { filterStyledSystemMarginProps } from "../../style/utils";
import tagComponent from "../../utils/helpers/tags";
import {
StyledHeading,
StyledHeadingIcon,
StyledSubHeader,
StyledHeader,
StyledSeparator,
StyledHeaderHelp,
StyledHeadingTitle,
StyledDivider,
StyledHeaderContent,
StyledHeadingBackButton,
StyledHeadingPills,
} from "./heading.style";
const marginPropTypes = filterStyledSystemMarginProps(
styledSystemPropTypes.space
);
class Heading extends React.Component {
static propTypes = {
...marginPropTypes,
/**
* Children elements
*/
children: PropTypes.node,
/**
* Defines the title for the heading.
*/
title: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
/**
* Defines the title id for the heading.
*/
titleId: PropTypes.string,
/**
* Defines the subheader for the heading.
*/
subheader: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
/**
* Defines the subtitle id for the heading.
*/
subtitleId: PropTypes.string,
/**
* Defines the help text for the heading.
*/
help: PropTypes.string,
/**
* Defines the help link for the heading.
*/
helpLink: PropTypes.string,
/**
* Defines the a href for the back link.
*/
backLink: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Adds a divider below the heading and the content.
*/
divider: PropTypes.bool,
/**
* Adds a separator between the title and the subheader.
*/
separator: PropTypes.bool,
/**
* Pills that will be added after the title.
*/
pills: PropTypes.node,
};
static defaultProps = {
divider: true,
separator: false,
};
/**
* Returns the help component.
*
* @method help
* @return {Object} JSX
*/
get help() {
if (!this.props.help && !this.props.helpLink) {
return null;
}
return (
<StyledHeaderHelp
data-element="help"
tooltipPosition="right"
href={this.props.helpLink}
>
{this.props.help}
</StyledHeaderHelp>
);
}
/**
* Returns the back button.
*
* @method back
* @return {Object} JSX
*/
get back() {
if (!this.props.backLink) {
return null;
}
let props;
if (typeof this.props.backLink === "string") {
props = { href: this.props.backLink };
} else {
props = { onClick: this.props.backLink };
}
return (
<StyledHeadingBackButton
// this event allows an element to be focusable on click event on IE
onMouseDown={(e) => e.currentTarget.focus()}
data-element="back"
{...props}
>
<StyledHeadingIcon type="chevron_left" divider={this.props.divider} />
</StyledHeadingBackButton>
);
}
/**
* Returns the subheader.
*
* @method subheader
* @return {Object} JSX
*/
get subheader() {
if (!this.props.subheader) {
return null;
}
return (
<StyledSubHeader
data-element="subtitle"
id={this.props.subtitleId}
hasBackLink={!!this.props.backLink}
hasSeparator={this.props.separator}
>
{this.props.subheader}
</StyledSubHeader>
);
}
/**
* Returns the separator if enabled and needed.
*
* @method separator
* @return {Object} JSX
*/
get separator() {
return this.props.separator ? <StyledSeparator /> : null;
}
/**
* Returns the separator if enabled and needed.
*
* @method divider
* @return {Object} JSX
*/
get divider() {
return this.props.divider ? <StyledDivider data-element="divider" /> : null;
}
/**
* Returns pills if provided
*
* @method pills
* @return {Object} JSX
*/
get pills() {
return this.props.pills ? (
<StyledHeadingPills data-element="pills">
{this.props.pills}
</StyledHeadingPills>
) : null;
}
/**
* @method render
* @return {Object} JSX
*/
render() {
if (!this.props.title) {
return null;
}
const marginProps = filterStyledSystemMarginProps(this.props);
return (
<StyledHeading {...tagComponent("heading", this.props)} {...marginProps}>
<StyledHeader
data-element="header-container"
divider={this.props.divider}
subheader={this.props.subheader}
hasBackLink={!!this.props.backLink}
>
{this.back}
<StyledHeaderContent>
<StyledHeadingTitle
withMargin={this.props.pills || this.props.help}
variant="h1"
data-element="title"
id={this.props.titleId}
>
{this.props.title}
</StyledHeadingTitle>
{this.help}
{this.pills}
</StyledHeaderContent>
{this.separator}
{this.subheader}
</StyledHeader>
{this.divider}
{this.props.children}
</StyledHeading>
);
}
}
export default Heading;
|
megahbite/transources
|
config/routes.rb
|
Transources::Application.routes.draw do
resources :resources do
resources :comments, only: [:create, :destroy]
collection do
get 'manage'
get 'search'
get 'search_all'
get 'tag/:tag_id', to: "resources#tag"
end
member do
post 'score'
end
end
get "tags/categories", to: "tags#categories"
resources :comments, only: [:destroy] do
collection do
get "manage"
get 'spam'
get 'ham'
end
end
resources :banned_ips, only: [:create, :destroy]
root to: "home#index"
get 'about', to: 'home#about'
get 'contact', to: 'home#contact'
post 'contact', to: 'home#contact_submit'
get 'privacy', to: 'home#privacy'
get 'terms', to: 'home#terms'
devise_for :users
end
|
louisgy/paperless
|
paperless/src/main/java/com/ueh/paperless/service/IntStudentPasswordReset.java
|
//package com.ueh.paperless.service;
//
//import com.ueh.paperless.domain.Students;
//import com.ueh.paperless.dto.Passworddto;
//
//public interface IntStudentPasswordReset {
// public Students resetPassword(Passworddto passworddto);
//}
|
trevorhein-matc/theTwistedLeaf
|
src/components/Element/BaseContainer/BaseContainer.js
|
// @flow
import * as React from 'react'
import PropTypes from 'prop-types'
import { Flex, Box } from 'rebass'
export function BaseContainer({
children,
flex,
className,
...props
}: {
children: React.Node,
flex: boolean,
className: string,
props: any
}) {
if (flex) {
return (
<Flex {...props} className={className}>
{children}
</Flex>
)
} else {
return (
<Box {...props} className={className}>
{children}
</Box>
)
}
}
BaseContainer.propTypes = {
flex: PropTypes.bool,
// children: PropTypes.node.isRequired,
className: PropTypes.string
}
|
jhgonggg/spring-boot
|
hello-spring-boot/src/main/java/com/funtl/hello/spring/boot/help/ContentValidator.java
|
package com.funtl.hello.spring.boot.help;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.funtl.hello.spring.boot.annotation.ContentValidate;
import com.funtl.hello.spring.boot.constant.SysConst;
import com.funtl.hello.spring.boot.enums.WorkFlowTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
@Slf4j
public class ContentValidator implements ConstraintValidator<ContentValidate, Object> {
/**
* 工作流web层组合校验,发布的内容长度(每种工作流字段content里面的字段都不一样)需要根据具体工作流类型而定
* admin api都需要用到
*/
@Override
public void initialize(ContentValidate constraintAnnotation) {
}
/**
* pc端、app端发起工作流程公用参数校验,发布的内容长度视工作流类型不同而不同
* @param value 检验的内容
* @param context 上下文环境
* @return 校验结果 成功 true 失败 false
*/
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (Objects.isNull(value)) {
return true;
}
JSONObject json = JSON.parseObject(JSON.toJSONString(value));
int type = json.getIntValue("type");
String content = json.getString("content");
if (StringUtils.isBlank(content)) {
return false;
}
JSONObject jsonContent = JSON.parseObject(content);
if (Objects.isNull(jsonContent)) {
return false;
}
WorkFlowTypeEnum typeEnum = WorkFlowTypeEnum.getInstance(type);
int length = SysConst.ZERO;
switch (typeEnum) {
case NOTE:
length = StringUtils.length(jsonContent.getString("noteContent"));
break;
case SHARE:
case CHECKIN:
length = StringUtils.length(jsonContent.getString("texContent"));
break;
case TASK:
case VISIT:
case REPORT:
case MANUSCRIPTS:
case REVIEWER:
length = StringUtils.length(jsonContent.getString("visitContent"));
break;
case APPROVAL:
length = StringUtils.length(jsonContent.getString("auditContent"));
break;
case CLUE:
length = StringUtils.length(jsonContent.getString("clueContent"));
break;
default:
break;
}
return length <= 16000;
}
}
|
femmebot/shape
|
db/migrate/20200729224906_add_collection_style_settings.rb
|
<reponame>femmebot/shape<filename>db/migrate/20200729224906_add_collection_style_settings.rb
class AddCollectionStyleSettings < ActiveRecord::Migration[5.2]
def change
add_column :collections, :font_color, :string, default: nil
add_column :collections, :propagate_font_color, :boolean, default: false
add_column :collections, :propagate_background_image, :boolean, default: false
end
end
|
mewspring/llir-llvm-backup
|
asm/enum/dwarflang_string.go
|
// Code generated by "string2enum -linecomment -type DwarfLang /home/u/Desktop/go/src/github.com/llir/llvm/ir/enum"; DO NOT EDIT.
package enum
import "fmt"
import "github.com/llir/llvm/ir/enum"
const (
_DwarfLang_name_0 = "DW_LANG_C89DW_LANG_CDW_LANG_Ada83DW_LANG_C_plus_plusDW_LANG_Cobol74DW_LANG_Cobol85DW_LANG_Fortran77DW_LANG_Fortran90DW_LANG_Pascal83DW_LANG_Modula2DW_LANG_JavaDW_LANG_C99DW_LANG_Ada95DW_LANG_Fortran95DW_LANG_PLIDW_LANG_ObjCDW_LANG_ObjC_plus_plusDW_LANG_UPCDW_LANG_DDW_LANG_PythonDW_LANG_OpenCLDW_LANG_GoDW_LANG_Modula3DW_LANG_HaskellDW_LANG_C_plus_plus_03DW_LANG_C_plus_plus_11DW_LANG_OCamlDW_LANG_RustDW_LANG_C11DW_LANG_SwiftDW_LANG_JuliaDW_LANG_DylanDW_LANG_C_plus_plus_14DW_LANG_Fortran03DW_LANG_Fortran08DW_LANG_RenderScriptDW_LANG_BLISS"
_DwarfLang_name_1 = "DW_LANG_Mips_Assembler"
_DwarfLang_name_2 = "DW_LANG_GOOGLE_RenderScript"
_DwarfLang_name_3 = "DW_LANG_BORLAND_Delphi"
)
var (
_DwarfLang_index_0 = [...]uint16{0, 11, 20, 33, 52, 67, 82, 99, 116, 132, 147, 159, 170, 183, 200, 211, 223, 245, 256, 265, 279, 293, 303, 318, 333, 355, 377, 390, 402, 413, 426, 439, 452, 474, 491, 508, 528, 541}
)
func DwarfLangFromString(s string) enum.DwarfLang {
if len(s) == 0 {
return 0
}
for i := range _DwarfLang_index_0[:len(_DwarfLang_index_0)-1] {
if s == _DwarfLang_name_0[_DwarfLang_index_0[i]:_DwarfLang_index_0[i+1]] {
return enum.DwarfLang(i + 1)
}
}
if s == _DwarfLang_name_1 {
return enum.DwarfLang(32769)
}
if s == _DwarfLang_name_2 {
return enum.DwarfLang(36439)
}
if s == _DwarfLang_name_3 {
return enum.DwarfLang(45056)
}
panic(fmt.Errorf("unable to locate DwarfLang enum corresponding to %q", s))
}
|
MoezAbid/Thinklance-pidev-java
|
src/com/thinklance/pidev/GUI/Projet/ListTacheController.java
|
<reponame>MoezAbid/Thinklance-pidev-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 com.thinklance.pidev.GUI.Projet;
import com.thinklance.pidev.Service.Impl.TacheService;
import com.thinklance.pidev.entities.Tache;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.Stage;
import javafx.util.Callback;
/**
* FXML Controller class
*
* @author LENOVO
*/
public class ListTacheController implements Initializable {
@FXML
private Label codeProjet;
@FXML
private TableView<Tache> tableTache;
@FXML
private TableColumn<Tache, String> c_nonTache;
@FXML
private TableColumn<Tache, String> c_typeTache;
@FXML
private TableColumn<Tache, String> c_estimationTache;
@FXML
private TableColumn<Tache, Integer> c_prioriteTache;
@FXML
private TableColumn<Tache, String> c_etatTache;
private Connection connection;
private Statement st;
private ResultSet rs;
private PreparedStatement pst;
ObservableList<Tache> oblist;
@FXML
private TableColumn<Tache,String> col_supp;
@FXML
private TextField txtnomt;
@FXML
private TextField txtPriorite;
@FXML
private Button enregistrer;
@FXML
private ComboBox<String> txttypeTache;
Tache tache = new Tache();
@FXML
private TextField typr;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
TacheService pdao = new TacheService();
// Integer.parseInt(codeProjet.getText());
// System.out.println("++++++++++++++++++++++++++++++++++++"+Integer.parseInt(codeProjet.getText()));
oblist = pdao.getTacheParId(1);
codeProjet.setText("");
c_nonTache.setCellValueFactory(new PropertyValueFactory<Tache, String>("nomTache"));
c_typeTache.setCellValueFactory(new PropertyValueFactory<Tache, String>("typeTache"));
c_estimationTache.setCellValueFactory(new PropertyValueFactory<Tache, String>("estimationTache"));
c_prioriteTache.setCellValueFactory(new PropertyValueFactory<Tache, Integer>("prioriteTache"));
c_etatTache.setCellValueFactory(new PropertyValueFactory<Tache, String>("etatTache"));
javafx.util.Callback<TableColumn<Tache, String>, TableCell<Tache, String>> cellFactory
= //
new Callback<TableColumn<Tache, String>, TableCell<Tache, String>>() {
@Override
public TableCell call(final TableColumn<Tache, String> param) {
final TableCell<Tache, String> cell = new TableCell<Tache, String>() {
final Button btn = new Button("Delete");
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
setText(null);
} else {
btn.setOnAction(event -> {
Tache cn = getTableView().getItems().get(getIndex());
System.out.println(cn.getNomTache());
TacheService cs = new TacheService();
cs.deleteTache(cn);
Parent root;
try {
root = FXMLLoader.load(getClass().getResource("ListTache.fxml"));
btn.getScene().setRoot(root);
} catch (IOException ex) {
}
});
setGraphic(btn);
setText(null);
}
}
};
return cell;
}
};
col_supp.setCellFactory(cellFactory);
tableTache.getColumns().add(col_supp);
tableTache.setItems(oblist);
modifierNomTache();
// modifierTypeTache();
// modifierEstimationTache();
// modifierPrioriteTache();
// modifierEtatTache();
txttypeTache.getItems().addAll("projet administratif","Gestion des employeurs","paiement en ligne");
}
public void modifierNomTache() {
c_nonTache.setCellFactory(TextFieldTableCell.forTableColumn());
c_nonTache.setOnEditCommit(e -> {
e.getTableView().getItems().get(e.getTablePosition().getRow()).setNomTache(e.getNewValue());
final int row = tableTache.getEditingCell().getRow();
System.out.println("_______________" + row);
System.out.println("Titre projet __________ " + tableTache.getItems().get(row).getNomTache());
System.out.println("PRIORITE __________ " + tableTache.getItems().get(row).getPrioriteTache());
TacheService proj = new TacheService();
proj.updateNomT(tableTache.getItems().get(row));
});
tableTache.setEditable(true);
}
private void supprimerTache(ActionEvent event) {
ObservableList<Tache> allProjet, singleProjet;
allProjet = tableTache.getItems();
singleProjet = tableTache.getSelectionModel().getSelectedItems();
Tache p = (Tache) tableTache.getSelectionModel().getSelectedItem();
TacheService pdao = new TacheService();
pdao.deleteTache(p);
singleProjet.forEach(allProjet::remove);
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("ListeTache.fxml"));
loader.setController(new ListeProjetController());
Parent root = loader.load();
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException ex) {
}
}
public Label getCodeProjet() {
return codeProjet;
}
public void setCodeProjet(Label codeProjet) {
this.codeProjet = codeProjet;
}
//public void seta(int a){this.codeProjet.setText(String.valueOf(a));}
public void setValue(int id){
this.codeProjet.setText(String.valueOf(id));
}
@FXML
private void plusTache(ActionEvent event) {
TacheService tachdao = new TacheService();
tache.setNomTache(txtnomt.getText());
tache.setTypeTache(typr.getText());
int p=Integer.parseInt(txtPriorite.getText());
// tache.setIdProjet(Integer.parseInt(codeProjet.getText()));
tache.setPrioriteTache(p);
tachdao.addTache2(tache);
}
}
|
xvik/spock-junit5
|
src/test/java/playground/tests/JupiterManualRegistration.java
|
<filename>src/test/java/playground/tests/JupiterManualRegistration.java
package playground.tests;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import ru.vyarus.spock.jupiter.support.ActionHolder;
import ru.vyarus.spock.jupiter.support.LifecycleExtension;
import ru.vyarus.spock.jupiter.support.LifecycleExtension2;
import ru.vyarus.spock.jupiter.support.LifecycleExtension3;
/**
* @author <NAME>
* @since 26.12.2021
*/
@Disabled
public class JupiterManualRegistration {
@RegisterExtension
static LifecycleExtension ext = new LifecycleExtension();
@RegisterExtension
LifecycleExtension2 ext2 = new LifecycleExtension2();
@Test
@ExtendWith(LifecycleExtension3.class)
void sampleTest() {
ActionHolder.add("test.body");
}
}
|
TwoFistedJustice/square-pie
|
src/lib/order_object_tax.js
|
const { nanoid } = require("nanoid");
const {
arche_money,
shazam_max_length,
shazam_is_integer,
} = require("./utilities");
const { uid_length } = require("../pie_defaults");
const man =
"build one Line Item Tax for an order. (goes in taxes array of Order_Object) \n" +
"Uses standard Pie syntax. There is nothing unusual about this class.\n" +
"uid is set automatically. But you can change it using make().uid()\n" +
"https://developer.squareup.com/reference/square_2022-01-20/objects/OrderLineItemTax";
/**
* {@link https://developer.squareup.com/reference/square_2022-01-20/objects/OrderLineItemTax | **-------> Link To Square Docs <-------**}
* @class Order_Tax
* @classdesc
*
* Build one Line Item Tax for an order. (goes in taxes array of Order_Object)<br><br>
* uid is set automatically. But you can change it using make().uid()<br><br>
* */
class Order_Tax {
_display_name = "Order_Tax";
_last_verified_square_api_version = "2022-01-20";
_help = this.display_name + ": " + man;
constructor() {
this._fardel = {
uid: "uid_order_tax#" + nanoid(uid_length),
name: undefined, //str 255
catalog_object_id: undefined, // id 192
catalog_version: undefined, //int
percentage: undefined, // str 10
applied_money: undefined, //'money object',
scope: undefined, // enum
};
this.configuration = {
maximums: {
uid: 60,
name: 255,
catalog_object_id: 192,
percentage: 10,
},
};
}
get display_name() {
return this._display_name;
}
get square_version() {
return `The last verified compatible Square API version is ${this._last_verified_square_api_version}`;
}
get help() {
return this._help;
}
get fardel() {
return this._fardel;
}
// GETTERS
get uid() {
return this._fardel.uid;
}
get name() {
return this._fardel.name;
}
get catalog_object_id() {
return this._fardel.catalog_object_id;
}
get catalog_version() {
return this._fardel.catalog_version;
}
get percentage() {
return this._fardel.percentage;
}
get applied_money() {
return this._fardel.applied_money;
}
get scope() {
return this._fardel.scope;
}
// SETTERS
set uid(uid) {
if (
shazam_max_length(
this.configuration.maximums.uid,
uid,
this.display_name,
"uid"
)
) {
this._fardel.uid = uid;
}
}
set name(name) {
if (
shazam_max_length(
this.configuration.maximums.name,
name,
this.display_name,
"name"
)
) {
this._fardel.name = name;
}
}
set catalog_object_id(id) {
if (
shazam_max_length(
this.configuration.maximums.catalog_object_id,
id,
this.display_name,
"catalog_object_id"
)
) {
this._fardel.catalog_object_id = id;
}
}
set catalog_version(ver) {
if (shazam_is_integer(ver, this.display_name, "catalog_version")) {
this._fardel.catalog_version = ver;
}
}
set percentage(percent) {
if (
shazam_max_length(
this.configuration.maximums.percentage,
percent,
this.display_name,
"percentage"
)
) {
this._fardel.percentage = percent;
}
}
set applied_money(money) {
this._fardel.applied_money = money;
}
set scope(str) {
this._fardel.scope = str;
}
/**
* {@link https://developer.squareup.com/reference/square_2022-01-20/enums/OrderLineItemTaxScope | Square Docs}<br>
*
* #enum_scope<br>
* Enumerated methods set specific values from a limited set of allowable values defined by Square.
* For each value, a sub-method will exist that is the lowercase version of that value. There may also
* exist abbreviated aliases.
*
* Enumerated methods are usually called by other functions and set the value on the object on which
* the calling function operates.
* @typedef {function} Order_Tax.enum_scope
* @private
* @abstract
* @memberOf Order_Tax
* @property other_tax_scope() - sets value to "OTHER_TAX_SCOPE"
* @property line_item() - sets value to "LINE_ITEM"
* @property order() - sets value to "ORDER"
* @property other() - alias of `other_tax_scope`
* @property line() - alias of `line_item`
* @property ()
* @example
* If you were allowed to choose from the set ["GOOD", "BAD", "UGLY"] in order to set the
* value of `clint` on the object 'western'
*
* vyMar.make_western().clint.().good() => const spaghetti = {western : {clint: "GOOD"}}
* */
#enum_scope(calling_this) {
return {
self: this,
other_tax_scope: function () {
this.self.scope = "OTHER_TAX_SCOPE";
return calling_this;
},
line_item: function () {
this.self.scope = "LINE_ITEM";
return calling_this;
},
order: function () {
this.self.scope = "ORDER";
return calling_this;
},
other: function () {
return this.other_tax_scope();
},
line: function () {
return this.line_item();
},
};
}
// MAKE METHODS
/**
* make() method of Order_Tax
* Make sure to have the Square Docs open in front of you.
* Sub-Method names are exactly the same as the property names listed
* in the Square docs. There may be additional methods and/or shortened aliases of other methods.
*
* You should read the generated docs as:
* method_name(arg) {type} description of arg
*
* @typedef {function} Order_Tax.make
* @method
* @public
* @memberOf Order_Tax
* @property {string} uid(uid) - automatically set. Use this only to replace the generated uid.
* @property name(name) {string} -
* @property catalog_object_id(id) {string<id>} -
* @property catalog_version(ver) {integer} -
* @property percentage(percent) {string} - a percentage amount in the form of a string.
* @property applied_money(amount,currency) {money} - Standard compliant money object builder.
* @property scope() {Enumerated} - Calls `#enum_scope()`
* @example
* You must use parentheses with every call to make and with every sub-method. If you have to make a lot
* of calls from different lines, it will reduce your tying and improve readability to set make() to a
* variable.
*
* let make = myVar.make();
* make.gizmo()
* make.gremlin()
* //is the same as
* myVar.make().gizmo().gremlin()
* */
make() {
return {
self: this,
uid: function (uid) {
this.self.uid = uid;
return this;
},
name: function (name) {
this.self.name = name;
return this;
},
catalog_object_id: function (id) {
this.self.catalog_object_id = id;
return this;
},
catalog_version: function (ver) {
this.self.catalog_version = ver;
return this;
},
percentage: function (percent) {
this.self.percentage = percent;
return this;
},
applied_money: function (amount, currency) {
this.self.applied_money = arche_money(amount, currency);
return this;
},
scope: function () {
return this.self.#enum_scope(this);
},
};
}
}
module.exports = Order_Tax;
|
aberdev/orientdb
|
client/src/main/java/com/orientechnologies/orient/client/remote/message/OListDatabasesResponse.java
|
package com.orientechnologies.orient.client.remote.message;
import com.orientechnologies.orient.client.remote.OBinaryResponse;
import com.orientechnologies.orient.client.remote.OStorageRemoteSession;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerNetworkFactory;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelDataInput;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelDataOutput;
import java.io.IOException;
import java.util.Map;
public class OListDatabasesResponse implements OBinaryResponse {
private Map<String, String> databases;
public OListDatabasesResponse(Map<String, String> databases) {
this.databases = databases;
}
public OListDatabasesResponse() {}
@Override
public void write(OChannelDataOutput channel, int protocolVersion, ORecordSerializer serializer)
throws IOException {
final ODocument result = new ODocument();
result.field("databases", databases);
byte[] toSend = serializer.toStream(result);
channel.writeBytes(toSend);
}
@Override
public void read(OChannelDataInput network, OStorageRemoteSession session) throws IOException {
ORecordSerializer serializer = ORecordSerializerNetworkFactory.INSTANCE.current();
final ODocument result = new ODocument();
serializer.fromStream(network.readBytes(), result, null);
databases = result.field("databases");
}
public Map<String, String> getDatabases() {
return databases;
}
}
|
Marvingms7/IFPI
|
Semana09Atividade01/Sem08Atv01Q05.py
|
<filename>Semana09Atividade01/Sem08Atv01Q05.py
def carrega_cidades():
resultado = []
m = str(int(input()))
p = int(input())
res = e_mes(int(m))
ress = str(res).upper()
print(f'CIDADES COM MAIS DE {p} HABITANTES E ANIVERSÁRIO EM {ress}:')
with open('cidades.csv', 'r', encoding='utf-8') as arquivo:
for linha in arquivo:
uf, ibge, nome, dia, mes, pop = linha.split(';')
for n in (1, 5557):
res = e_mes(int(m))
if mes == m and int(pop) > p:
pplc = pop.split()
print(f'{nome}({uf}) tem {pplc[0]} habitantes e faz aniversário em {dia} de {res}.')
break
arquivo.close()
return resultado
def e_mes(a):
mess = (
'janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro',
'dezembro')
for c in range(len(mess)):
if a - 1 == c:
return (mess[c])
cidades = carrega_cidades()
|
NewAcropolis/api
|
migrations/versions/0040.py
|
<reponame>NewAcropolis/api
"""empty message
Revision ID: 0040 add email providers
Revises: 0039 add subject to emails
Create Date: 2020-06-18 01:38:30.911104
"""
# revision identifiers, used by Alembic.
revision = '0040 add email providers'
down_revision = '0039 add subject to emails'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('email_providers',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('daily_limit', sa.Integer(), nullable=True),
sa.Column('api_key', sa.String(), nullable=True),
sa.Column('api_url', sa.String(), nullable=True),
sa.Column('data_struct', sa.String(), nullable=True),
sa.Column('pos', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name'),
sa.UniqueConstraint('pos')
)
op.add_column(u'email_to_member', sa.Column('emailed_by', sa.String(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column(u'email_to_member', 'emailed_by')
op.drop_table('email_providers')
# ### end Alembic commands ###
|
Futuremappermydud/Naluluna-Modifier-Quest
|
include/codegen/include/GlobalNamespace/GameEnergyCounter_InitData.hpp
|
<filename>include/codegen/include/GlobalNamespace/GameEnergyCounter_InitData.hpp<gh_stars>1-10
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: GameEnergyCounter
#include "GlobalNamespace/GameEnergyCounter.hpp"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: GameEnergyCounter/InitData
class GameEnergyCounter::InitData : public ::Il2CppObject {
public:
// public readonly GameplayModifiers/EnergyType energyType
// Offset: 0x10
GlobalNamespace::GameplayModifiers::EnergyType energyType;
// public readonly System.Boolean noFail
// Offset: 0x14
bool noFail;
// public readonly System.Boolean instaFail
// Offset: 0x15
bool instaFail;
// public readonly System.Boolean failOnSaberClash
// Offset: 0x16
bool failOnSaberClash;
// public System.Void .ctor(GameplayModifiers/EnergyType energyType, System.Boolean noFail, System.Boolean instaFail, System.Boolean failOnSaberClash)
// Offset: 0xB3C0CC
static GameEnergyCounter::InitData* New_ctor(GlobalNamespace::GameplayModifiers::EnergyType energyType, bool noFail, bool instaFail, bool failOnSaberClash);
}; // GameEnergyCounter/InitData
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::GameEnergyCounter::InitData*, "", "GameEnergyCounter/InitData");
#pragma pack(pop)
|
nordapp/rest
|
org.i3xx.util.driverapi/src/main/java/org/i3xx/util/driverapi/client/RootsInfo.java
|
<filename>org.i3xx.util.driverapi/src/main/java/org/i3xx/util/driverapi/client/RootsInfo.java
package org.i3xx.util.driverapi.client;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* JSON Deserializer
*
* @author Stefan
*
*/
public class RootsInfo {
/**
* Parses the collection info from StatisticImpl
* {protocol}://{server}/dba/{session}/statistic?type=roots
*
* @param json
* @return
*/
public static String[] parse(String json) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
String[] list = gson.fromJson(json, String[].class);
return list;
}
}
|
vertgenlab/gonomics
|
cmd/statCalc/statCalc.go
|
// Command Group: "Statistics & Population Genetics"
package main
import (
"flag"
"fmt"
"github.com/vertgenlab/gonomics/common"
"github.com/vertgenlab/gonomics/numbers"
"github.com/vertgenlab/gonomics/popgen"
"log"
"strings"
)
//kills the program if multiple options are selected.
func MultipleOptionErrorCheck(Normal *string, Binomial *string, Poisson *string, Beta *string, Gamma *string, SampleAfs *string, SampleBeta *string, SampleGamma *string, SampleNormal *string) {
var count int = 0
if *Normal != "" {
count++
}
if *Binomial != "" {
count++
}
if *Poisson != "" {
count++
}
if *Beta != "" {
count++
}
if *Gamma != "" {
count++
}
if *SampleAfs != "" {
count++
}
if *SampleBeta != "" {
count++
}
if *SampleGamma != "" {
count++
}
if *SampleNormal != "" {
count++
}
if count > 1 {
log.Fatalf("Error: Multiple distribution arguments selected.")
}
}
func usage() {
fmt.Print(
"statCalc - Command line statistics calculator.\n" +
"Usage:\t" +
" statCalc [options] \n" +
"options:\n" +
" -normal=mu,sigma. Defines a normal distribution with mean mu and standard deviation sigma. Ex Usage: -normal=0,1 1 or -normal=0,1 2 inf\n" +
" -binomial=n,p. Defines a binomial distribution with n experiments and success probability p. Ex Usage: -binomial=10,0.5 3 or -binomial=10, 0.5 6 n\n" +
" -poisson=lambda. Defines a poisson distribution with rate parameter lambda. Ex Usage: -poisson=4 4\n" +
" -beta=alpha,beta. Defines a beta dsitribution with paramters alpha and beta. Ex Usage: -beta=5,5 0.2\n" +
" -gamma=alpha,beta. Defines a gamma distribution with parameters alpha and beta. Ex Usage: -gamma=4,4 6\n" +
" -sampleAfs=alpha,numSamples,maxSampleDepth,bins,xLeft,xRight. Provides a list of values sampled from an allele frequency spectrum with selection parameter alpha.\n" +
"sampleAFS will return numSamples many values between xLeft and xRight. Bins and maxSampleDepth are performance and accuracy options, suggested values are 1000 and 1000, respectively.\n" +
"After defining a distribution, one float64 argument returns the function density at that value. Ex usage: -sampleAfs=0.02,200,1000,1000,0.001,0.999,false\n" +
"sampleBeta=alpha,beta,numSamples. Provides a list of values sampled from the beta distribution with a selected alpha and beta parameter.\n" +
"sampleGamma=alpha,beta,numSample. Provides a list of values sampled from the gamma distribution with a selected alpha and beta parameter.\n" +
"sampleNormal=mu,sigma,numSamples. Provides a list of values sampled from the normal distribution with a selected mu and sigma parameter.\n" +
"For discrete distributions, two arguments will evaluate the sum between two input values.\n" +
"For the binomial distribution summation, the second argument can be set to n or N to evaluate the entire right tailed sum.\n" +
"For continuous distributions, two arguments will evaluate an integral between the two input values with the defined distribution as the integrand.\n")
}
func main() {
var Normal *string = flag.String("normal", "", "")
var Binomial *string = flag.String("binomial", "", "")
var Poisson *string = flag.String("poisson", "", "")
var Beta *string = flag.String("beta", "", "")
var Gamma *string = flag.String("gamma", "", "")
var SampleAfs *string = flag.String("sampleAfs", "", "")
var SampleBeta *string = flag.String("sampleBeta", "", "")
var SampleGamma *string = flag.String("sampleGamma", "", "")
var SampleNormal *string = flag.String("sampleNormal", "", "")
var randSeed *bool = flag.Bool("randSeed", false, "Uses a random seed for the RNG.")
var setSeed *int64 = flag.Int64("setSeed", -1, "Use a specific seed for the RNG.")
flag.Usage = usage
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
flag.Parse()
MultipleOptionErrorCheck(Normal, Binomial, Poisson, Beta, Gamma, SampleAfs, SampleBeta, SampleGamma, SampleNormal)
common.RngSeed(*randSeed, *setSeed)
if *Normal != "" {
words := strings.Split(*Normal, ",")
if len(words) != 2 {
log.Fatalf("Error: A normal distribution is defined by two parameters. Received %v.\n", len(words))
}
mu := common.StringToFloat64(words[0])
sigma := common.StringToFloat64(words[1])
if len(flag.Args()) > 2 || len(flag.Args()) < 1 {
flag.Usage()
log.Fatalf("Error: expected one or two arguments, but got %d\n", len(flag.Args()))
}
if len(flag.Args()) == 1 {
x := common.StringToFloat64(flag.Arg(0))
fmt.Printf("%e\n", numbers.NormalDist(x, mu, sigma))
} else if len(flag.Args()) == 2 {
fmt.Printf("%e\n", numbers.NormalAdaptiveIntegral(flag.Arg(0), flag.Arg(1), mu, sigma))
}
} else if *Binomial != "" {
words := strings.Split(*Binomial, ",")
if len(words) != 2 {
log.Fatalf("Error: a binomial distribution is defined by two parameters. Received %v.\n", len(words))
}
n := common.StringToInt(words[0])
p := common.StringToFloat64(words[1])
if len(flag.Args()) > 2 || len(flag.Args()) < 1 {
flag.Usage()
log.Fatalf("Error: expected one or two arguments, but got %d\n", len(flag.Args()))
}
if len(flag.Args()) == 1 {
i := common.StringToInt(flag.Arg(0))
answer, _ := numbers.BinomialDist(n, i, p)
fmt.Printf("%e\n", answer)
} else if len(flag.Args()) == 2 {
left := common.StringToInt(flag.Arg(0))
if flag.Arg(1) == "N" || flag.Arg(1) == "n" {
if left == 0 {
fmt.Printf("%e\n", 1.00000)
} else {
fmt.Printf("%e\n", numbers.BinomialRightSummation(n, left, p))
}
} else if left == 0 {
right := common.StringToInt(flag.Arg(1))
fmt.Printf("%e\n", numbers.BinomialLeftSummation(n, right, p))
} else {
right := common.StringToInt(flag.Arg(1))
fmt.Printf("%e\n", numbers.BinomialSum(left, right, n, p))
}
}
} else if *Poisson != "" {
lambda := common.StringToFloat64(*Poisson)
if len(flag.Args()) > 2 || len(flag.Args()) < 1 {
flag.Usage()
log.Fatalf("Error: expected one or two arguments, but got %d\n", len(flag.Args()))
}
if len(flag.Args()) == 1 {
k := common.StringToInt(flag.Arg(0))
fmt.Printf("%e\n", numbers.PoissonDist(k, lambda))
} else if len(flag.Args()) == 2 {
if flag.Arg(1) == "INF" || flag.Arg(1) == "inf" || flag.Arg(1) == "Inf" {
k := common.StringToInt(flag.Arg(0))
fmt.Printf("%e\n", numbers.PoissonRightSummation(k, lambda))
} else {
left := common.StringToInt(flag.Arg(0))
right := common.StringToInt(flag.Arg(1))
fmt.Printf("%e\n", numbers.PoissonSum(left, right, lambda))
}
}
} else if *Beta != "" {
words := strings.Split(*Beta, ",")
if len(words) != 2 {
log.Fatalf("Error: a beta distribution is defined by two parameters. Received %v.\n", len(words))
}
alpha := common.StringToFloat64(words[0])
beta := common.StringToFloat64(words[1])
if len(flag.Args()) > 2 || len(flag.Args()) < 1 {
flag.Usage()
log.Fatalf("Error: expected one or two arguments, but got %d\n", len(flag.Args()))
}
if len(flag.Args()) == 1 {
x := common.StringToFloat64(flag.Arg(0))
fmt.Printf("%e\n", numbers.BetaDist(x, alpha, beta))
} else if len(flag.Args()) == 2 {
left := common.StringToFloat64(flag.Arg(0))
right := common.StringToFloat64(flag.Arg(1))
fmt.Printf("%e\n", numbers.BetaIntegral(left, right, alpha, beta))
}
} else if *Gamma != "" {
words := strings.Split(*Gamma, ",")
if len(words) != 2 {
log.Fatalf("Error: a gamma distribution is defined by two parameters. Received %v.\n", len(words))
}
alpha := common.StringToFloat64(words[0])
beta := common.StringToFloat64(words[1])
if len(flag.Args()) > 2 || len(flag.Args()) < 1 {
flag.Usage()
log.Fatalf("Error: expected one or two arguments, but got %d\n", len(flag.Args()))
}
if len(flag.Args()) == 1 {
x := common.StringToFloat64(flag.Arg(0))
fmt.Printf("%e\n", numbers.GammaDist(x, alpha, beta))
} else if len(flag.Args()) == 2 {
left := common.StringToFloat64(flag.Arg(0))
if flag.Arg(1) == "INF" || flag.Arg(1) == "inf" || flag.Arg(1) == "Inf" {
fmt.Printf("%e\n", numbers.GammaRightIntegral(left, alpha, beta))
} else {
right := common.StringToFloat64(flag.Arg(1))
fmt.Printf("%e\n", numbers.GammaIntegral(left, right, alpha, beta))
}
}
} else if *SampleAfs != "" {
words := strings.Split(*SampleAfs, ",")
if len(words) != 6 {
log.Fatalf("Error: sampleAFS expected seven parameters, received: %v.\n", len(words))
}
alpha := common.StringToFloat64(words[0])
numSamples := common.StringToInt(words[1])
maxSampleDepth := common.StringToInt(words[2])
bins := common.StringToInt(words[3])
xLeft := common.StringToFloat64(words[4])
xRight := common.StringToFloat64(words[5])
answer := popgen.StationaritySampler(alpha, numSamples, maxSampleDepth, bins, xLeft, xRight)
for i := 0; i < len(answer); i++ {
fmt.Printf("%e\n", answer[i])
}
} else if *SampleBeta != "" {
words := strings.Split(*SampleBeta, ",")
if len(words) != 3 {
log.Fatalf("Error: sampleBeta expected four parameters, received: %v.\n", len(words))
}
alpha := common.StringToFloat64(words[0])
beta := common.StringToFloat64(words[1])
numSamples := common.StringToInt(words[2])
sampler := numbers.BetaSampler(alpha, beta)
var current float64
for i := 0; i < numSamples; i++ {
current, _ = sampler()
fmt.Printf("%e\n", current)
}
} else if *SampleGamma != "" {
words := strings.Split(*SampleGamma, ",")
if len(words) != 3 {
log.Fatalf("Error: sampleGamma expected four parameters, received: %v.\n", len(words))
}
alpha := common.StringToFloat64(words[0])
beta := common.StringToFloat64(words[1])
numSamples := common.StringToInt(words[2])
sampler := numbers.GammaSampler(alpha, beta)
var current float64
for i := 0; i < numSamples; i++ {
current, _ = sampler()
fmt.Printf("%e\n", current)
}
} else if *SampleNormal != "" {
words := strings.Split(*SampleNormal, ",")
if len(words) != 3 {
log.Fatalf("Error: sampleNormal expected four parameters, received: %v.\n", len(words))
}
mu := common.StringToFloat64(words[0])
sigma := common.StringToFloat64(words[1])
numSamples := common.StringToInt(words[2])
for i := 0; i < numSamples; i++ {
fmt.Printf("%e\n", numbers.SampleInverseNormal(mu, sigma))
}
} else {
flag.Usage()
log.Fatalf("Error: No distribution command specified.")
}
}
|
vladbalach/uchat
|
client/src/file_sender/mx_free_file.c
|
#include "client.h"
#include "mxinet.h"
#include "defines_client.h"
void mx_free_file(t_file *file) {
free(file->name);
free(file);
}
|
matthiasblaesing/COMTypelibraries
|
excel1/src/main/java/eu/doppel_helix/jna/tlb/excel1/PivotFilters.java
|
package eu.doppel_helix.jna.tlb.excel1;
import com.sun.jna.platform.win32.COM.util.annotation.ComInterface;
import com.sun.jna.platform.win32.COM.util.annotation.ComMethod;
import com.sun.jna.platform.win32.COM.util.annotation.ComProperty;
import com.sun.jna.platform.win32.COM.util.IDispatch;
import com.sun.jna.platform.win32.COM.util.IUnknown;
import com.sun.jna.platform.win32.COM.util.IRawDispatchHandle;
import com.sun.jna.platform.win32.Variant.VARIANT;
/**
* <p>uuid({00024484-0000-0000-C000-000000000046})</p>
*/
@ComInterface(iid="{00024484-0000-0000-C000-000000000046}")
public interface PivotFilters extends IUnknown, IRawDispatchHandle, IDispatch {
/**
* <p>id(0x94)</p>
* <p>vtableId(7)</p>
*/
@ComProperty(name = "Application", dispId = 0x94)
Application getApplication();
/**
* <p>id(0x95)</p>
* <p>vtableId(8)</p>
*/
@ComProperty(name = "Creator", dispId = 0x95)
XlCreator getCreator();
/**
* <p>id(0x96)</p>
* <p>vtableId(9)</p>
*/
@ComProperty(name = "Parent", dispId = 0x96)
com.sun.jna.platform.win32.COM.util.IDispatch getParent();
/**
* <p>id(0x0)</p>
* <p>vtableId(10)</p>
* @param Index [in] {@code Object}
*/
@ComProperty(name = "_Default", dispId = 0x0)
PivotFilter get_Default(Object Index);
/**
* <p>id(0xaa)</p>
* <p>vtableId(12)</p>
* @param Index [in] {@code Object}
*/
@ComProperty(name = "Item", dispId = 0xaa)
PivotFilter getItem(Object Index);
/**
* <p>id(0x76)</p>
* <p>vtableId(13)</p>
*/
@ComProperty(name = "Count", dispId = 0x76)
Integer getCount();
/**
* <p>id(0xb5)</p>
* <p>vtableId(14)</p>
* @param Type [in] {@code XlPivotFilterType}
* @param DataField [in, optional] {@code Object}
* @param Value1 [in, optional] {@code Object}
* @param Value2 [in, optional] {@code Object}
* @param Order [in, optional] {@code Object}
* @param Name [in, optional] {@code Object}
* @param Description [in, optional] {@code Object}
* @param MemberPropertyField [in, optional] {@code Object}
*/
@ComMethod(name = "Add", dispId = 0xb5)
PivotFilter Add(XlPivotFilterType Type,
Object DataField,
Object Value1,
Object Value2,
Object Order,
Object Name,
Object Description,
Object MemberPropertyField);
/**
* <p>id(0xbee)</p>
* <p>vtableId(15)</p>
* @param Type [in] {@code XlPivotFilterType}
* @param DataField [in, optional] {@code Object}
* @param Value1 [in, optional] {@code Object}
* @param Value2 [in, optional] {@code Object}
* @param Order [in, optional] {@code Object}
* @param Name [in, optional] {@code Object}
* @param Description [in, optional] {@code Object}
* @param MemberPropertyField [in, optional] {@code Object}
* @param WholeDayFilter [in, optional] {@code Object}
*/
@ComMethod(name = "Add2", dispId = 0xbee)
PivotFilter Add2(XlPivotFilterType Type,
Object DataField,
Object Value1,
Object Value2,
Object Order,
Object Name,
Object Description,
Object MemberPropertyField,
Object WholeDayFilter);
}
|
johnwilldonicely/LDAS
|
source/xf_expand1_f.c
|
<filename>source/xf_expand1_f.c
/*
<TAGS>signal_processing transform</TAGS>
[JRH] 23 November 2015
DESCRIPTION:
Expand a series of numbers so there are a user-defined number of elements [setn]
Data is duplicated as required
Alters input array
NAN values will be ignored, but INF will affect the results
USES:
- modifying different series of data so they are all the same length
- making an irregular matrix of data have rows all the same length
DEPENDENCY TREE:
No dependencies
ARGUMENTS:
double *data: input, array of numbers to be resampled
long nn: input, number of elements in data
long setn: input, the new number of elements requested for data
char *message : pre-allocated array to hold error message
RETURN VALUE:
Pointer to modified data array - NULL if memory allocation error occurs
SAMPLE CALL:
*/
#include <stdio.h>
#include <stdlib.h>
float *xf_expand1_f(float *data , long nn, long setn, char *message) {
char *thisfunc="xf_expand1_f\0";
int leftover_data;
long ii,jj,kk,n2,tot;
double binsize;
double sum;
if(nn==setn) return(data);
binsize= (double)nn/(double)setn;
data= realloc(data,setn*sizeof(*data));
if(data!=NULL) {
for(ii=(setn-1);ii>=0;ii--) data[ii]= data[((int)((double)ii*binsize))];
}
else {
sprintf(message,"%s [ERROR]: memory allocation error",thisfunc);
}
return (data);
}
|
KnightAndroid/wanandroid
|
library_util/src/main/java/com/knight/wanandroid/library_util/SystemUtils.java
|
package com.knight.wanandroid.library_util;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.BlendMode;
import android.graphics.BlendModeColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import com.knight.wanandroid.library_common.utils.CacheUtils;
import java.io.File;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
/**
* @author created by knight
* @organize wanandroid
* @Date 2021/4/2 14:56
* @descript:
*/
public class SystemUtils {
/**
*
* 隐藏软键盘
* @param activity
*/
public static void hideSoftKeyboard(Activity activity){
View view = activity.getCurrentFocus();
if(view != null){
InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
*
* 延迟显示软键盘
* @param view
*/
public static void showDelaySoftKeyBoard(View view){
new Handler(Looper.getMainLooper()).postDelayed(()->{
showSoftKeyBoard(view);
},500);
}
/**
*
* 显示软键盘
* @param view
*/
public static void showSoftKeyBoard(View view){
try {
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.RESULT_UNCHANGED_SHOWN);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,
InputMethodManager.HIDE_IMPLICIT_ONLY);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 监听输入框
* @param et
* @param tv
*/
public static void seteditTextChangeListener(EditText et, TextView tv){
et.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (!s.toString().equals("")) {
tv.setText("搜索");
} else {
tv.setText("取消");
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals("")) {
tv.setText("搜索");
} else {
tv.setText("取消");
}
}
});
}
/**
*
* 复制文本到剪切板
*/
public static void copyContent(Context context,String copyText) {
//获取剪贴板管理器:
ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
ClipData mClipData = ClipData.newPlainText("Label", copyText);
// 将ClipData内容放到系统剪贴板里。
cm.setPrimaryClip(mClipData);
}
/**
* 返回当前程序版本号
*/
public static long getAppVersionCode(Context context) {
long versioncode = 0;
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
versioncode = pi.getLongVersionCode();
} else {
versioncode = pi.versionCode;
}
} catch (Exception e) {
Log.e("VersionInfo", "Exception", e);
}
return versioncode;
}
/**
* 返回当前程序版本名
*/
public static String getAppVersionName(Context context) {
String versionName=null;
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
versionName = pi.versionName;
} catch (Exception e) {
Log.e("VersionInfo", "Exception", e);
}
return versionName;
}
/**
* 获取应用程序名称
*/
public static synchronized String getAppName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getString(labelRes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* 格式化长度
* @param files
* @return
*/
public static String formetFileSize(long files){
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (files == 0L) {
return wrongSize;
}
if (files < 1024) {
fileSizeString = df.format((double) files).toString() + "B";
} else if (files < 1048576) {
fileSizeString =df.format((double) files / 1024).toString() + "KB";
} else if (files < 1073741824) {
fileSizeString =df.format((double) files / 1048576).toString() + "MB";
} else {
fileSizeString = df.format((double) files / 1073741824).toString() + "GB";
}
return fileSizeString;
}
/**
*
* 安装apk
* @param apkFile
* @param context
*/
public static void installApk(File apkFile,Context context){
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
Uri fileUri = FileProvider.getUriForFile(context,context.getApplicationContext().getPackageName() + ".fileprovider",apkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(fileUri,context.getContentResolver().getType(fileUri));
context.startActivity(intent);
} else {
Uri uri = Uri.fromFile(apkFile);
intent.setAction(Intent.ACTION_VIEW);
// 指定数据和类型
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
/**
*
* 重启应用
* @param context
*/
public static void restartApp(Context context){
PackageManager packageManager = context.getPackageManager();
if (packageManager == null) {
return;
}
Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
/**
*
* 判断是什么模式
*/
public static void darkNormal() {
if (CacheUtils.getAutoNightMode()) {
int nightStartHour = Integer.valueOf(CacheUtils.getStartNightModeHour());
int nightStartMinute = Integer.valueOf(CacheUtils.getStartNightModeMinuter());
int dayStartHour = Integer.valueOf(CacheUtils.getStartDayModeHour());
int dayStartMinuter = Integer.valueOf(CacheUtils.getStartDayModeMinuter());
Calendar calendar = Calendar.getInstance();
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int nightValue = nightStartHour * 60 + nightStartMinute;
int dayValue = dayStartHour * 60 +dayStartMinuter;
int currentValue = currentHour * 60 + currentMinute;
if (currentValue >= nightValue || currentValue <= dayValue) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
CacheUtils.setNightModeStatus(true);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
CacheUtils.setNightModeStatus(false);
}
} else {
CacheUtils.setNightModeStatus(false);
if (CacheUtils.getFollowSystem()) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else {
if (CacheUtils.getNormalDark()) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
}
/**
*
* 设置颜色
* @param editText
* @param color
*/
public static void setCursorDrawableColor(EditText editText, int color) {
try {
Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
cursorDrawableResField.setAccessible(true);
int cursorDrawableRes = cursorDrawableResField.getInt(editText);
Field editorField = TextView.class.getDeclaredField("mEditor");
editorField.setAccessible(true);
Object editor = editorField.get(editText);
Class<?> clazz = editor.getClass();
Resources res = editText.getContext().getResources();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Field drawableForCursorField = clazz.getDeclaredField("mDrawableForCursor");
drawableForCursorField.setAccessible(true);
Drawable drawable = res.getDrawable(cursorDrawableRes,editText.getContext().getTheme());
drawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
drawableForCursorField.set(editor, drawable);
} else {
Field cursorDrawableField = clazz.getDeclaredField("mCursorDrawable");
cursorDrawableField.setAccessible(true);
Drawable[] drawables = new Drawable[2];
drawables[0] = ContextCompat.getDrawable(editText.getContext(),cursorDrawableRes);
drawables[1] = ContextCompat.getDrawable(editText.getContext(),cursorDrawableRes);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
drawables[0].setColorFilter(new BlendModeColorFilter(color, BlendMode.SRC_IN));
drawables[1].setColorFilter(new BlendModeColorFilter(color, BlendMode.SRC_IN));
} else {
drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
cursorDrawableField.set(editor, drawables);
}
} catch (Throwable t) {
}
}
/**
* 判断是否在主进程中,一些SDK中的PushServer可能运行在其他进程中。
* 也就会造成Application初始化两次,而只有在主进程中才需要初始化。
* * @return
*/
public static boolean isRunOnMainProcess(Context context) {
ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
String mainProcessName = context.getPackageName();
int myPid = android.os.Process.myPid();
for (ActivityManager.RunningAppProcessInfo info : processInfos) {
if (info.pid == myPid && mainProcessName.equals(info.processName)) {
return true;
}
}
return false;
}
/**
*
* 获取需要hook的activity
* @param context
*/
public static String getCheckActivityName(Context context,String checkActivity) {
PackageManager mPackageManager = context.getPackageManager();
String checkActivityName = "";
try {
ApplicationInfo appInfo = mPackageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
checkActivityName = appInfo.metaData.getString(checkActivity);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return checkActivityName;
}
/**
*
* 获取activity 名字
* @param name
* @return
*/
public static String getActivityName(String name,String checkActivityName) {
if (CacheUtils.getAgreeStatus()) {
return name;
} else {
setRealFirstActivityName(name);
return checkActivityName;
}
}
/**
*
* 原有真正打开的
*
*/
private static String realFirstActivityName = null;
/**
*
* 设置
* @param firstActivityName
*/
public static void setRealFirstActivityName(String firstActivityName) {
realFirstActivityName = firstActivityName;
}
/**
*
* 返回真正打开的第一个界面
* @return
*/
public static String getRealFirstActivityName() {
return realFirstActivityName;
}
}
|
chpatel3/coherence-cpp-extend-client
|
include/public/coherence/lang/cloneable_spec.hpp
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_CLONEABLE_SPEC_HPP
#define COH_CLONEABLE_SPEC_HPP
#include "coherence/lang/compatibility.hpp"
#include "coherence/lang/class_spec.hpp"
#include "coherence/lang/lang_spec.hpp"
#include "coherence/lang/TypedHandle.hpp"
#include "coherence/lang/TypedHolder.hpp"
COH_OPEN_NAMESPACE2(coherence,lang)
class Object;
/**
* Helper for defining a cloneable managed class.
*
* It addition to the features auto-generated by the class_spec<> helper template
* cloneable_spec<> auto-generates an implementation of "Object::Handle clone() const"
* which delegates to the defined classes const copy constructor.
*
* A normal cloneable class definition would be:
* @code
* class Foo
* : public cloneable_spec<Foo,
* extends<Bar>,
* implements<SomeInterface, SomeOtherInterface> >
* {
* // add support for auto-generated static create methods
* friend class factory<Foo>;
*
* protected:
* // Constructors are defined as protected, and access via
* // auto-generated create methods, with matching signatures
* Foo()
* : super() ...
* {
* }
*
* // Copy constructor
* Foo(const Foo& that)
* : super(that) ...
* {
* }
*
* public:
* // normal class definition....
* };
* @endcode
*
* @see extends
* @see implements
*
* @author mf 2008.07.14
*/
template<class T, class E = extends<Object>, class I = implements<> >
class COH_EXPORT_SPEC cloneable_spec
: public class_spec<T, E, I>
{
// ----- typedefs -------------------------------------------------------
public:
/**
* Specification definition
*/
typedef cloneable_spec this_spec;
/**
* Definition T's parent class
*/
typedef cloneable_spec super;
/**
* Definition of the spec's parent class
*/
typedef class_spec<T, E, I> super_spec;
// ----- constructors ---------------------------------------------------
protected:
/**
* Generate a set of proxy constructors matching the signatures of the
* parent class's constructors.
*
* NOTE: Compilation errors referencing this line likely indicate that
* class being defined by this spec makes calls a "super"
* constructor supplying a set of parameters for which there is
* no exact match on the parent class.
*/
COH_DEFINE_PROXY_CONSTRUCTORS(cloneable_spec)
public:
/**
* {@inheritDoc}
*/
virtual TypedHandle<Object> clone() const
{
return T::create(static_cast<const T&>(*this));
}
};
COH_CLOSE_NAMESPACE2
#endif // COH_CLONEABLE_SPEC_HPP
|
unverbraucht/cybergarage-upnp
|
core/src/main/java/org/cybergarage/soap/SOAPRequest.java
|
<gh_stars>100-1000
/******************************************************************
*
* CyberSOAP for Java
*
* Copyright (C) <NAME> 2002
*
* File: SOAPRequest.java
*
* Revision;
*
* 12/11/02
* - first revision.
* 02/13/04
* - <NAME> <<EMAIL>>, <NAME> <<EMAIL>>.
* - Added XML header, <?xml version=\"1.0\"?> to setContent().
* 05/11/04
* - Changed the XML header to <?xml version="1.0" encoding="utf-8"?> in setContent().
*
******************************************************************/
package org.cybergarage.soap;
import java.io.ByteArrayInputStream;
import org.cybergarage.http.HTTP;
import org.cybergarage.http.HTTPRequest;
import org.cybergarage.http.HTTPResponse;
import org.cybergarage.util.Debug;
import org.cybergarage.xml.Node;
import org.cybergarage.xml.Parser;
import org.cybergarage.xml.ParserException;
public class SOAPRequest extends HTTPRequest
{
private final static String SOAPACTION = "SOAPACTION";
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
public SOAPRequest()
{
setContentType(SOAP.CONTENT_TYPE);
setMethod(HTTP.POST);
}
public SOAPRequest(HTTPRequest httpReq)
{
set(httpReq);
}
////////////////////////////////////////////////
// SOAPACTION
////////////////////////////////////////////////
public void setSOAPAction(String action)
{
setStringHeader(SOAPACTION, action);
}
public String getSOAPAction()
{
return getStringHeaderValue(SOAPACTION);
}
public boolean isSOAPAction(String value)
{
String headerValue = getHeaderValue(SOAPACTION);
if (headerValue == null)
return false;
if (headerValue.equals(value) == true)
return true;
String soapAction = getSOAPAction();
if (soapAction == null)
return false;
return soapAction.equals(value);
}
////////////////////////////////////////////////
// post
////////////////////////////////////////////////
public SOAPResponse postMessage(String host, int port)
{
HTTPResponse httpRes = post(host, port);
SOAPResponse soapRes = new SOAPResponse(httpRes);
byte content[] = soapRes.getContent();
if (content.length <= 0)
return soapRes;
try {
ByteArrayInputStream byteIn = new ByteArrayInputStream(content);
Parser xmlParser = SOAP.getXMLParser();
Node rootNode = xmlParser.parse(byteIn);
soapRes.setEnvelopeNode(rootNode);
}
catch (Exception e) {
Debug.warning(e);
}
return soapRes;
}
////////////////////////////////////////////////
// Node
////////////////////////////////////////////////
private Node rootNode;
private void setRootNode(Node node)
{
rootNode = node;
}
private synchronized Node getRootNode()
{
if (rootNode != null)
return rootNode;
try {
byte content[] = getContent();
ByteArrayInputStream contentIn = new ByteArrayInputStream(content);
Parser parser = SOAP.getXMLParser();
rootNode = parser.parse(contentIn);
}
catch (ParserException e) {
Debug.warning(e);
}
return rootNode;
}
////////////////////////////////////////////////
// XML
////////////////////////////////////////////////
public void setEnvelopeNode(Node node)
{
setRootNode(node);
}
public Node getEnvelopeNode()
{
return getRootNode();
}
public Node getBodyNode()
{
Node envNode = getEnvelopeNode();
if (envNode == null)
return null;
if (envNode.hasNodes() == false)
return null;
return envNode.getNode(0);
}
////////////////////////////////////////////////
// XML Contents
////////////////////////////////////////////////
public void setContent(Node node)
{
// Thanks for <NAME> <<EMAIL>>, <NAME> <<EMAIL>>.
String conStr = "";
conStr += SOAP.VERSION_HEADER;
conStr += "\n";
conStr += node.toString();
setContent(conStr);
}
////////////////////////////////////////////////
// print
////////////////////////////////////////////////
public void print()
{
Debug.message(toString());
if (hasContent() == true)
return;
Node rootElem = getRootNode();
if (rootElem == null)
return;
Debug.message(rootElem.toString());
}
}
|
kmhughes/robotbrains-examples
|
data/cloud/scala/org.robotbrains.data.cloud.timeseries.server/src/main/scala/org/robotbrains/support/web/server/netty/NettyHttpResponse.java
|
<reponame>kmhughes/robotbrains-examples
/*
* Copyright (C) 2013 Google Inc.
* Copyright (C) 2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.robotbrains.support.web.server.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.codec.http.cookie.ServerCookieEncoder;
import io.smartspaces.SmartSpacesException;
import io.smartspaces.service.web.HttpResponseCode;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpCookie;
import java.util.Map;
import java.util.Set;
import org.robotbrains.support.web.server.HttpResponse;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
/**
* A Netty-based HttpResponse
*
* @author <NAME>
*/
public class NettyHttpResponse implements HttpResponse {
/**
* Create a Netty representation of a cookie.
*
* @param cookie
* the standard Java cookie
*
* @return the Netty cookie
*/
public static Cookie createNettyCookie(HttpCookie cookie) {
Cookie nettyCookie = new DefaultCookie(cookie.getName(), cookie.getValue());
nettyCookie.setDomain(cookie.getDomain());
nettyCookie.setMaxAge((int) cookie.getMaxAge());
nettyCookie.setPath(cookie.getPath());
nettyCookie.setSecure(cookie.getSecure());
return nettyCookie;
}
/**
* The Netty handler context.
*/
private ChannelHandlerContext ctx;
/**
* The channel buffer for writing content.
*/
private ByteBuf channelBuffer;
/**
* The output stream for writing on the channel buffer.
*/
private ByteBufOutputStream outputStream;
/**
* Content headers to add to the response.
*/
private Multimap<String, String> contentHeaders = HashMultimap.create();
/**
* The HTTP response code to be used for the response.
*/
private int responseCode = HttpResponseCode.OK;
/**
* The content type of the response.
*/
private String contentType;
/**
* Construct a new response.
*
* @param ctx
* the Netty context for the connection to the client
* @param extraHttpContentHeaders
* a map of content headers, can be {@code null}
*/
public NettyHttpResponse(ChannelHandlerContext ctx, Map<String, String> extraHttpContentHeaders) {
this.ctx = ctx;
channelBuffer = Unpooled.buffer();
if (extraHttpContentHeaders != null) {
for (String key : extraHttpContentHeaders.keySet()) {
contentHeaders.put(key, extraHttpContentHeaders.get(key));
}
}
}
/**
* Construct a new response.
*
* @param ctx
* the Netty context for the connection to the client
* @param extraHttpContentHeaders
* a multimap of content headers, can be {@code null}
*/
public NettyHttpResponse(ChannelHandlerContext ctx,
Multimap<String, String> extraHttpContentHeaders) {
this.ctx = ctx;
channelBuffer = Unpooled.buffer();
if (extraHttpContentHeaders != null) {
contentHeaders.putAll(extraHttpContentHeaders);
}
}
@Override
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
@Override
public int getResponseCode() {
return responseCode;
}
@Override
public void setContentType(String contentType) {
this.contentType = contentType;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public OutputStream getOutputStream() {
if (outputStream == null) {
outputStream = new ByteBufOutputStream(channelBuffer);
}
return outputStream;
}
@Override
public void addContentHeader(String name, String value) {
contentHeaders.put(name, value);
}
@Override
public void addContentHeaders(Multimap<String, String> headers) {
contentHeaders.putAll(headers);
}
@Override
public Multimap<String, String> getContentHeaders() {
return contentHeaders;
}
/**
* Get the channel buffer containing the response.
*
* <p>
* Once this is called, the output stream used for writing the response is
* closed.
*
* @return the channel buffer
*/
public ByteBuf getChannelBuffer() {
try {
if (outputStream != null) {
outputStream.flush();
}
} catch (IOException e) {
throw new SmartSpacesException("Could not flush HTTP dynamic output stream", e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
throw new SmartSpacesException("Could not close HTTP dynamic output stream", e);
}
}
}
return channelBuffer;
}
@Override
public void addCookie(HttpCookie cookie) {
contentHeaders.put("Set-Cookie", ServerCookieEncoder.STRICT.encode(createNettyCookie(cookie)));
}
@Override
public void addCookies(Set<HttpCookie> newCookies) {
if (newCookies == null) {
return;
}
contentHeaders.putAll("Set-Cookie", ServerCookieEncoder.STRICT.encode(Collections2.transform(
newCookies, new Function<HttpCookie, Cookie>() {
@Override
public Cookie apply(HttpCookie cookie) {
return createNettyCookie(cookie);
}
})));
}
}
|
statful/statful-client-java
|
core/src/main/java/com/statful/client/core/api/ConfigurationBuilder.java
|
<reponame>statful/statful-client-java
package com.statful.client.core.api;
import com.statful.client.core.config.DefaultClientConfiguration;
import com.statful.client.domain.api.ClientConfiguration;
import com.statful.client.domain.api.Tags;
import com.statful.client.domain.api.Transport;
/**
* This is a {@link com.statful.client.domain.api.ClientConfiguration} builder which allows to chain a
* <code>T</code> type to return <code>T</code> upon build.
* <p>
* This class allows to wrap a {@link ConfigurationBuilderChain}
* which in sequence returns an instance to a <code>T</code> that can use the build
* {@link ConfigurationBuilder} as an argument.
*
* @param <T> The type to return upon build
*/
public final class ConfigurationBuilder<T> {
private DefaultClientConfiguration result;
private ConfigurationBuilderChain<T> builderChain;
private ConfigurationBuilder() {
this.result = new DefaultClientConfiguration();
}
/**
* Private default constructor.
*
* @param builderChain The {@link ConfigurationBuilderChain} of <code>T</code>.
*/
private ConfigurationBuilder(final ConfigurationBuilderChain<T> builderChain) {
this.result = new DefaultClientConfiguration();
this.builderChain = builderChain;
}
/**
* Creates a new instance of {@link ConfigurationBuilder} of <code>T</code>.
*
* @param <T> The type to return upon build
* @return An instance of {@link ConfigurationBuilder}
*/
static <T> ConfigurationBuilder<T> newBuilder() {
return new ConfigurationBuilder<T>();
}
/**
* Creates a new instance of {@link ConfigurationBuilder} with the passed
* {@link ConfigurationBuilderChain} of <code>T</code>.
*
* @param builderChain A {@link ConfigurationBuilderChain} of <code>T</code>
* @param <T> A T type
* @return A {@link ConfigurationBuilder} of <code>T</code>
*/
public static <T> ConfigurationBuilder<T> newBuilder(final ConfigurationBuilderChain<T> builderChain) {
return new ConfigurationBuilder<>(builderChain);
}
/**
* Sets the host.
*
* @param host The hostname
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> host(final String host) {
if (isStringSafe(host)) {
this.result.setHost(host);
}
return this;
}
/**
* Sets the port.
*
* @param port The port number
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> port(final int port) {
this.result.setPort(port);
return this;
}
/**
* Sets the path.
*
* @param path The path
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> path(final String path) {
this.result.setPath(path);
return this;
}
/**
* Sets the transport.
*
* @param transport The transport type
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> transport(final Transport transport) {
if (transport != null) {
this.result.setTransport(transport);
}
return this;
}
/**
* Sets the application token
*
* @param token The token
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> token(final String token) {
if (isStringSafe(token)) {
this.result.setToken(token);
}
return this;
}
/**
* Sets the application name.
*
* @param app The application name
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> app(final String app) {
if (isStringSafe(app)) {
this.result.setApp(app);
}
return this;
}
/**
* Sets if telemetry is running in dry mode.
*
* @param isDryRun Boolean to set dry run
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> isDryRun(final boolean isDryRun) {
this.result.setDryRun(isDryRun);
return this;
}
/**
* Sets the number of workers to process the telemetry.
*
* @param workersPoolSize The size of the pool as integer
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> workerPoolSize(final int workersPoolSize) {
this.result.setWorkersPoolSize(workersPoolSize);
return this;
}
/**
* Sets the flag to use HTTP or HTTPS
*
* @param secure The flag to set if the transport should be secure
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> secure(final boolean secure) {
this.result.setSecure(secure);
return this;
}
/**
* Sets the connection pool size for TCP based transports.
*
* @param connectPoolSize The connections pool size
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> connectionPoolSize(final int connectPoolSize) {
this.result.setConnectionPoolSize(connectPoolSize);
return this;
}
/**
* Sets the connection timeout for TCP based transports.
*
* @param connectTimeoutMs The connection timeout in milliseconds
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> connectionTimeoutMs(final int connectTimeoutMs) {
this.result.setConnectTimeoutMillis(connectTimeoutMs);
return this;
}
/**
* Sets the socket timeout for TCP based transports.
*
* @param socketTimeoutMs The socket timeout in milliseconds
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> timeoutMs(final int socketTimeoutMs) {
this.result.setSocketTimeoutMillis(socketTimeoutMs);
return this;
}
/**
* Sets the metrics namespace.
*
* @param namespace The namespace
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> namespace(final String namespace) {
if (isStringSafe(namespace)) {
this.result.setNamespace(namespace);
}
return this;
}
/**
* Sets the global tags to use.
*
* @param type The tag type
* @param value The tag value
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> tag(final String type, final String value) {
if (!Tags.isEmptyOrNull(type, value)) {
this.result.mergeApplicationTag(type, value);
}
return this;
}
/**
* Sets the global sample rate.
*
* @param sampleRate The sample rate as integer
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> sampleRate(final int sampleRate) {
this.result.setSampleRate(sampleRate);
return this;
}
/**
* Sets the flush size in number of metrics.
*
* @param flushSize The flush size as integer
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> flushSize(final int flushSize) {
this.result.setFlushSize(flushSize);
return this;
}
/**
* Sets the flush interval in milliseconds.
*
* @param flushInterval The flush interval as long
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> flushInterval(final long flushInterval) {
this.result.setFlushIntervalMillis(flushInterval);
return this;
}
/**
* Sets the timer method default tags.
* <p>
* Example: <code>timer(tag("host", "localhost"), tag("cluster", production)).</code>
*
* @param tagBuilders An array of {@link TagBuilder} to use, which can be imported statically
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> timer(final TagBuilder... tagBuilders) {
if (tagBuilders != null) {
for (TagBuilder tagBuilder : tagBuilders) {
this.result.mergeTimerTag(tagBuilder.getType(), tagBuilder.getValue());
}
}
return this;
}
/**
* Sets the timer method default aggregations.
* <p>
* Example: <code>timer(agg(AVG), agg(LAST)).</code>
*
* @param aggregationBuilders An array of {@link AggregationBuilder} to use, which can be imported statically
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> timer(final AggregationBuilder... aggregationBuilders) {
if (aggregationBuilders != null) {
for (AggregationBuilder aggregationBuilder : aggregationBuilders) {
this.result.mergeTimerAggregation(aggregationBuilder.getAggregation());
}
}
return this;
}
/**
* Sets the timer method default aggregation frequency.
* <p>
* Example: <code>timer(aggregationFrequency(FREQ_120)).</code>
*
* @param aggregationFreqBuilder An {@link AggregationFreqBuilder}
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> timer(final AggregationFreqBuilder aggregationFreqBuilder) {
if (aggregationFreqBuilder != null) {
this.result.setTimerAggregationFrequency(aggregationFreqBuilder.getAggFreq());
}
return this;
}
/**
* Sets the counter method default tags.
* <p>
* Example: <code>counter(tag("host", "localhost"), tag("cluster", production)).</code>
*
* @param tagBuilders An array of {@link TagBuilder} to use, which can be imported statically
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> counter(final TagBuilder... tagBuilders) {
if (tagBuilders != null) {
for (TagBuilder tagBuilder : tagBuilders) {
this.result.mergeCounterTag(tagBuilder.getType(), tagBuilder.getValue());
}
}
return this;
}
/**
* Sets the counter method default aggregations.
* <p>
* Example: <code>counter(agg(AVG), agg(LAST)).</code>
*
* @param aggregationBuilders An array of {@link AggregationBuilder} to use, which can be imported statically
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> counter(final AggregationBuilder... aggregationBuilders) {
if (aggregationBuilders != null) {
for (AggregationBuilder aggregationBuilder : aggregationBuilders) {
this.result.mergeCounterAggregation(aggregationBuilder.getAggregation());
}
}
return this;
}
/**
* Sets the counter method default aggregation frequency.
* <p>
* Example: <code>counter(aggregationFrequency(FREQ_120)).</code>
*
* @param aggregationFreqBuilder An {@link AggregationFreqBuilder}
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> counter(final AggregationFreqBuilder aggregationFreqBuilder) {
if (aggregationFreqBuilder != null) {
this.result.setCounterAggregationFrequency(aggregationFreqBuilder.getAggFreq());
}
return this;
}
/**
* Sets the gauge method default tags.
* <p>
* Example: gauge(tag("host", "localhost"), tag("cluster", production)).
*
* @param tagBuilders An array of {@link TagBuilder} to use, which can be imported statically
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> gauge(final TagBuilder... tagBuilders) {
if (tagBuilders != null) {
for (TagBuilder tagBuilder : tagBuilders) {
this.result.mergeGaugeTag(tagBuilder.getType(), tagBuilder.getValue());
}
}
return this;
}
/**
* Sets the gauge method default aggregations.
* <p>
* Example: <code>gauge(agg(AVG), agg(LAST)).</code>
*
* @param aggregationBuilders An array of {@link AggregationBuilder} to use, which can be imported statically
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> gauge(final AggregationBuilder... aggregationBuilders) {
if (aggregationBuilders != null) {
for (AggregationBuilder aggregationBuilder : aggregationBuilders) {
this.result.mergeGaugeAggregation(aggregationBuilder.getAggregation());
}
}
return this;
}
/**
* Sets the gauge method default aggregation frequency. Example: gauge(aggregationFrequency(FREQ_120)).
*
* @param aggregationFreqBuilder An {@link AggregationFreqBuilder}
* @return A reference to this configuration builder
*/
public ConfigurationBuilder<T> gauge(final AggregationFreqBuilder aggregationFreqBuilder) {
if (aggregationFreqBuilder != null) {
this.result.setGaugeAggregationFrequency(aggregationFreqBuilder.getAggFreq());
}
return this;
}
/**
* Builds the configuration and passed it to the {@link ConfigurationBuilderChain}
* of type <code>T</code>.
*
* @return An instance of <code>T</code>
*/
public T build() {
return builderChain.build(this.buildConfiguration());
}
/**
* Returns the {@link com.statful.client.domain.api.ClientConfiguration} to be passed to the
* {@link ConfigurationBuilderChain}.
*
* @return The {@link com.statful.client.domain.api.ClientConfiguration}
*/
ClientConfiguration buildConfiguration() {
if (!result.isValid()) {
throw new IllegalStateException("Configuration is not valid. Transport must be defined");
}
return this.result;
}
private boolean isStringSafe(final String string) {
return string != null && !string.isEmpty();
}
}
|
CalmDownsy/TestPlatform
|
ulpay-platform/src/main/java/com/ulpay/testplatform/common/enums/MessageType.java
|
<filename>ulpay-platform/src/main/java/com/ulpay/testplatform/common/enums/MessageType.java<gh_stars>1-10
package com.ulpay.testplatform.common.enums;
import com.ulpay.testplatform.handler.message.BaseMessageParseHandler;
import com.ulpay.testplatform.handler.message.JsonMessageParseHandler;
import com.ulpay.testplatform.handler.message.XmlMessageParseHandler;
/**
* @author zhangsy
*/
public enum MessageType {
/**
* xml
*/
XML("1", XmlMessageParseHandler.getInstance()),
/**
* json
*/
JSON("2", JsonMessageParseHandler.getInstance()),
/**
* url
*/
URL("3", null),
/**
* javabean 暂时也使用json处理器
*/
JAVABEAN("4", JsonMessageParseHandler.getInstance());
private String code;
private BaseMessageParseHandler msgHandler;
MessageType(String code, BaseMessageParseHandler msgHandler) {
this.code = code;
this.msgHandler = msgHandler;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public BaseMessageParseHandler getMsgHandler() {
return msgHandler;
}
public void setMsgHandler(BaseMessageParseHandler msgHandler) {
this.msgHandler = msgHandler;
}
public static BaseMessageParseHandler getMsgHandler(String msgType) {
for (MessageType messageType : values()) {
if (msgType.equals(messageType.getCode())) {
return messageType.getMsgHandler();
}
}
return null;
}
}
|
Wzzzx/chromium-crosswalk
|
content/browser/frame_host/frame_tree.cc
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/frame_host/frame_tree.h"
#include <stddef.h>
#include <queue>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/memory/ptr_util.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/navigator.h"
#include "content/browser/frame_host/render_frame_host_factory.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/frame_host/render_frame_proxy_host.h"
#include "content/browser/renderer_host/render_view_host_factory.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/common/content_switches_internal.h"
#include "content/common/input_messages.h"
#include "content/common/site_isolation_policy.h"
#include "third_party/WebKit/public/web/WebSandboxFlags.h"
namespace content {
namespace {
// Helper function to collect SiteInstances involved in rendering a single
// FrameTree (which is a subset of SiteInstances in main frame's proxy_hosts_
// because of openers).
std::set<SiteInstance*> CollectSiteInstances(FrameTree* tree) {
std::set<SiteInstance*> instances;
for (FrameTreeNode* node : tree->Nodes())
instances.insert(node->current_frame_host()->GetSiteInstance());
return instances;
}
} // namespace
FrameTree::NodeIterator::NodeIterator(const NodeIterator& other) = default;
FrameTree::NodeIterator::~NodeIterator() {}
FrameTree::NodeIterator& FrameTree::NodeIterator::operator++() {
for (size_t i = 0; i < current_node_->child_count(); ++i) {
FrameTreeNode* child = current_node_->child_at(i);
if (child == node_to_skip_)
continue;
queue_.push(child);
}
if (!queue_.empty()) {
current_node_ = queue_.front();
queue_.pop();
} else {
current_node_ = nullptr;
}
return *this;
}
bool FrameTree::NodeIterator::operator==(const NodeIterator& rhs) const {
return current_node_ == rhs.current_node_;
}
FrameTree::NodeIterator::NodeIterator(FrameTreeNode* starting_node,
FrameTreeNode* node_to_skip)
: current_node_(starting_node != node_to_skip ? starting_node : nullptr),
node_to_skip_(node_to_skip) {}
FrameTree::NodeIterator FrameTree::NodeRange::begin() {
return NodeIterator(root_, node_to_skip_);
}
FrameTree::NodeIterator FrameTree::NodeRange::end() {
return NodeIterator(nullptr, nullptr);
}
FrameTree::NodeRange::NodeRange(FrameTreeNode* root,
FrameTreeNode* node_to_skip)
: root_(root), node_to_skip_(node_to_skip) {}
FrameTree::FrameTree(Navigator* navigator,
RenderFrameHostDelegate* render_frame_delegate,
RenderViewHostDelegate* render_view_delegate,
RenderWidgetHostDelegate* render_widget_delegate,
RenderFrameHostManager::Delegate* manager_delegate)
: render_frame_delegate_(render_frame_delegate),
render_view_delegate_(render_view_delegate),
render_widget_delegate_(render_widget_delegate),
manager_delegate_(manager_delegate),
root_(new FrameTreeNode(this,
navigator,
render_frame_delegate,
render_widget_delegate,
manager_delegate,
nullptr,
// The top-level frame must always be in a
// document scope.
blink::WebTreeScopeType::Document,
std::string(),
std::string(),
blink::WebFrameOwnerProperties())),
focused_frame_tree_node_id_(-1),
load_progress_(0.0) {}
FrameTree::~FrameTree() {
delete root_;
root_ = nullptr;
}
FrameTreeNode* FrameTree::FindByID(int frame_tree_node_id) {
for (FrameTreeNode* node : Nodes()) {
if (node->frame_tree_node_id() == frame_tree_node_id)
return node;
}
return nullptr;
}
FrameTreeNode* FrameTree::FindByRoutingID(int process_id, int routing_id) {
RenderFrameHostImpl* render_frame_host =
RenderFrameHostImpl::FromID(process_id, routing_id);
if (render_frame_host) {
FrameTreeNode* result = render_frame_host->frame_tree_node();
if (this == result->frame_tree())
return result;
}
RenderFrameProxyHost* render_frame_proxy_host =
RenderFrameProxyHost::FromID(process_id, routing_id);
if (render_frame_proxy_host) {
FrameTreeNode* result = render_frame_proxy_host->frame_tree_node();
if (this == result->frame_tree())
return result;
}
return nullptr;
}
FrameTreeNode* FrameTree::FindByName(const std::string& name) {
if (name.empty())
return root_;
for (FrameTreeNode* node : Nodes()) {
if (node->frame_name() == name)
return node;
}
return nullptr;
}
FrameTree::NodeRange FrameTree::Nodes() {
return NodesExcept(nullptr);
}
FrameTree::NodeRange FrameTree::SubtreeNodes(FrameTreeNode* subtree_root) {
return NodeRange(subtree_root, nullptr);
}
FrameTree::NodeRange FrameTree::NodesExcept(FrameTreeNode* node_to_skip) {
return NodeRange(root_, node_to_skip);
}
bool FrameTree::AddFrame(
FrameTreeNode* parent,
int process_id,
int new_routing_id,
blink::WebTreeScopeType scope,
const std::string& frame_name,
const std::string& frame_unique_name,
blink::WebSandboxFlags sandbox_flags,
const blink::WebFrameOwnerProperties& frame_owner_properties) {
CHECK_NE(new_routing_id, MSG_ROUTING_NONE);
// A child frame always starts with an initial empty document, which means
// it is in the same SiteInstance as the parent frame. Ensure that the process
// which requested a child frame to be added is the same as the process of the
// parent node.
if (parent->current_frame_host()->GetProcess()->GetID() != process_id)
return false;
// AddChild is what creates the RenderFrameHost.
FrameTreeNode* added_node = parent->AddChild(
base::WrapUnique(new FrameTreeNode(
this, parent->navigator(), render_frame_delegate_,
render_widget_delegate_, manager_delegate_, parent, scope, frame_name,
frame_unique_name, frame_owner_properties)),
process_id, new_routing_id);
// Set sandbox flags and make them effective immediately, since initial
// sandbox flags should apply to the initial empty document in the frame.
added_node->SetPendingSandboxFlags(sandbox_flags);
added_node->CommitPendingSandboxFlags();
// Now that the new node is part of the FrameTree and has a RenderFrameHost,
// we can announce the creation of the initial RenderFrame which already
// exists in the renderer process.
added_node->current_frame_host()->SetRenderFrameCreated(true);
return true;
}
void FrameTree::RemoveFrame(FrameTreeNode* child) {
FrameTreeNode* parent = child->parent();
if (!parent) {
NOTREACHED() << "Unexpected RemoveFrame call for main frame.";
return;
}
parent->RemoveChild(child);
}
void FrameTree::CreateProxiesForSiteInstance(
FrameTreeNode* source,
SiteInstance* site_instance) {
// Create the RenderFrameProxyHost for the new SiteInstance.
if (!source || !source->IsMainFrame()) {
RenderViewHostImpl* render_view_host = GetRenderViewHost(site_instance);
if (!render_view_host) {
root()->render_manager()->CreateRenderFrameProxy(site_instance);
} else {
root()->render_manager()->EnsureRenderViewInitialized(render_view_host,
site_instance);
}
}
// Proxies are created in the FrameTree in response to a node navigating to a
// new SiteInstance. Since |source|'s navigation will replace the currently
// loaded document, the entire subtree under |source| will be removed.
for (FrameTreeNode* node : NodesExcept(source)) {
// If a new frame is created in the current SiteInstance, other frames in
// that SiteInstance don't need a proxy for the new frame.
SiteInstance* current_instance =
node->render_manager()->current_frame_host()->GetSiteInstance();
if (current_instance != site_instance)
node->render_manager()->CreateRenderFrameProxy(site_instance);
}
}
RenderFrameHostImpl* FrameTree::GetMainFrame() const {
return root_->current_frame_host();
}
FrameTreeNode* FrameTree::GetFocusedFrame() {
return FindByID(focused_frame_tree_node_id_);
}
void FrameTree::SetFocusedFrame(FrameTreeNode* node, SiteInstance* source) {
if (node == GetFocusedFrame())
return;
std::set<SiteInstance*> frame_tree_site_instances =
CollectSiteInstances(this);
SiteInstance* current_instance =
node->current_frame_host()->GetSiteInstance();
// Update the focused frame in all other SiteInstances. If focus changes to
// a cross-process frame, this allows the old focused frame's renderer
// process to clear focus from that frame and fire blur events. It also
// ensures that the latest focused frame is available in all renderers to
// compute document.activeElement.
//
// We do not notify the |source| SiteInstance because it already knows the
// new focused frame (since it initiated the focus change), and we notify the
// new focused frame's SiteInstance (if it differs from |source|) separately
// below.
for (const auto& instance : frame_tree_site_instances) {
if (instance != source && instance != current_instance) {
DCHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
RenderFrameProxyHost* proxy =
node->render_manager()->GetRenderFrameProxyHost(instance);
proxy->SetFocusedFrame();
}
}
// If |node| was focused from a cross-process frame (i.e., via
// window.focus()), tell its RenderFrame that it should focus.
if (current_instance != source)
node->current_frame_host()->SetFocusedFrame();
focused_frame_tree_node_id_ = node->frame_tree_node_id();
node->DidFocus();
// The accessibility tree data for the root of the frame tree keeps
// track of the focused frame too, so update that every time the
// focused frame changes.
root()->current_frame_host()->UpdateAXTreeData();
}
void FrameTree::SetFrameRemoveListener(
const base::Callback<void(RenderFrameHost*)>& on_frame_removed) {
on_frame_removed_ = on_frame_removed;
}
RenderViewHostImpl* FrameTree::CreateRenderViewHost(
SiteInstance* site_instance,
int32_t routing_id,
int32_t main_frame_routing_id,
bool swapped_out,
bool hidden) {
RenderViewHostMap::iterator iter =
render_view_host_map_.find(site_instance->GetId());
if (iter != render_view_host_map_.end())
return iter->second;
RenderViewHostImpl* rvh =
static_cast<RenderViewHostImpl*>(RenderViewHostFactory::Create(
site_instance, render_view_delegate_, render_widget_delegate_,
routing_id, main_frame_routing_id, swapped_out, hidden));
render_view_host_map_[site_instance->GetId()] = rvh;
return rvh;
}
RenderViewHostImpl* FrameTree::GetRenderViewHost(SiteInstance* site_instance) {
RenderViewHostMap::iterator iter =
render_view_host_map_.find(site_instance->GetId());
if (iter != render_view_host_map_.end())
return iter->second;
return nullptr;
}
void FrameTree::AddRenderViewHostRef(RenderViewHostImpl* render_view_host) {
SiteInstance* site_instance = render_view_host->GetSiteInstance();
RenderViewHostMap::iterator iter =
render_view_host_map_.find(site_instance->GetId());
CHECK(iter != render_view_host_map_.end());
CHECK(iter->second == render_view_host);
iter->second->increment_ref_count();
}
void FrameTree::ReleaseRenderViewHostRef(RenderViewHostImpl* render_view_host) {
SiteInstance* site_instance = render_view_host->GetSiteInstance();
int32_t site_instance_id = site_instance->GetId();
RenderViewHostMap::iterator iter =
render_view_host_map_.find(site_instance_id);
CHECK(iter != render_view_host_map_.end());
CHECK_EQ(iter->second, render_view_host);
// Decrement the refcount and shutdown the RenderViewHost if no one else is
// using it.
CHECK_GT(iter->second->ref_count(), 0);
iter->second->decrement_ref_count();
if (iter->second->ref_count() == 0) {
iter->second->ShutdownAndDestroy();
render_view_host_map_.erase(iter);
}
}
void FrameTree::FrameRemoved(FrameTreeNode* frame) {
if (frame->frame_tree_node_id() == focused_frame_tree_node_id_)
focused_frame_tree_node_id_ = -1;
// No notification for the root frame.
if (!frame->parent()) {
CHECK_EQ(frame, root_);
return;
}
// Notify observers of the frame removal.
if (!on_frame_removed_.is_null())
on_frame_removed_.Run(frame->current_frame_host());
}
void FrameTree::UpdateLoadProgress() {
double progress = 0.0;
ProgressBarCompletion completion = GetProgressBarCompletionPolicy();
int frame_count = 0;
switch (completion) {
case ProgressBarCompletion::DOM_CONTENT_LOADED:
case ProgressBarCompletion::RESOURCES_BEFORE_DCL:
if (root_->has_started_loading())
progress = root_->loading_progress();
break;
case ProgressBarCompletion::LOAD_EVENT:
for (FrameTreeNode* node : Nodes()) {
// Ignore the current frame if it has not started loading.
if (!node->has_started_loading())
continue;
progress += node->loading_progress();
frame_count++;
}
break;
case ProgressBarCompletion::RESOURCES_BEFORE_DCL_AND_SAME_ORIGIN_IFRAMES:
for (FrameTreeNode* node : Nodes()) {
// Ignore the current frame if it has not started loading,
// if the frame is cross-origin, or about:blank.
if (!node->has_started_loading() || !node->HasSameOrigin(*root_) ||
node->current_url() == GURL(url::kAboutBlankURL))
continue;
progress += node->loading_progress();
frame_count++;
}
break;
default:
NOTREACHED();
}
if (frame_count != 0)
progress /= frame_count;
if (progress <= load_progress_)
return;
load_progress_ = progress;
// Notify the WebContents.
root_->navigator()->GetDelegate()->DidChangeLoadProgress();
}
void FrameTree::ResetLoadProgress() {
for (FrameTreeNode* node : Nodes())
node->reset_loading_progress();
load_progress_ = 0.0;
}
bool FrameTree::IsLoading() const {
for (const FrameTreeNode* node : const_cast<FrameTree*>(this)->Nodes()) {
if (node->IsLoading())
return true;
}
return false;
}
void FrameTree::ReplicatePageFocus(bool is_focused) {
std::set<SiteInstance*> frame_tree_site_instances =
CollectSiteInstances(this);
// Send the focus update to main frame's proxies in all SiteInstances of
// other frames in this FrameTree. Note that the main frame might also know
// about proxies in SiteInstances for frames in a different FrameTree (e.g.,
// for window.open), so we can't just iterate over its proxy_hosts_ in
// RenderFrameHostManager.
for (const auto& instance : frame_tree_site_instances)
SetPageFocus(instance, is_focused);
}
void FrameTree::SetPageFocus(SiteInstance* instance, bool is_focused) {
RenderFrameHostManager* root_manager = root_->render_manager();
// This is only used to set page-level focus in cross-process subframes, and
// requests to set focus in main frame's SiteInstance are ignored.
if (instance != root_manager->current_frame_host()->GetSiteInstance()) {
RenderFrameProxyHost* proxy =
root_manager->GetRenderFrameProxyHost(instance);
proxy->Send(new InputMsg_SetFocus(proxy->GetRoutingID(), is_focused));
}
}
} // namespace content
|
21tretiak0101/briana-crm
|
briana-server/src/main/java/by/ttre16/briana/service/EventService.java
|
<filename>briana-server/src/main/java/by/ttre16/briana/service/EventService.java
package by.ttre16.briana.service;
import by.ttre16.briana.entity.Event;
import by.ttre16.briana.repository.EventRepository;
import by.ttre16.briana.transport.mapper.EventMapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import static org.slf4j.LoggerFactory.getLogger;
@Service
@NoArgsConstructor
@AllArgsConstructor
public class EventService {
private EventRepository eventRepository;
private EventMapper eventMapper;
private static final Logger log = getLogger(EventService.class);
@Transactional(propagation = Propagation.SUPPORTS)
// @MessageMapping("/chat")
// @SendTo("/topic/messages")
public void push(Event event) {
/* Event savedEvent = eventRepository.save(event);
log.info("pushing event: {}", savedEvent.getMessage());
return eventMapper.toDto(savedEvent);*/
}
}
|
FationSH/MinusXL
|
MinusXL source code/minusXL_view/NewWorkbookWindow.java
|
package minusXL_view;
import minusXL_data_management.*;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class NewWorkbookWindow extends JDialog {
private static final long serialVersionUID = 1L;
private JTextField nameTextField;
/**
* Create the dialog.
*/
public NewWorkbookWindow() {
createWorkbookDialogWindow();
}
public void createWorkbookDialogWindow() {
setFont(new Font("Dialog", Font.PLAIN, 12));
setModal(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("New workbook");
setBounds(100, 100, 440, 120);
getContentPane().setLayout(null);
JLabel lblWorkbookName = new JLabel("Workbook name:");
lblWorkbookName.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblWorkbookName.setBounds(10, 11, 404, 14);
getContentPane().add(lblWorkbookName);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
}
});
btnCancel.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnCancel.setBounds(325, 47, 89, 23);
getContentPane().add(btnCancel);
JButton btnCreate = new JButton("Create");
btnCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String nameTextFieldValue = nameTextField.getText();
if (nameTextFieldValue.isEmpty()) {
nameTextFieldValue = "MinusXL Workbook"; // default name if the user does not give input
}
setVisible(false);
Workbook myNewWorkbook = new Workbook(nameTextFieldValue);
NewWorkbook myWorkbook = new NewWorkbook();
myWorkbook.createWorkbookWindow(myNewWorkbook); // Workbook
}
});
btnCreate.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnCreate.setBounds(226, 47, 89, 23);
getContentPane().add(btnCreate);
nameTextField = new JTextField();
nameTextField.setFont(new Font("Tahoma", Font.PLAIN, 11));
nameTextField.setBounds(98, 8, 316, 20);
getContentPane().add(nameTextField);
nameTextField.setColumns(10);
}
}
|
wachunga/ui-demo
|
tools/babel/index.js
|
// All babel config needs to be in one file, since babel caching mechanism won't check other "require"d modules/file
const packageRoots = require('../../lerna.json').packages;
const plugins = [
['@babel/plugin-proposal-decorators', { legacy: true }],
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-proposal-object-rest-spread',
['@quickbaseoss/babel-plugin-styled-components-css-namespace', { rawCssNamespace: '&&&&' }],
'babel-plugin-styled-components',
];
const envConfigs = {
development: {
loose: true,
modules: false,
targets: {
chrome: 59,
},
},
production: {
loose: true,
modules: false,
targets: {
browsers: ['last 2 versions', 'safari >= 7'],
ie: 11,
},
},
test: { targets: { node: 'current' } },
};
module.exports = function babelConfig(api) {
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development';
// console.log(`\nbabel env: ${env}`);
api.cache(() => env);
const resultPlugins = plugins.slice();
if (env === 'test') {
resultPlugins.push('babel-plugin-require-context-hook', 'dynamic-import-node-babel-7');
}
const resultEnvConfig = envConfigs[env];
return {
// need to explicitly define package roots that need to be transpiled,
// otherwise babel will transpile only current package files
// more info: https://babeljs.io/docs/en/options#babelrcroots
babelrcRoots: packageRoots.map(p => `${__dirname}/../../${p}`),
presets: ['@babel/preset-typescript', ['@babel/preset-env', resultEnvConfig], '@babel/preset-react'],
plugins: resultPlugins,
};
};
|
varuntiwari27/rally
|
tests/unit/plugins/openstack/scenarios/zaqar/test_basic.py
|
# Copyright (c) 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from rally.plugins.openstack.scenarios.zaqar import basic
from tests.unit import test
BASE = "rally.plugins.openstack.scenarios.zaqar."
BASIC = BASE + "basic.ZaqarBasic."
class ZaqarBasicTestCase(test.ScenarioTestCase):
@mock.patch(BASIC + "generate_random_name", return_value="fizbit")
def test_create_queue(self, mock_generate_random_name):
scenario = basic.ZaqarBasic(self.context)
scenario._queue_create = mock.MagicMock()
scenario.create_queue(fakearg="fake")
scenario._queue_create.assert_called_once_with(fakearg="fake")
@mock.patch(BASIC + "generate_random_name", return_value="kitkat")
def test_producer_consumer(self, mock_generate_random_name):
scenario = basic.ZaqarBasic(self.context)
messages = [{"body": {"id": idx}, "ttl": 360} for idx
in range(20)]
queue = mock.MagicMock()
scenario._queue_create = mock.MagicMock(return_value=queue)
scenario._messages_post = mock.MagicMock()
scenario._messages_list = mock.MagicMock()
scenario._queue_delete = mock.MagicMock()
scenario.producer_consumer(min_msg_count=20, max_msg_count=20,
fakearg="fake")
scenario._queue_create.assert_called_once_with(fakearg="fake")
scenario._messages_post.assert_called_once_with(queue, messages,
20, 20)
scenario._messages_list.assert_called_once_with(queue)
scenario._queue_delete.assert_called_once_with(queue)
|
devium/argentum
|
argentum-api/api/models/config.py
|
from django.db import models
from rest_framework import serializers, viewsets, mixins
from rest_framework.filters import OrderingFilter
class Config(models.Model):
key = models.CharField(max_length=32, unique=True)
value = models.CharField(max_length=32)
def __str__(self):
return f'Config(id={self.id},key="{self.key}",value="{self.value}")'
class ConfigSerializer(serializers.ModelSerializer):
class Meta:
model = Config
fields = ['id', 'key', 'value']
read_only_fields = ['key']
class ConfigViewSet(
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet
):
queryset = Config.objects.all()
serializer_class = ConfigSerializer
filter_backends = (OrderingFilter,)
ordering = ('id',)
|
booknu/study-refactoring-book
|
martin-fowler-refactoring-2nd/test/chp10/ReplaceNestedConditionalwithGuardClauses2.test.js
|
<filename>martin-fowler-refactoring-2nd/test/chp10/ReplaceNestedConditionalwithGuardClauses2.test.js
import {expect} from 'chai';
import {adjustedCapital} from '../../src/chp10/ReplaceNestedConditionalwithGuardClauses2'
describe('adjustedCapital', () => {
it('give 0 adjusted capital if capital is 0 or less than 0', () => {
expect(adjustedCapital({capital: 0})).to.equal(0);
expect(adjustedCapital({capital: -1})).to.equal(0);
});
it('give 0 adjusted capital if interestRate is 0 or less than 0', () => {
expect(adjustedCapital({capital: 1, interestRate: 0})).to.equal(0);
expect(adjustedCapital({capital: 1, interestRate: -1})).to.equal(0);
});
it('give 0 adjusted capital if duration is 0 or less than 0', () => {
expect(adjustedCapital({capital: 1, interestRate: 0, duration: 0})).to.equal(0);
expect(adjustedCapital({capital: 1, interestRate: 1, duration: -1})).to.equal(0);
});
it('calculate adjusted capital when capital, interestRate and duration are greater than 0', () => {
expect(adjustedCapital({capital: 1, interestRate: 1, duration: 1, income: 1, adjustmentFactor: 1})).to.equal(1);
expect(adjustedCapital({capital: 1, interestRate: 1, duration: 1, income: 2, adjustmentFactor: 2})).to.equal(4);
});
});
|
moneytech/skift
|
kernel/device/zero.c
|
<filename>kernel/device/zero.c
/* Copyright © 2018-2020 <NAME>. */
/* This code is licensed under the MIT License. */
/* See: LICENSE.md */
#include <libsystem/cstring.h>
#include "kernel/filesystem/Filesystem.h"
static Result zero_FsOperationRead(FsNode *node, FsHandle *handle, void *buffer, size_t size, size_t *readed)
{
__unused(node);
__unused(handle);
memset(buffer, 0, size);
*readed = size;
return SUCCESS;
}
static Result zero_FsOperationWrite(FsNode *node, FsHandle *handle, const void *buffer, size_t size, size_t *writen)
{
__unused(node);
__unused(handle);
__unused(buffer);
*writen = size;
return SUCCESS;
}
void zero_initialize(void)
{
FsNode *zero_device = __create(FsNode);
fsnode_init(zero_device, FSNODE_DEVICE);
FSNODE(zero_device)->read = (FsOperationRead)zero_FsOperationRead;
FSNODE(zero_device)->write = (FsOperationWrite)zero_FsOperationWrite;
Path *zero_device_path = path_create("/dev/zero");
filesystem_link_and_take_ref(zero_device_path, zero_device);
path_destroy(zero_device_path);
}
|
jarreed0/ArchGE
|
docs/html/search/all_1.js
|
var searchData=
[
['b',['b',['../classInput.html#a0db44708450d98572cb324ac9f0daafb',1,'Input']]],
['background',['Background',['../classBackground.html',1,'']]],
['bypasssplash',['bypassSplash',['../classEngine.html#a3b9cf8a050f43e4e185748f7b2a3ded8',1,'Engine']]]
];
|
surajkn/brooklin
|
datastream-client/src/main/java/com/linkedin/datastream/DatastreamRestClient.java
|
<filename>datastream-client/src/main/java/com/linkedin/datastream/DatastreamRestClient.java
/**
* Copyright 2019 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD 2-Clause License. See the LICENSE file in the project root for license information.
* See the NOTICE file in the project root for additional information regarding copyright ownership.
*/
package com.linkedin.datastream;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.linkedin.data.template.StringMap;
import com.linkedin.datastream.common.Datastream;
import com.linkedin.datastream.common.DatastreamAlreadyExistsException;
import com.linkedin.datastream.common.DatastreamNotFoundException;
import com.linkedin.datastream.common.DatastreamRuntimeException;
import com.linkedin.datastream.common.DatastreamStatus;
import com.linkedin.datastream.common.ErrorLogger;
import com.linkedin.datastream.common.PollUtils;
import com.linkedin.datastream.common.RetriesExhaustedException;
import com.linkedin.datastream.server.dms.DatastreamRequestBuilders;
import com.linkedin.r2.RemoteInvocationException;
import com.linkedin.restli.client.ActionRequest;
import com.linkedin.restli.client.BatchUpdateRequest;
import com.linkedin.restli.client.CreateIdRequest;
import com.linkedin.restli.client.DeleteRequest;
import com.linkedin.restli.client.FindRequest;
import com.linkedin.restli.client.GetAllRequest;
import com.linkedin.restli.client.GetRequest;
import com.linkedin.restli.client.ResponseFuture;
import com.linkedin.restli.client.RestClient;
import com.linkedin.restli.client.RestLiResponseException;
import com.linkedin.restli.client.response.BatchKVResponse;
import com.linkedin.restli.common.CollectionResponse;
import com.linkedin.restli.common.EmptyRecord;
import com.linkedin.restli.common.HttpStatus;
import com.linkedin.restli.common.IdResponse;
import com.linkedin.restli.common.UpdateStatus;
/**
* Datastream REST Client
*/
public class DatastreamRestClient {
private static final Logger LOG = LoggerFactory.getLogger(DatastreamRestClient.class);
@VisibleForTesting
protected static final String DATASTREAM_UUID = "datastreamUUID";
// To support retries on the request timeouts
public static final String CONFIG_RETRY_PERIOD_MS = "retryPeriodMs";
public static final String CONFIG_RETRY_TIMEOUT_MS = "retryTimeoutMs";
private static final long DEFAULT_RETRY_PERIOD_MS = Duration.ofSeconds(6).toMillis();
private static final long DEFAULT_RETRY_TIMEOUT_MS = Duration.ofSeconds(90).toMillis();
private final DatastreamRequestBuilders _builders;
private final RestClient _restClient;
private long _retryPeriodMs = DEFAULT_RETRY_PERIOD_MS;
private long _retryTimeoutMs = DEFAULT_RETRY_TIMEOUT_MS;
/**
* Construct the DatastreamRestClient
* @deprecated Please use {@link DatastreamRestClientFactory} instead
* @param restClient pre-created RestClient
*/
@Deprecated
public DatastreamRestClient(RestClient restClient) {
this(restClient, new Properties());
}
/**
* Construct the DatastreamRestClient. Should be called by {@link DatastreamRestClientFactory} only
* @param restClient rest.li client to use
* @param config config for the DatastreamRestClient. Note that this is not the HTTP config for the underlying
* RestClient
*/
public DatastreamRestClient(RestClient restClient, Properties config) {
if (config.containsKey(CONFIG_RETRY_PERIOD_MS)) {
_retryPeriodMs = Long.parseLong(config.getProperty(CONFIG_RETRY_PERIOD_MS));
}
if (config.containsKey(CONFIG_RETRY_TIMEOUT_MS)) {
_retryTimeoutMs = Long.parseLong(config.getProperty(CONFIG_RETRY_TIMEOUT_MS));
}
Validate.isTrue(_retryPeriodMs > 0);
Validate.isTrue(_retryTimeoutMs > _retryPeriodMs);
Validate.notNull(restClient, "null restClient");
_builders = new DatastreamRequestBuilders();
_restClient = restClient;
LOG.info("DatastreamRestClient created with retryPeriodMs={} retryTimeoutMs={}", _retryPeriodMs, _retryTimeoutMs);
}
private long getRetryPeriodMs() {
// give a bit of randomness to the retry period; in the mean time, retry period can't exceed retry timeout
return Math.min(Math.round(_retryPeriodMs * RandomUtils.nextDouble(0.6, 1.4)) + 1, _retryTimeoutMs);
}
private long getRetryTimeoutMs() {
return _retryTimeoutMs;
}
private Datastream doGetDatastream(String datastreamName) throws RemoteInvocationException {
GetRequest<Datastream> request = _builders.get().id(datastreamName).build();
ResponseFuture<Datastream> datastreamResponseFuture = _restClient.sendRequest(request);
return datastreamResponseFuture.getResponseEntity();
}
private static boolean isNotFoundHttpStatus(RemoteInvocationException e) {
return (e instanceof RestLiResponseException
&& ((RestLiResponseException) e).getStatus() == HttpStatus.S_404_NOT_FOUND.getCode());
}
/**
* Get the complete datastream object corresponding to the datastream name. This method makes a GET REST call
* to the Datastream management service which in turn fetches this Datastream object from the store (ZooKeeper).
* @param datastreamName
* Name of the datastream that should be retrieved.
* @return
* Datastream object corresponding to the datastream. This method will not return null.
* @throws com.linkedin.datastream.common.DatastreamRuntimeException
* Throws DatastreamNotFoundException if the datastream doesn't exist,
* Throws DatastreamRuntimeException for any other errors encountered while fetching the datastream.
* If there are any other network/system level errors while sending the request or receiving the response.
*/
public Datastream getDatastream(String datastreamName) {
Instant startTime = Instant.now();
Datastream datastream = PollUtils.poll(() -> {
try {
return doGetDatastream(datastreamName);
} catch (RemoteInvocationException e) {
// instanceof works for null as well
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: getDatastream. May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
String errorMessage = String.format("Get Datastream {%s} failed with error.", datastreamName);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
return null; // not reachable; Meltdown hack goes here...
}
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("getDatastream for datastream {} took {} ms", datastreamName,
Duration.between(startTime, Instant.now()).toMillis());
return datastream;
}
/**
* After creating the datastream, initialization of the datastream is an async process.
* Initialization typically involves creating the destination topic, creating the datastream tasks and
* assigning them to the datastream instances for producing.
* @param datastreamName
* Name of the datastream
* @param timeoutMs
* wait timeout in milliseconds
* @return
* Returns the initialized datastream object.
*/
public Datastream waitTillDatastreamIsInitialized(String datastreamName, long timeoutMs) throws InterruptedException {
final int pollIntervalMs = 500;
final long startTimeMs = System.currentTimeMillis();
while (System.currentTimeMillis() - startTimeMs < timeoutMs) {
Datastream ds = getDatastream(datastreamName);
if (ds.hasStatus() && ds.getStatus() == DatastreamStatus.READY) {
return ds;
}
Thread.sleep(pollIntervalMs);
}
String errorMessage = String.format("Datastream was not initialized before the timeout %s", timeoutMs);
LOG.error(errorMessage);
throw new DatastreamRuntimeException(errorMessage);
}
/**
* DeleteDatastream just marks the datastream for deletion. Hard delete of the datastream is an async process.
* This method waits till the datastream is completely removed from the system.
* @param datastreamName Name of the datastream.
* @param timeoutMs wait timeout in milliseconds.
*/
public void waitTillDatastreamIsDeleted(String datastreamName, long timeoutMs) throws InterruptedException {
final int pollIntervalMs = 500;
final long startTimeMs = System.currentTimeMillis();
while (System.currentTimeMillis() - startTimeMs < timeoutMs) {
try {
getDatastream(datastreamName);
} catch (DatastreamNotFoundException e) {
return;
}
Thread.sleep(pollIntervalMs);
}
String errorMessage = String.format("Datastream was not deleted before the timeout %s", timeoutMs);
LOG.error(errorMessage);
throw new DatastreamRuntimeException(errorMessage);
}
private List<Datastream> getAllDatastreams(GetAllRequest<Datastream> request) {
Instant startTime = Instant.now();
List<Datastream> datastreams = PollUtils.poll(() -> {
ResponseFuture<CollectionResponse<Datastream>> datastreamResponseFuture = _restClient.sendRequest(request);
try {
return datastreamResponseFuture.getResponse().getEntity().getElements();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: getAllDatastreams. May retry...", e);
return null;
}
String errorMessage = "Get All Datastreams failed with error.";
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("getAllDatastreams took {} ms", Duration.between(startTime, Instant.now()).toMillis());
return datastreams;
}
/**
* Get all the datastream objects available on the sever. This method makes a GET REST call
* to the Datastream management service which in turn fetches all the Datastream objects from the store (ZooKeeper).
* Entries will be returned in lexicographical order based on their getName() property.
*
* @return all the Datastream objects
* @for any errors encountered while fetching the datastream.
*/
public List<Datastream> getAllDatastreams() {
return getAllDatastreams(_builders.getAll().build());
}
/**
* Get all the datastream objects available on the sever. This method makes a GET REST call
* to the Datastream management service which in turn fetches all the Datastream objects from the store (ZooKeeper).
* Entries will be returned in lexicographical order based on their getName() property.
*
* @param start index of the first datastream to produce
* @param count maximum number of entries to be produced
*/
public List<Datastream> getAllDatastreams(int start, int count) {
return getAllDatastreams(_builders.getAll().paginate(start, count).build());
}
/**
* Creates a new datastream. Name of the datastream must be unique. This method makes a POST REST call to the
* Datastream management service which validates the datastream object and writes it to the store (ZooKeeper).
* @param datastream Datastream to create
*/
public void createDatastream(Datastream datastream) {
Instant startTime = Instant.now();
String creationUid = UUID.randomUUID().toString();
PollUtils.poll(() -> {
if (!datastream.hasMetadata()) {
datastream.setMetadata(new StringMap());
}
datastream.getMetadata().put(DATASTREAM_UUID, creationUid);
CreateIdRequest<String, Datastream> request = _builders.create().input(datastream).build();
ResponseFuture<IdResponse<String>> datastreamResponseFuture = _restClient.sendRequest(request);
try {
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: createDatastream. May retry...", e);
return null;
}
if (e instanceof RestLiResponseException) {
int errorCode = ((RestLiResponseException) e).getStatus();
if (errorCode == HttpStatus.S_409_CONFLICT.getCode()) {
// Timeout on previous request can make it appear as though datastream already existed.
// Check if the datastream was in fact created by this request.
Datastream existingDatastream = getDatastream(datastream.getName());
Optional<String> existingUid = Optional.ofNullable(existingDatastream.getMetadata().get(DATASTREAM_UUID));
if (existingUid.isPresent() && existingUid.get().equals(creationUid)) {
return existingDatastream;
}
String msg = String.format("Datastream %s exists with the same name. Requested datastream %s",
existingDatastream.toString(), datastream.toString());
LOG.warn(msg, e);
throw new DatastreamAlreadyExistsException(msg);
} else if (errorCode == HttpStatus.S_403_FORBIDDEN.getCode()) {
// Handle any DMS REST authorization failure for the caller principal
String msg = "Client is not authorized to invoke Datastream-CREATE, stream=" + datastream.getName();
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, msg, e);
}
}
String errorMessage = String.format("Create Datastream %s failed with error.", datastream);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
return null; // unreachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("createDatastream for datastream {} took {} ms", datastream,
Duration.between(startTime, Instant.now()).toMillis());
}
/**
* Update a datastream. Validation will be performed on the server side to ensure certain conditions are met
* (e.g. datastream is valid, the connector type supports datastream updates, etc.)
* @param datastream datastream to be updated
*/
public void updateDatastream(Datastream datastream) {
updateDatastream(Collections.singletonList(datastream));
}
/**
* Update datastreams in batch. Either all datastreams get updated or none get updated. Validation will be
* performed on the server side to ensure certain conditions are met (e.g. datastreams are valid, the connector
* type supports datastream updates, etc.)
* @param datastreams list of datastreams to be updated
*/
public void updateDatastream(List<Datastream> datastreams) {
Instant startTime = Instant.now();
// we won't support partial success. so ignore the result
PollUtils.poll(() -> {
BatchUpdateRequest<String, Datastream> request = _builders.batchUpdate()
.inputs(datastreams.stream().collect(Collectors.toMap(Datastream::getName, ds -> ds)))
.build();
ResponseFuture<BatchKVResponse<String, UpdateStatus>> datastreamResponseFuture = _restClient.sendRequest(request);
try {
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: updateDatastream. May retry...", e);
return null;
}
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "Failed to update datastreams", e);
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("updateDatastreams for datastreams {} took {} ms", datastreams,
Duration.between(startTime, Instant.now()).toMillis());
}
/**
* Delete the datastream with the specified name. This method makes a DELETE REST call to the Datastream management service
* on the DatastreamResource which in turn deletes the entity from ZooKeeper. All the connectors that
* are serving the datastream will get notified to stop producing events for the datastream.
* @param datastreamName
* Name of the datastream that should be deleted.
* @throws DatastreamRuntimeException
* When the datastream is not found or any other error happens on the server.
*/
public void deleteDatastream(String datastreamName) {
Instant startTime = Instant.now();
PollUtils.poll(() -> {
DeleteRequest<Datastream> request = _builders.delete().id(datastreamName).build();
ResponseFuture<EmptyRecord> response = _restClient.sendRequest(request);
try {
return response.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: deleteDatastream. May retry...", e);
return null;
}
String errorMessage = String.format("Delete Datastream %s failed with error.", datastreamName);
if (isNotFoundHttpStatus(e)) {
LOG.error(errorMessage, e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("deleteDatastream for datastream {} took {} ms", datastreamName,
Duration.between(startTime, Instant.now()).toMillis());
}
/**
* Check whether the specified datastream exists in the current Datastream cluster.
* @param datastreamName name of the datastream to be checked
* @return true if such datastream exists
*/
public boolean datastreamExists(String datastreamName) {
return PollUtils.poll(() -> {
try {
doGetDatastream(datastreamName);
return Boolean.TRUE;
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: datastreamExists. May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.debug("Datastream {} is not found", datastreamName);
} else {
String errorMessage = String.format("Get Datastream %s failed with error.", datastreamName);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
}
return Boolean.FALSE;
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
}
/**
* Pause a datastream, by changing its status to PAUSED. In case there are multiple datastreams
* in a group, the group is PAUSED if ALL the datastreams are paused
* @param datastreamName Name of the datastream to pause.
* @throws DatastreamRuntimeException in case of a communication issue or an error response from
* the server.
*/
public void pause(String datastreamName) throws RemoteInvocationException {
pause(datastreamName, false);
}
/**
* Pause a datastream, by changing its status to PAUSED. In case there are multiple datastreams
* in a group, the group is only PAUSED if ALL the datastreams are paused
* @param datastreamName Name of the datastream to pause.
* @param force pause all other datastreams within the same group
* @throws DatastreamRuntimeException in case of a communication issue or an error response from
* the server.
*/
public void pause(String datastreamName, boolean force) throws RemoteInvocationException {
pauseOrStop(datastreamName, force, true);
}
/**
* Stop a datastream, by changing its status to Stopped. This is similar to pause but it is treated as
* unassigned and it won't generate any metric
* @param datastreamName Name of the datastream to stop.
* @throws DatastreamRuntimeException in case of a communication issue or an error response from
* the server.
*/
public void stop(String datastreamName) throws RemoteInvocationException {
pauseOrStop(datastreamName, false, false);
}
/**
* Pause/Stop a datastream, by changing its status to PAUSED/STOPPED
* @param datastreamName
* Name of the datastream to pause.
* @param force
* If true, change all the datastreams in the same group to PAUSED/STOPPED
* @throws DatastreamRuntimeException in case of a communication issue or an error response from
* the server.
*/
private void pauseOrStop(String datastreamName, boolean force, boolean isPaused) {
Instant startTime = Instant.now();
String action = isPaused ? "PAUSE" : "STOP";
PollUtils.poll(() -> {
try {
ActionRequest<Void> request = isPaused ? _builders.actionPause().id(datastreamName).forceParam(force).build()
: _builders.actionStop().id(datastreamName).forceParam(force).build();
ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: " + action + ". May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
String errorMessage = String.format("Pause Datastream {%s} failed with error.", datastreamName);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info(action + " for datastream {} took {} ms", datastreamName,
Duration.between(startTime, Instant.now()).toMillis());
}
/**
* Resume a datastream, by changing its status from PAUSED to READY.
* @param datastreamName
* Name of the datastream to resume.
* @throws DatastreamRuntimeException in case of a communication issue or
* an error response from the server.
*/
public void resume(String datastreamName) throws RemoteInvocationException {
resume(datastreamName, false);
}
/**
* Resume a datastream, by changing its status from PAUSED to READY.
* @param datastreamName
* Name of the datastream to resume.
* @param force
* If true, changes all the datastreams in the same group to READY.
* @throws DatastreamRuntimeException in case of a communication issue or
* an error response from the server.
*/
public void resume(String datastreamName, boolean force) throws RemoteInvocationException {
Instant startTime = Instant.now();
PollUtils.poll(() -> {
try {
ActionRequest<Void> request = _builders.actionResume().id(datastreamName).forceParam(force).build();
ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: pause. May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
String errorMessage = String.format("Resume Datastream {%s} failed with error.", datastreamName);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("resume for datastream {} took {} ms", datastreamName,
Duration.between(startTime, Instant.now()).toMillis());
}
/**
* move partitions to the target host
* @param datastreamName
* Name of the datastream to move.
* @param partitions
* partitions that need to be moved, separate by comma, ex topicA-0,topicB-1
* @param targetHost
* the target host the partition assignment
* @throws RemoteInvocationException
*/
public void movePartitions(String datastreamName, String partitions, String targetHost) throws RemoteInvocationException {
Instant startTime = Instant.now();
PollUtils.poll(() -> {
try {
ActionRequest<Void> request = _builders.actionMovePartitions().id(datastreamName).
partitionsParam(partitions).targetHostParam(targetHost).build();
ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: movePartitions. May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
String errorMessage = String.format("move partitions failed with error, Datastream {%s}.", datastreamName);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("move partitions for datastream {} took {} ms", datastreamName, Duration.between(startTime, Instant.now()).toMillis());
}
/**
* Get all the datastream objects that are in the same group as the datastream whose name is "datastreamName".
* This method makes a GET REST call to the Datastream management service which in turn fetches all the Datastream
* objects from the store (ZooKeeper). Entries will be return in lexicographical based on their getName() property.
*
* @return all the Datastream objects that are in the same group as the supplied datastreamName
* @throws DatastreamRuntimeException in case of a communication issue or an error response from the server.
*/
public List<Datastream> findGroup(String datastreamName) {
return PollUtils.poll(() -> {
try {
FindRequest<Datastream> request = _builders.findByFindGroup().datastreamNameParam(datastreamName).build();
return _restClient.sendRequest(request).getResponse().getEntity().getElements();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: findGroup. May retry...", e);
return null;
}
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, "findGroup failed with error.", e);
}
return null; // not reachable
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
}
/**
* Pause source partitions for a particular datastream.
* @param datastreamName
* Name of the datastream to be paused.
* @param sourcePartitions
* StringMap of format <source, comma separated list of partitions or "*">. Example: <"FooTopic", "0,13,2">
* or <"FooTopic","*">
* @throws DatastreamRuntimeException in case of a communication issue or an error response from the server.
*/
public void pauseSourcePartitions(String datastreamName, StringMap sourcePartitions)
throws RemoteInvocationException {
Instant startTime = Instant.now();
PollUtils.poll(() -> {
try {
ActionRequest<Void> request =
_builders.actionPauseSourcePartitions().id(datastreamName).sourcePartitionsParam(sourcePartitions).build();
ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: pauseSourcePartitions. May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
String errorMessage =
String.format("Pause Datastream partitions failed with error. Datastream: {%s}, Partitions: {%s}",
datastreamName, sourcePartitions);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("pauseSourcePartitions for datastream {}, sourcePartitions {} took {} ms", datastreamName, sourcePartitions,
Duration.between(startTime, Instant.now()).toMillis());
}
/**
* Resume source partitions for a particular datastream.
* @param datastreamName
* Name of the datastream to be paused.
* @param sourcePartitions
* StringMap of format <source, comma separated list of partitions or "*">. Example: <"FooTopic", "0,13,2">
* or <"FooTopic","*">
* @throws DatastreamRuntimeException in case of a communication issue or an error response from the server.
*/
public void resumeSourcePartitions(String datastreamName, StringMap sourcePartitions)
throws RemoteInvocationException {
Instant startTime = Instant.now();
PollUtils.poll(() -> {
try {
ActionRequest<Void> request =
_builders.actionResumeSourcePartitions().id(datastreamName).sourcePartitionsParam(sourcePartitions).build();
ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: pauseSourcePartitions. May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
String errorMessage =
String.format("Resume Datastream partitions failed with error. Datastream: {%s}, Partitions: {%s}",
datastreamName, sourcePartitions);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("resumeSourcePartitions for datastream {}, sourcePartitions {} took {} ms", datastreamName, sourcePartitions,
Duration.between(startTime, Instant.now()).toMillis());
}
}
|
Lchangqing/reservation
|
front/src/models/searchRePage.js
|
/* eslint-disable radix */
import { getReByName, getSuitsById, getMenusById } from '../services/restaurant';
export default {
namespace: 'searchRePage',
state: {
searchRes: [],
searchWords: '',
layout: null,
menus: []
},
effects: {
*getRestaurant(action, { call, put }) {
try {
const { searchWords } = action.payload;
const result = yield call(getReByName, { where: { name: searchWords } });
yield put({ type: 'save', payload: { searchRes: result, searchWords } });
} catch (error) {
console.log('報錯', error);
}
// if(result.code === 0){
// const {searchRes} = result
// console.log('searchRes',searchRes);
// yield put({type:'save',payload:{searchWords,searchRes}})
// }
},
*getLayout(action, { call, put }) {
try {
const { id } = action.payload;
let layout = yield call(getSuitsById, { id });
layout.stables = layout.stables ? layout.stables.split(',').map(i => parseInt(i)) : [];
layout.mtables = layout.mtables ? layout.mtables.split(',').map(i => parseInt(i)) : [];
layout.ltables = layout.ltables ? layout.ltables.split(',').map(i => parseInt(i)) : [];
layout.smoking = layout.smoking ? layout.smoking.split(',').map(i => parseInt(i)) : [];
layout.no_smoking = layout.no_smoking ? layout.no_smoking.split(',').map(i => parseInt(i)) : [];
layout.window = layout.window ? layout.window.split(',').map(i => parseInt(i)) : [];
layout.no_window = layout.no_window ? layout.no_window.split(',').map(i => parseInt(i)) : [];
layout.noon = layout.noon ? layout.noon.split(',').map(i => parseInt(i)) : [];
layout.night = layout.night ? layout.night.split(',').map(i => parseInt(i)) : [];
yield put({ type: 'save', payload: { layout } });
} catch (error) {
console.log('getSuits報錯', error);
}
},
*getMenus(action, { call, put }) {
try {
const { id } = action.payload;
let menus = yield call(getMenusById, { id });
yield put({ type: 'save', payload: { menus } });
} catch (error) {
console.log('getSuits報錯', error);
}
}
},
reducers: {
save(state, action) {
const a = { ...state, ...action.payload };
console.log('...state, ...action.payload', state, action.payload)
return a;
},
},
};
|
bailuk/TLG
|
tlg_gnome/src/main/java/ch/bailu/tlg_gnome/BaseContext.java
|
package ch.bailu.tlg_gtk;
import org.gnome.gdk.RGBA;
import ch.bailu.tlg.PlatformContext;
import ch.bailu.tlg.StateRunning;
import ch.bailu.tlg.TlgPoint;
import ch.bailu.tlg.TlgRectangle;
public class BaseContext extends PlatformContext {
private static final int PALETTE_RESERVED=5;
private static final int PALETTE_SIZE=(StateRunning.SHAPE_PER_LEVEL*3)+PALETTE_RESERVED;
private static final int COLOR_GRID=PALETTE_SIZE-PALETTE_RESERVED-1;
private static final int COLOR_BACKGROUND=COLOR_GRID+1;
private static final int COLOR_HIGHLIGHT=COLOR_GRID+2;
private static final int COLOR_DARK=COLOR_GRID+3;
private static final int COLOR_FRAME=COLOR_GRID+4;
private static final int COLOR_GRAYED=COLOR_GRID+5;
private static RGBA palette[] = null;
public BaseContext() {
if (palette == null) {
initPalette();
}
}
private void initPalette() {
float h=0f;
palette=new RGBA[PALETTE_SIZE];
for (int i=0; i< (PALETTE_SIZE - PALETTE_RESERVED); i++) {
float[] rgb = ColorHelper.HSVtoRGB(h, 1f, 1f);
palette[i]= new RGBA(rgb[0], rgb[1], rgb[2], 1);
h++;
h%=6;
}
double x=1d/256d;
palette[COLOR_GRID]= new RGBA(x*44,x*67,x*77,1);
palette[COLOR_FRAME]= new RGBA(x*44,x*109,x*205,1);
palette[COLOR_BACKGROUND]= new RGBA(x*10,x*10,x*10,1);
palette[COLOR_HIGHLIGHT]= new RGBA(1,1,1,1);
palette[COLOR_DARK]= new RGBA(0,0,0,1);
palette[COLOR_GRAYED]= new RGBA(x*208,x*208,x*208,1);
}
public RGBA getGtkColor(int color) {
return palette[color];
}
@Override
public void drawLine(int color, TlgPoint p1, TlgPoint p2) {
}
@Override
public void drawFilledRectangle(int color, TlgRectangle rect) {
}
@Override
public void drawText(int color, TlgRectangle rect, String text) {
}
@Override
public int colorBackground() {
return COLOR_BACKGROUND;
}
@Override
public int colorDark() {
return COLOR_DARK;
}
@Override
public int colorHighlight() {
return COLOR_HIGHLIGHT;
}
@Override
public int colorGrayed() {
return COLOR_GRAYED;
}
@Override
public int colorFrame() {
return COLOR_FRAME;
}
@Override
public int colorGrid() {
return COLOR_GRID;
}
@Override
public int countOfColor() {
return PALETTE_SIZE;
}
@Override
public int getColor(int i) {
return i;
}
@Override
public void onNewHighscore() {
}
}
|
NYCMOTI/open-bid
|
app/presenters/pluralize.rb
|
class Pluralize
include ActionView::Helpers::TextHelper
attr_reader :number, :word
def initialize(number:, word:)
@number = number
@word = word
end
def to_s
pluralize(number, word)
end
end
|
Shoothzj/go_demo
|
demo_base/slice/slice_init_test.go
|
package slice
import (
"fmt"
"testing"
)
func Test_SliceInit1(t *testing.T) {
aux := make([]int, 5)
aux[0] = 1
aux[1] = 2
aux[2] = 3
aux[3] = 4
aux[4] = 5
fmt.Println(aux)
}
func Test_SliceInit2(t *testing.T) {
aux := [5]int{1, 2, 3, 4, 5}
fmt.Println(aux)
}
func Test_SliceInit3(t *testing.T) {
aux := [...]int{1, 2, 3, 4, 5}
fmt.Println(aux)
}
func Test_SliceInit4(t *testing.T) {
aux := [...]int{1: 2, 3: 4, 5}
fmt.Println(aux)
}
|
reyou/Ggg.VueJs
|
apps/app-web/scrimba.com/Vuex-Documentation/intro12-Modules-SubModules/src/index.js
|
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const moduleA = {
namespaced: true,
state: {
count: 3
},
mutations: {
increment(state) {
state.count++;
}
},
getters: {
doubleCount(state) {
return state.count * 2;
}
},
actions: {
incrementIfOdd({ state, commit }) {
if (state.count % 2 === 1) {
commit("increment");
}
}
}
};
const moduleB = {
namespaced: true,
modules: {
subModule: {
namespaced: true,
state: {},
mutations: {
login() {
console.log("moduleB.subModule.mutations.login");
}
},
getters: {
login() {
console.log("moduleB.subModule.getters.login");
}
},
actions: {
login() {
console.log("moduleB.subModule.actions.login");
}
}
}
},
state: {
count: 8
},
mutations: {},
getters: {
someGetter(state, getters, rootState, rootGetters) {
rootState.count;
state.count;
getters.someOtherGetter;
rootGetters.someOtherGetter;
}
},
actions: {
someAction({ dispatch, commit, getters }) {
getters.someGetter;
rootGetters.someGetter;
dispatch("someOtherAction");
dispatch("someOtherAction", null, { root: true });
commit("someMutation");
commit("someMutation", null, { root: true });
}
}
};
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
},
state: {
count: 2
},
mutations: {},
getters: {},
actions: {}
});
import { mapState, mapActions } from "vuex";
new Vue({
el: "#app",
store,
data: {},
computed: mapState({
a: state => state.a.count,
b: state => state.b.subModule.count
}),
methods: mapActions("some/nested/module", [
"foo" // this.foo()
])
});
// console.log(store.state.a.count);
// // console.log(store.state.b.count);
// store.commit('a/increment');
// console.log(store.state.a.count);
store.commit("b/subModule/login");
store.dispatch("b/subModule/login");
store.getters["b/subModule/login"];
|
Daniel-Tilley/College
|
FYP/RestAPI/TrainingPalAPI/api_app/dao/target_dao.py
|
<reponame>Daniel-Tilley/College
from api_app.config.database import DataBase
from api_app.constants.database.targets_table import TargetsTable
from api_app.helpers.dao_helper import DAOHelper
from api_app.helpers.query_builder import QueryBuilder
class TargetDao:
def __init__(self):
self.db = DataBase.GetDataBaseConnection()
# Used to get a list of targets by week
def GetTargetsByWeek(self, user_id, week_number, year_number):
try:
with self.db.cursor() as cursor:
sql = QueryBuilder() \
.Select() \
.AllColumns() \
.From() \
.Table(TargetsTable.TABLE_NAME) \
.Where() \
.ColumnsNoBrackets([TargetsTable.ATHLETE_ID]) \
.Like() \
.ValuesNoBrackets([user_id]) \
.And() \
.ColumnsNoBrackets([TargetsTable.WEEK]) \
.Equals() \
.ValuesNoBrackets([week_number]) \
.And() \
.ColumnsNoBrackets([TargetsTable.YEAR]) \
.Equals() \
.ValuesNoBrackets([year_number]) \
.OrderBy() \
.ColumnsNoBrackets([TargetsTable.ID]) \
.Asc() \
.Build()
cursor.execute(sql)
columns = cursor.description
targets = []
for values in cursor.fetchall():
targets.append(DAOHelper.ConvertResultsToObject(columns, values)[0])
return targets
except:
return None
finally:
cursor.close()
self.db.close()
# Create Target from a target object
def CreateTarget(self, target):
try:
with self.db.cursor() as cursor:
sql = QueryBuilder() \
.Insert() \
.Into() \
.Table(TargetsTable.TABLE_NAME) \
.ColumnsBrackets([
TargetsTable.ATHLETE_ID,
TargetsTable.CONTENT,
TargetsTable.STATUS,
TargetsTable.WEEK,
TargetsTable.YEAR
]) \
.ValuesKeyword() \
.ValuesBrackets([
target.Athlete_Id.__str__(),
target.Content.__str__(),
target.Status.__str__(),
target.Week.__str__(),
target.Year.__str__()
]) \
.Build()
cursor.execute(sql, QueryBuilder().CountNulls(sql).BuildNullTuple())
if cursor.rowcount != 0:
self.db.commit()
return True
else:
return None
except:
return None
finally:
cursor.close()
self.db.close()
# Update target from a update object
def UpdateTarget(self, update_data):
try:
with self.db.cursor() as cursor:
sql = QueryBuilder() \
.Update() \
.Table(TargetsTable.TABLE_NAME) \
.Set() \
.UpdateValues(update_data.memberKeys, update_data.memberValues) \
.Where() \
.ColumnsNoBrackets([update_data.identifierKeys[0]]) \
.Like() \
.ValuesNoBrackets([update_data.identifierValues[0]]) \
.And() \
.ColumnsNoBrackets([update_data.identifierKeys[1]]) \
.Like() \
.ValuesNoBrackets([update_data.identifierValues[1]]) \
.Build()
cursor.execute(sql, QueryBuilder().CountNulls(sql).BuildNullTuple())
if cursor.rowcount != 0:
self.db.commit()
return True
else:
return None
except:
return None
finally:
cursor.close()
self.db.close()
# Used to delete targets
def DeleteTarget(self, user_id, target_id):
try:
with self.db.cursor() as cursor:
sql = QueryBuilder() \
.Delete() \
.From() \
.Table(TargetsTable.TABLE_NAME) \
.Where() \
.ColumnsNoBrackets([TargetsTable.ID]) \
.Like() \
.ValuesNoBrackets([target_id]) \
.And() \
.ColumnsNoBrackets([TargetsTable.ATHLETE_ID]) \
.Like() \
.ValuesNoBrackets([user_id]) \
.Build()
cursor.execute(sql)
if cursor.rowcount != 0:
self.db.commit()
return True
else:
return None
except:
return None
finally:
cursor.close()
self.db.close()
|
slaclab/kpix
|
old-software/kpixSw/util/read_example.cc
|
<gh_stars>0
//-----------------------------------------------------------------------------
// File : read_example.cc
// Author : <NAME> <<EMAIL>>
// Created : 10/31/2008
// Project : Kpix Software Package
//-----------------------------------------------------------------------------
// Description :
// Example file to demonstrate reading from a KPIX root file.
//-----------------------------------------------------------------------------
// Copyright (c) 2009 by SLAC. All rights reserved.
// Proprietary and confidential to SLAC.
//-----------------------------------------------------------------------------
// Modification history :
// 10/31/2008: created
// 06/22/2009: Added namespace.
//-----------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <KpixRunRead.h>
#include <KpixCalibRead.h>
#include <KpixFpga.h>
#include <KpixAsic.h>
#include <KpixRunVar.h>
#include <KpixSample.h>
#include <KpixEventVar.h>
#include <TFile.h>
using namespace std;
// Process the data
// Pass root file to open as first and only arg.
int main ( int argc, char **argv ) {
KpixRunRead *runRead;
KpixAsic *asic;
KpixFpga *fpga;
KpixEventVar *eventVar;
KpixRunVar *runVar;
KpixSample *sample;
KpixCalibRead *calibRead;
double gain,icept;
bool status;
int x, y, count;
int timeCount, trainCount;
int lastTime, lastTrain;
// Root file is the first and only arg
if ( argc != 2 ) {
cout << "Usage: read_example file.root\n";
return(1);
}
// Attempt to open root file using KpixRunRead class
// The second arg to the run read file controls debugging.
try {
runRead = new KpixRunRead(argv[1],false);
} catch ( string error ) {
cout << "Error opening run file:\n";
cout << error << "\n";
return(2);
}
// Once the run read file is open you have access to all the
// data stored in the run. This includes the strings which
// describe the run as well as the KpixAsic and KpixFpga
// classes which contain the hardware configurion for the
// run. In the example below a few run attributes are
// displayed as an example.
cout << " Run Name: " << runRead->getRunName() << endl;
cout << " Run Time: " << runRead->getRunTime() << endl;
cout << " End Time: " << runRead->getEndTime() << endl;
cout << " Cal Time: " << runRead->getRunCalib() << endl;
cout << " Duration: " << runRead->getRunDuration() << endl;
cout << "Description: " << runRead->getRunDescription() << endl;
// In addition to using the KpixRunRead class to access the root file
// you can also access the root file class directly. Here we do an
// ls of the root file base directory.
cout << endl << "Listing Root File Directory Contents" << endl;
runRead->treeFile->ls();
cout << endl;
// Below is an example of reading data from the support FPGA.
// The false flag in the read statement indicates that we don't
// want to really read from hardware. Data from the class is read
// instead. If false is not provided an exception will be thrown
// since no hardware link is open.
fpga = runRead->getFpga();
cout << "Fpga Clock Period=" << fpga->getClockPeriod(false) << endl;
cout << endl;
// We can also read information about the Asics as well. Here we read
// the serial number, version number and polarity setting for each ASIC.
// Again the false flag is passed when reading the polarity to indicate
// that we don't want to really read from hardware.
// Remember that the KpixAsic object with the highest index is not a true
// KPIX ASIC but a dummy version of the digital core contained in the
// FPGA. It has a version number of zero and only supports certain registers.
cout << "Number of Asics In Configuration: " << runRead->getAsicCount() << endl;
for ( x=0; x < runRead->getAsicCount(); x++ ) {
asic = runRead->getAsic(x);
cout << "Reading Asic " << x << endl;
cout << " Serial: " << asic->getSerial() << endl;
cout << " Version: " << asic->getVersion() << endl;
cout << " Polarity: " << asic->getCntrlPosPixel(false) << endl;
}
// Next we will read out the run variables for this file. A run variable is
// a mechanism to store an unlimited number of double variables in the
// root file. These variables descrive the conditions under which the run
// occured. These variables are set once at the start of the run and
// remain constant during the run.
cout << endl << "Number of Run Variables: " << runRead->getRunVarCount() << endl;
for ( x=0; x < runRead->getRunVarCount(); x++ ) {
runVar = runRead->getRunVar(x);
cout << "Reading Run Varable " << x << endl;
cout << " Name: " << runVar->name() << endl;
cout << " Desc: " << runVar->description() << endl;
cout << " Value: " << runVar->value() << endl;
}
// Next we will read out the event variable key for this file. An event
// variable is a value which can change from event to event. The
// KpixEventVar class contains information about the run variables
// related to this root file. The class contains no value field
// it simply describes the data stored in each sample. Each KpixSample
// record (read later in this example) contains an array of doubles
// to store the event variables. The number field in the KpixEventVar
// class can be used as an index into the array.
cout << endl << "Number of event Variables: " << runRead->getEventVarCount() << endl;
for ( x=0; x < runRead->getEventVarCount(); x++ ) {
eventVar = runRead->getEventVar(x);
cout << "Reading Event Variable " << x << endl;
cout << " Name: " << eventVar->name() << endl;
cout << " Desc: " << eventVar->description() << endl;
cout << " Number: " << eventVar->number() << endl;
}
// Before processing samples we may want to read the calibration constants
// for each channel. This will allow us to convert the ADC value contained
// in each sample to a charge value. It is common practice in the new
// version of the API to store calibration data along with the run data in
// the same file.
calibRead = new KpixCalibRead(runRead);
// Here we will read the calibration data for channel 0, bucket 0 of
// the first KPIX. The return value will be true on success, false on fail.
// "ForceTrig" is the common directory for stored calibration plots.
// We will read the values for each gain mode.
cout << endl << "Reading Calibration Data" << endl;
for (x=0; x<3; x++) { // 0=Normal Gain, 1=Double Gain, 2=Low Gain
status = calibRead->getCalibData(&gain,&icept,"Force_Trig",x,
runRead->getAsic(0)->getSerial(),
0,0); // Channel=0, bucket=0
cout << "Mode=" << x;
cout << ", Gain=" << gain;
cout << ", Intercept=" << icept;
cout << ", Status=" << status << endl;
}
// For normal data processing it is best to read all of the needed
// calibration constants at the start of processing. This way the
// values are available as you read through the events. You don't want
// to have to read from the root file after each event.
// Next we will process each event in the file. The root file contains a
// series of events sorted by their timestamp. Each sample contains about
// a single event bucket within a single channel. Each sample record
// contains information about the address of the Kpix it was read from,
// the train number in which it was read, the timestamp of the sample
// as well as the sample's value. If one wishes to group a number of
// samples into an event, all samples with a matching timestemp for
// example, they would be grouped as they are read from the file.
try {
// Here we read the number of samples contained in the root file
count = runRead->getSampleCount();
cout << endl << "Found " << count << " Samples In the File" << endl;
// Init a couple of variables we will use
lastTime = 0;
lastTrain = 0;
timeCount = 0;
trainCount = 0;
// Iterate through each sample serially
for ( x=0; x < count; x++ ) {
// Get the sample.
sample = runRead->getSample(x);
// Before processing the sample you may want to check to see if you
// now in a new train or time bucket. This way you can process
// samples in groups.
// If we wanted to process samples by time group
if ( x!=0 && lastTime != sample->getSampleTime() ) {
// Here we will process samples that were read between calls to
// this block of code. Here we simply return the number of
// samples in the time group.
cout << "We found " << timeCount;
cout << " Samples For Time " << lastTime;
cout << " In Train " << lastTrain << endl;
timeCount = 0;
}
// If we wanted to process samples by train
if ( x!=0 && lastTrain != sample->getTrainNum() ) {
// Here we will process samples that were read between calls to
// this block of code. Here we simply return the number of
// samples in the train group.
cout << "We found " << trainCount;
cout << " Samples In Train " << lastTrain << endl;
trainCount = 0;
}
// Once we have read the sample we can extract the information contained
// inside it. Here we will print each variable contained in the sample.
cout << endl << "Reading Sample " << x << endl;
cout << " Train Number: " << sample->getTrainNum() << endl;
cout << " Kpix Address: " << sample->getKpixAddress() << endl;
cout << " Kpix Channel: " << sample->getKpixChannel() << endl;
cout << " Kpix Bucket: " << sample->getKpixBucket() << endl;
cout << " Sample Range: " << sample->getSampleRange() << endl;
cout << " Sample Time: " << sample->getSampleTime() << endl;
cout << " Sample Value: " << sample->getSampleValue() << endl;
// Next read the event variable values. These are just a sequence
// of doubles contained in the sample. The name and description
// of each sample can be determined by retrieving the associated
// event variable from the rootRead object.
for (y=0; y < sample->getVarCount(); y++) {
cout << " Sample Value: " << sample->getSampleValue() << endl;
cout << " Var " << dec << setw(2) << y;
cout << " Value: " << sample->getVarValue(y) << endl;
}
// Increment train and time counters
trainCount++;
timeCount++;
// Set last train and last time value to detect new state on next iteration
lastTime = sample->getSampleTime();
lastTrain = sample->getTrainNum();
}
} catch ( string error ) {
cout << "Error extracting Events:\n";
cout << error << "\n";
return(1);
}
// Delete the created classes when done
delete(calibRead);
delete(runRead);
}
|
knime-mpicbg/HCS-Tools
|
de.mpicbg.knime.hcs.core/src/de/mpicbg/knime/hcs/core/Excel2003WriterUtils.java
|
package de.mpicbg.knime.hcs.core;
import de.mpicbg.knime.hcs.core.model.Plate;
import de.mpicbg.knime.hcs.core.model.Well;
import de.mpicbg.knime.hcs.core.util.StringTable;
import de.mpicbg.knime.hcs.core.view.color.ScreenColorScheme;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
/**
* Document me!
*
* @author <NAME>
*/
public class Excel2003WriterUtils {
public static int CONC_TABLE_ROW_OFFSET = 4;
public static int ROW_OFFSET = 6;
public static void saveLayoutAsExcel(Plate plate, File outFile) {
try {
WritableWorkbook workbook = Workbook.createWorkbook(outFile);
WritableSheet sheet = workbook.createSheet(LayoutUtils.DEFAULT_LAYOUT_SHEET_NAME, 0);
int concTableOffset = CONC_TABLE_ROW_OFFSET + plate.getNumRows();
WritableFont font = new WritableFont(WritableFont.ARIAL);
font.setBoldStyle(WritableFont.BOLD);
WritableCellFormat boldFormat = new WritableCellFormat(font);
sheet.addCell(new Label(LayoutUtils.COL_OFFSET - 1, ROW_OFFSET - 2, TdsUtils.SCREEN_MODEL_TREATMENT));
sheet.addCell(new Label(LayoutUtils.COL_OFFSET - 1, ROW_OFFSET + concTableOffset - 2, TdsUtils.SCREEN_MODEL_CONCENTRATION));
ScreenColorScheme colorScheme = ScreenColorScheme.getInstance();
boldFormat.setBackground(jxl.format.Colour.GRAY_25);
for (int rowIndex = 0; rowIndex <= plate.getNumRows(); rowIndex++) {
for (int colIndex = 0; colIndex <= plate.getNumColumns(); colIndex++) {
int excelCol = colIndex + LayoutUtils.COL_OFFSET - 1;
int excelRow = rowIndex + ROW_OFFSET - 1;
if (rowIndex == 0 && colIndex == 0)
continue;
if (rowIndex == 0 && colIndex > 0) {
sheet.addCell(new Label(excelCol, excelRow, colIndex + "", boldFormat));
sheet.addCell(new Label(excelCol, excelRow + concTableOffset, colIndex + "", boldFormat));
continue;
}
if (colIndex == 0 && rowIndex > 0) {
sheet.addCell(new Label(excelCol, excelRow, TdsUtils.mapPlateRowNumberToString(rowIndex), boldFormat));
sheet.addCell(new Label(excelCol, excelRow + concTableOffset, TdsUtils.mapPlateRowNumberToString(rowIndex), boldFormat));
continue;
}
// write treatment-field
Well well = plate.getWell(colIndex, rowIndex);
String treatment = well.getTreatment();
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setBackground(colorScheme.getBestMatchingExcelColor(treatment));
if (treatment != null) {
sheet.addCell(new Label(excelCol, excelRow, treatment, cellFormat));
}
// write concentration
String concentration = well.getCompoundConcentration();
if (concentration != null) {
sheet.addCell(new Label(excelCol, excelRow + concTableOffset, concentration, cellFormat));
}
}
}
workbook.write();
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, BiffException {
org.apache.poi.ss.usermodel.Workbook workbook = LayoutUtils.openWorkBook(new File("/Users/brandl/ttt.xls"));
Rectangle plateDim = StringTable.guessPlateBounds(workbook.getSheetAt(0), new Point(LayoutUtils.COL_OFFSET, ROW_OFFSET));
StringTable table = StringTable.readStringGridFromExcel(plateDim, workbook.getSheetAt(0));
System.err.println("table is" + table);
}
}
|
yingxx26/MicroCommunity
|
service-report/src/main/java/com/java110/report/bmo/reportOwnerPayFee/impl/UpdateReportOwnerPayFeeBMOImpl.java
|
package com.java110.report.bmo.reportOwnerPayFee.impl;
import com.java110.core.annotation.Java110Transactional;
import com.java110.intf.report.IReportOwnerPayFeeInnerServiceSMO;
import com.java110.po.reportOwnerPayFee.ReportOwnerPayFeePo;
import com.java110.report.bmo.reportOwnerPayFee.IUpdateReportOwnerPayFeeBMO;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@Service("updateReportOwnerPayFeeBMOImpl")
public class UpdateReportOwnerPayFeeBMOImpl implements IUpdateReportOwnerPayFeeBMO {
@Autowired
private IReportOwnerPayFeeInnerServiceSMO reportOwnerPayFeeInnerServiceSMOImpl;
/**
* @param reportOwnerPayFeePo
* @return 订单服务能够接受的报文
*/
@Java110Transactional
public ResponseEntity<String> update(ReportOwnerPayFeePo reportOwnerPayFeePo) {
int flag = reportOwnerPayFeeInnerServiceSMOImpl.updateReportOwnerPayFee(reportOwnerPayFeePo);
if (flag > 0) {
return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
}
return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
}
}
|
sirinath/Harmony
|
jdktools/modules/jdktools/src/main/java/org/apache/harmony/tools/appletviewer/Main.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tools.appletviewer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
public class Main {
static final String propertiesFileName = ".harmony.appletviewer.properties";
static final String httpProxyHost = "http.proxyHost";
static final String httpProxyPort = "http.proxyPort";
static final String httpsProxyHost = "https.proxyHost";
static final String httpsProxyPort = "https.proxyPort";
static final String ftpProxyHost = "ftp.proxyHost";
static final String ftpProxyPort = "ftp.proxyPort";
static final Properties properties = new Properties();
static File propertiesFile;
public static void main(String argv[]) throws Exception {
if (argv.length == 0) {
printHelp();
return;
}
ArrayList<String> propertiesList = new ArrayList<String>();
ArrayList<String> urlsList = new ArrayList<String>();
for(int i = 0; i < argv.length; i++){
if(argv[i].startsWith("-D")){
propertiesList.add(argv[i].substring(2));
} else {
urlsList.add(argv[i]);
}
}
if (urlsList.size() == 0) {
printHelp();
return;
}
// Load stored java.properties
String userHomeDir = System.getProperty("user.home");
propertiesFile = new File(userHomeDir +
File.separator + Main.propertiesFileName);
boolean needStore = false;
if(propertiesFile.exists()){
try{
properties.load(new FileInputStream(propertiesFile));
} catch(IOException e){
}
} else {
properties.setProperty(httpProxyHost, "");
properties.setProperty(httpProxyPort, "");
properties.setProperty(httpsProxyHost, "");
properties.setProperty(httpsProxyPort, "");
properties.setProperty(ftpProxyHost, "");
properties.setProperty(ftpProxyPort, "");
needStore = true;
}
// Parse command line java.properties
Iterator<String> iterator = propertiesList.iterator();
while(iterator.hasNext()){
String prop = iterator.next();
if(prop != null){
String[] pair = prop.split("=");
String key = null;
String val = null;
if(pair[0] != null){
key = pair[0].trim();
}
if(pair[1] != null){
val = pair[1].trim();
}
if(key != null && key != "" && val != null && val != ""){
if(validatePropertyName(key)){
properties.setProperty(key, val);
needStore = true;
} else {
System.err.println("Unknown proxy property: " + key);
System.exit(-1);
}
if(key.endsWith("Port")){
try{
if(Integer.parseInt(val) < 0){
wrongPortMessage(val);
System.exit(-1);
}
} catch(NumberFormatException ex){
wrongPortMessage(key);
System.exit(-1);
}
}
}
}
}
if(needStore) storeProxyProperties();
Enumeration<?> e = properties.propertyNames();
while(e.hasMoreElements()){
String key = (String)e.nextElement();
String val = properties.getProperty(key);
if(val != null && val != ""){
System.setProperty(key, val);
}
}
HTMLParser parser = new HTMLParser();
Object []applets = parser.parse(urlsList.toArray(new String[urlsList.size()]), 0);
// Start applets
for (int i = 0; i < applets.length; i++)
new AppletFrame((AppletInfo)applets[i]);
}
static void storeProxyProperties(){
try{
if(!propertiesFile.exists()) propertiesFile.createNewFile();
properties.store(new FileOutputStream(propertiesFile),
"User-specific properties for Harmony AppletViewer");
} catch(IOException e){
}
}
private static boolean validatePropertyName(String name){
if(!name.equals(httpProxyHost) && !name.equals(httpProxyPort) &&
!name.equals(httpsProxyHost) && !name.equals(httpsProxyPort) &&
!name.equals(ftpProxyHost) && !name.equals(ftpProxyPort)){
return false;
} else {
return true;
}
}
private static void wrongPortMessage(String portName){
System.err.println();
System.err.println("Proxy parameter error: " + portName + " must be a positive integer value");
}
private static void printHelp() {
System.err.println("AppletViewer");
System.err.println("Usage: appletviewer [[-Dproxy.property] ... ] url(s)");
System.err.println();
System.err.println("Available proxy properties:");
System.err.println();
System.err.println("\thttp.proxyHost");
System.err.println("\thttp.proxyPort");
System.err.println("\thttps.proxyHost");
System.err.println("\thttps.proxyPort");
System.err.println("\tftp.proxyHost");
System.err.println("\tftp.proxyPort");
}
}
|
greatanan/rocketmq-all
|
namesrv/src/main/java/org/apache/rocketmq/namesrv/processor/DefaultRequestProcessor.java
|
package org.apache.rocketmq.namesrv.processor;
import io.netty.channel.ChannelHandlerContext;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.rocketmq.common.DataVersion;
import org.apache.rocketmq.common.MQVersion;
import org.apache.rocketmq.common.MQVersion.Version;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.help.FAQUrl;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.logging.InternalLoggerFactory;
import org.apache.rocketmq.common.namesrv.NamesrvUtil;
import org.apache.rocketmq.common.namesrv.RegisterBrokerResult;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.body.RegisterBrokerBody;
import org.apache.rocketmq.common.protocol.body.TopicConfigSerializeWrapper;
import org.apache.rocketmq.common.protocol.header.GetTopicsByClusterRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.DeleteKVConfigRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.DeleteTopicInNamesrvRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetKVConfigRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetKVConfigResponseHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetKVListByNamespaceRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetRouteInfoRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.PutKVConfigRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.QueryDataVersionRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.QueryDataVersionResponseHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.RegisterBrokerRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.RegisterBrokerResponseHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.UnRegisterBrokerRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.WipeWritePermOfBrokerRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.WipeWritePermOfBrokerResponseHeader;
import org.apache.rocketmq.common.protocol.route.TopicRouteData;
import org.apache.rocketmq.namesrv.NamesrvController;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingCommandException;
import org.apache.rocketmq.remoting.netty.AsyncNettyRequestProcessor;
import org.apache.rocketmq.remoting.netty.NettyRequestProcessor;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
public class DefaultRequestProcessor extends AsyncNettyRequestProcessor implements NettyRequestProcessor {
private static InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
protected final NamesrvController namesrvController;
public DefaultRequestProcessor(NamesrvController namesrvController) {
this.namesrvController = namesrvController;
}
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
if (ctx != null) {
log.debug("receive request, {} {} {}",
request.getCode(),
RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
request);
}
switch (request.getCode()) {
case RequestCode.PUT_KV_CONFIG:
return this.putKVConfig(ctx, request);
case RequestCode.GET_KV_CONFIG:
return this.getKVConfig(ctx, request);
case RequestCode.DELETE_KV_CONFIG:
return this.deleteKVConfig(ctx, request);
case RequestCode.QUERY_DATA_VERSION:
return queryBrokerTopicConfig(ctx, request);
case RequestCode.REGISTER_BROKER:
Version brokerVersion = MQVersion.value2Version(request.getVersion());
if (brokerVersion.ordinal() >= MQVersion.Version.V3_0_11.ordinal()) {
return this.registerBrokerWithFilterServer(ctx, request);
} else {
return this.registerBroker(ctx, request);
}
case RequestCode.UNREGISTER_BROKER:
return this.unregisterBroker(ctx, request);
case RequestCode.GET_ROUTEINFO_BY_TOPIC:
return this.getRouteInfoByTopic(ctx, request);
case RequestCode.GET_BROKER_CLUSTER_INFO:
return this.getBrokerClusterInfo(ctx, request);
case RequestCode.WIPE_WRITE_PERM_OF_BROKER:
return this.wipeWritePermOfBroker(ctx, request);
case RequestCode.GET_ALL_TOPIC_LIST_FROM_NAMESERVER:
return getAllTopicListFromNameserver(ctx, request);
case RequestCode.DELETE_TOPIC_IN_NAMESRV:
return deleteTopicInNamesrv(ctx, request);
case RequestCode.GET_KVLIST_BY_NAMESPACE:
return this.getKVListByNamespace(ctx, request);
case RequestCode.GET_TOPICS_BY_CLUSTER:
return this.getTopicsByCluster(ctx, request);
case RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_NS:
return this.getSystemTopicListFromNs(ctx, request);
case RequestCode.GET_UNIT_TOPIC_LIST:
return this.getUnitTopicList(ctx, request);
case RequestCode.GET_HAS_UNIT_SUB_TOPIC_LIST:
return this.getHasUnitSubTopicList(ctx, request);
case RequestCode.GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST:
return this.getHasUnitSubUnUnitTopicList(ctx, request);
case RequestCode.UPDATE_NAMESRV_CONFIG:
return this.updateConfig(ctx, request);
case RequestCode.GET_NAMESRV_CONFIG:
return this.getConfig(ctx, request);
default:
break;
}
return null;
}
@Override
public boolean rejectRequest() {
return false;
}
public RemotingCommand putKVConfig(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final PutKVConfigRequestHeader requestHeader =
(PutKVConfigRequestHeader) request.decodeCommandCustomHeader(PutKVConfigRequestHeader.class);
this.namesrvController.getKvConfigManager().putKVConfig(
requestHeader.getNamespace(),
requestHeader.getKey(),
requestHeader.getValue()
);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
public RemotingCommand getKVConfig(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(GetKVConfigResponseHeader.class);
final GetKVConfigResponseHeader responseHeader = (GetKVConfigResponseHeader) response.readCustomHeader();
final GetKVConfigRequestHeader requestHeader =
(GetKVConfigRequestHeader) request.decodeCommandCustomHeader(GetKVConfigRequestHeader.class);
String value = this.namesrvController.getKvConfigManager().getKVConfig(
requestHeader.getNamespace(),
requestHeader.getKey()
);
if (value != null) {
responseHeader.setValue(value);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
response.setCode(ResponseCode.QUERY_NOT_FOUND);
response.setRemark("No config item, Namespace: " + requestHeader.getNamespace() + " Key: " + requestHeader.getKey());
return response;
}
public RemotingCommand deleteKVConfig(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final DeleteKVConfigRequestHeader requestHeader =
(DeleteKVConfigRequestHeader) request.decodeCommandCustomHeader(DeleteKVConfigRequestHeader.class);
this.namesrvController.getKvConfigManager().deleteKVConfig(
requestHeader.getNamespace(),
requestHeader.getKey()
);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
public RemotingCommand registerBrokerWithFilterServer(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(RegisterBrokerResponseHeader.class);
final RegisterBrokerResponseHeader responseHeader = (RegisterBrokerResponseHeader) response.readCustomHeader();
final RegisterBrokerRequestHeader requestHeader =
(RegisterBrokerRequestHeader) request.decodeCommandCustomHeader(RegisterBrokerRequestHeader.class);
if (!checksum(ctx, request, requestHeader)) {
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("crc32 not match");
return response;
}
RegisterBrokerBody registerBrokerBody = new RegisterBrokerBody();
if (request.getBody() != null) {
try {
registerBrokerBody = RegisterBrokerBody.decode(request.getBody(), requestHeader.isCompressed());
} catch (Exception e) {
throw new RemotingCommandException("Failed to decode RegisterBrokerBody", e);
}
} else {
registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setCounter(new AtomicLong(0));
registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setTimestamp(0);
}
RegisterBrokerResult result = this.namesrvController.getRouteInfoManager().registerBroker(
requestHeader.getClusterName(),
requestHeader.getBrokerAddr(),
requestHeader.getBrokerName(),
requestHeader.getBrokerId(),
requestHeader.getHaServerAddr(),
registerBrokerBody.getTopicConfigSerializeWrapper(),
registerBrokerBody.getFilterServerList(),
ctx.channel());
responseHeader.setHaServerAddr(result.getHaServerAddr());
responseHeader.setMasterAddr(result.getMasterAddr());
byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
response.setBody(jsonValue);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private boolean checksum(ChannelHandlerContext ctx, RemotingCommand request,
RegisterBrokerRequestHeader requestHeader) {
if (requestHeader.getBodyCrc32() != 0) {
final int crc32 = UtilAll.crc32(request.getBody());
if (crc32 != requestHeader.getBodyCrc32()) {
log.warn(String.format("receive registerBroker request,crc32 not match,from %s",
RemotingHelper.parseChannelRemoteAddr(ctx.channel())));
return false;
}
}
return true;
}
public RemotingCommand queryBrokerTopicConfig(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(QueryDataVersionResponseHeader.class);
final QueryDataVersionResponseHeader responseHeader = (QueryDataVersionResponseHeader) response.readCustomHeader();
final QueryDataVersionRequestHeader requestHeader =
(QueryDataVersionRequestHeader) request.decodeCommandCustomHeader(QueryDataVersionRequestHeader.class);
DataVersion dataVersion = DataVersion.decode(request.getBody(), DataVersion.class);
Boolean changed = this.namesrvController.getRouteInfoManager().isBrokerTopicConfigChanged(requestHeader.getBrokerAddr(), dataVersion);
if (!changed) {
this.namesrvController.getRouteInfoManager().updateBrokerInfoUpdateTimestamp(requestHeader.getBrokerAddr());
}
DataVersion nameSeverDataVersion = this.namesrvController.getRouteInfoManager().queryBrokerTopicConfig(requestHeader.getBrokerAddr());
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
if (nameSeverDataVersion != null) {
response.setBody(nameSeverDataVersion.encode());
}
responseHeader.setChanged(changed);
return response;
}
public RemotingCommand registerBroker(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(RegisterBrokerResponseHeader.class);
final RegisterBrokerResponseHeader responseHeader = (RegisterBrokerResponseHeader) response.readCustomHeader();
final RegisterBrokerRequestHeader requestHeader =
(RegisterBrokerRequestHeader) request.decodeCommandCustomHeader(RegisterBrokerRequestHeader.class);
if (!checksum(ctx, request, requestHeader)) {
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("crc32 not match");
return response;
}
TopicConfigSerializeWrapper topicConfigWrapper;
if (request.getBody() != null) {
topicConfigWrapper = TopicConfigSerializeWrapper.decode(request.getBody(), TopicConfigSerializeWrapper.class);
} else {
topicConfigWrapper = new TopicConfigSerializeWrapper();
topicConfigWrapper.getDataVersion().setCounter(new AtomicLong(0));
topicConfigWrapper.getDataVersion().setTimestamp(0);
}
RegisterBrokerResult result = this.namesrvController.getRouteInfoManager().registerBroker(
requestHeader.getClusterName(),
requestHeader.getBrokerAddr(),
requestHeader.getBrokerName(),
requestHeader.getBrokerId(),
requestHeader.getHaServerAddr(),
topicConfigWrapper,
null,
ctx.channel()
);
responseHeader.setHaServerAddr(result.getHaServerAddr());
responseHeader.setMasterAddr(result.getMasterAddr());
byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
response.setBody(jsonValue);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
public RemotingCommand unregisterBroker(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final UnRegisterBrokerRequestHeader requestHeader =
(UnRegisterBrokerRequestHeader) request.decodeCommandCustomHeader(UnRegisterBrokerRequestHeader.class);
this.namesrvController.getRouteInfoManager().unregisterBroker(
requestHeader.getClusterName(),
requestHeader.getBrokerAddr(),
requestHeader.getBrokerName(),
requestHeader.getBrokerId());
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
public RemotingCommand getRouteInfoByTopic(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetRouteInfoRequestHeader requestHeader =
(GetRouteInfoRequestHeader) request.decodeCommandCustomHeader(GetRouteInfoRequestHeader.class);
TopicRouteData topicRouteData = this.namesrvController.getRouteInfoManager().pickupTopicRouteData(requestHeader.getTopic());
if (topicRouteData != null) {
if (this.namesrvController.getNamesrvConfig().isOrderMessageEnable()) {
String orderTopicConf =
this.namesrvController.getKvConfigManager().getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG,
requestHeader.getTopic());
topicRouteData.setOrderTopicConf(orderTopicConf);
}
byte[] content = topicRouteData.encode();
response.setBody(content);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
response.setCode(ResponseCode.TOPIC_NOT_EXIST);
response.setRemark("No topic route info in name server for the topic: " + requestHeader.getTopic()
+ FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL));
return response;
}
private RemotingCommand getBrokerClusterInfo(ChannelHandlerContext ctx, RemotingCommand request) {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
byte[] content = this.namesrvController.getRouteInfoManager().getAllClusterInfo();
response.setBody(content);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand wipeWritePermOfBroker(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(WipeWritePermOfBrokerResponseHeader.class);
final WipeWritePermOfBrokerResponseHeader responseHeader = (WipeWritePermOfBrokerResponseHeader) response.readCustomHeader();
final WipeWritePermOfBrokerRequestHeader requestHeader =
(WipeWritePermOfBrokerRequestHeader) request.decodeCommandCustomHeader(WipeWritePermOfBrokerRequestHeader.class);
int wipeTopicCnt = this.namesrvController.getRouteInfoManager().wipeWritePermOfBrokerByLock(requestHeader.getBrokerName());
if (ctx != null) {
log.info("wipe write perm of broker[{}], client: {}, {}",
requestHeader.getBrokerName(),
RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
wipeTopicCnt);
}
responseHeader.setWipeTopicCount(wipeTopicCnt);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand getAllTopicListFromNameserver(ChannelHandlerContext ctx, RemotingCommand request) {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
byte[] body = this.namesrvController.getRouteInfoManager().getAllTopicList();
response.setBody(body);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand deleteTopicInNamesrv(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final DeleteTopicInNamesrvRequestHeader requestHeader =
(DeleteTopicInNamesrvRequestHeader) request.decodeCommandCustomHeader(DeleteTopicInNamesrvRequestHeader.class);
this.namesrvController.getRouteInfoManager().deleteTopic(requestHeader.getTopic());
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand getKVListByNamespace(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetKVListByNamespaceRequestHeader requestHeader =
(GetKVListByNamespaceRequestHeader) request.decodeCommandCustomHeader(GetKVListByNamespaceRequestHeader.class);
byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(
requestHeader.getNamespace());
if (null != jsonValue) {
response.setBody(jsonValue);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
response.setCode(ResponseCode.QUERY_NOT_FOUND);
response.setRemark("No config item, Namespace: " + requestHeader.getNamespace());
return response;
}
private RemotingCommand getTopicsByCluster(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetTopicsByClusterRequestHeader requestHeader =
(GetTopicsByClusterRequestHeader) request.decodeCommandCustomHeader(GetTopicsByClusterRequestHeader.class);
byte[] body = this.namesrvController.getRouteInfoManager().getTopicsByCluster(requestHeader.getCluster());
response.setBody(body);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand getSystemTopicListFromNs(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
byte[] body = this.namesrvController.getRouteInfoManager().getSystemTopicList();
response.setBody(body);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand getUnitTopicList(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
byte[] body = this.namesrvController.getRouteInfoManager().getUnitTopics();
response.setBody(body);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand getHasUnitSubTopicList(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
byte[] body = this.namesrvController.getRouteInfoManager().getHasUnitSubTopicList();
response.setBody(body);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand getHasUnitSubUnUnitTopicList(ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
byte[] body = this.namesrvController.getRouteInfoManager().getHasUnitSubUnUnitTopicList();
response.setBody(body);
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand updateConfig(ChannelHandlerContext ctx, RemotingCommand request) {
if (ctx != null) {
log.info("updateConfig called by {}", RemotingHelper.parseChannelRemoteAddr(ctx.channel()));
}
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
byte[] body = request.getBody();
if (body != null) {
String bodyStr;
try {
bodyStr = new String(body, MixAll.DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
log.error("updateConfig byte array to string error: ", e);
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("UnsupportedEncodingException " + e);
return response;
}
Properties properties = MixAll.string2Properties(bodyStr);
if (properties == null) {
log.error("updateConfig MixAll.string2Properties error {}", bodyStr);
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("string2Properties error");
return response;
}
this.namesrvController.getConfiguration().update(properties);
}
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
private RemotingCommand getConfig(ChannelHandlerContext ctx, RemotingCommand request) {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
String content = this.namesrvController.getConfiguration().getAllConfigsFormatString();
if (content != null && content.length() > 0) {
try {
response.setBody(content.getBytes(MixAll.DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
log.error("getConfig error, ", e);
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark("UnsupportedEncodingException " + e);
return response;
}
}
response.setCode(ResponseCode.SUCCESS);
response.setRemark(null);
return response;
}
}
|
pierce-m/p4c
|
test/unittests/transform1.cpp
|
/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ir/ir.h"
#include "ir/visitor.h"
#include <assert.h>
static IR::Constant *c1;
class TestTrans : public Transform {
IR::Node *postorder(IR::Add *a) override {
assert(a->left == c1);
assert(a->right == c1);
return a;
}
};
int main() {
c1 = new IR::Constant(2);
IR::Expression *e = new IR::Add(Util::SourceInfo(), c1, c1);
auto *n = e->apply(TestTrans());
assert(n == e);
}
|
viadee/javaAnchorAdapters
|
DefaultConfigsExtension/src/main/java/de/viadee/xai/anchor/adapter/tabular/util/SerializableSupplier.java
|
<filename>DefaultConfigsExtension/src/main/java/de/viadee/xai/anchor/adapter/tabular/util/SerializableSupplier.java
package de.viadee.xai.anchor.adapter.tabular.util;
import java.io.Serializable;
import java.util.function.Supplier;
/**
* {@link Supplier} interface which is {@link Serializable}
*/
@FunctionalInterface
public interface SerializableSupplier extends Supplier<Serializable>, Serializable {
}
|
Egg4/microfarm-app
|
public/js/app/container/popup-container.js
|
'use strict';
define([
'jquery',
'underscore',
'lib/container/container',
'app/view/popup/error-popup',
'app/view/popup/confirm-popup',
'app/view/popup/delete-popup',
'app/view/popup/menu-popup',
], function ($, _, Container,
ErrorPopup,
ConfirmPopup,
DeletePopup,
MenuPopup
) {
return Container.extend({
initialize: function () {
Container.prototype.initialize.call(this, {
error: function () {
return new ErrorPopup();
},
confirm: function () {
return new ConfirmPopup();
},
delete: function () {
return new DeletePopup();
},
menu: function () {
return new MenuPopup();
},
});
},
closeAll: function () {
var deferred = $.Deferred();
var promises = [];
this.each(function(popup) {
if (popup.isOpened()) {
promises.push(popup.close());
}
});
$.when.apply($, promises).done(function() {
deferred.resolve();
}.bind(this));
return deferred.promise();
},
});
});
|
myriadrf/lms-suite
|
LMS7002M/lms7suite/controlPanelGUI/dlgRegisterMap.h
|
<reponame>myriadrf/lms-suite<filename>LMS7002M/lms7suite/controlPanelGUI/dlgRegisterMap.h
/**
@file dlgRegisterMap.h
@author <NAME>
*/
#ifndef DLGREGISTERMAP_H
#define DLGREGISTERMAP_H
//(*Headers(dlgRegisterMap)
#include <wx/dialog.h>
class wxGrid;
class wxStaticText;
class wxFlexGridSizer;
class wxButton;
class wxGridEvent;
//*)
#include "SignalHandler.h"
class LMS7002_MainControl;
class dlgRegisterMap: public wxDialog, public SignalHandler
{
public:
dlgRegisterMap(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);
virtual ~dlgRegisterMap();
void Initialize(LMS7002_MainControl *mainControl);
void HandleMessage(const LMS_Message &msg);
void UpdateTables();
//(*Declarations(dlgRegisterMap)
wxGrid* gridCh1;
wxStaticText* StaticText2;
wxButton* btnClose;
wxGrid* gridCh0;
wxStaticText* StaticText1;
wxStaticText* StaticText3;
wxButton* btnForceRefresh;
wxStaticText* txtAction;
//*)
protected:
//(*Identifiers(dlgRegisterMap)
static const long ID_STATICTEXT2;
static const long ID_STATICTEXT1;
static const long ID_GRID1;
static const long ID_GRID2;
static const long ID_STATICTEXT3;
static const long ID_STATICTEXT4;
static const long ID_BUTTON2;
static const long ID_BUTTON1;
//*)
private:
//(*Handlers(dlgRegisterMap)
void OnbtnCloseClick(wxCommandEvent& event);
void OnbtnForceRefreshClick(wxCommandEvent& event);
//*)
protected:
LMS7002_MainControl *lmsControl;
void BuildContent(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size);
DECLARE_EVENT_TABLE()
};
#endif
|
andrej59/app-work
|
spring/src/main/java/ru/ajana/work/spring/controller/MainRestController.java
|
<gh_stars>0
package ru.ajana.work.spring.controller;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import ru.ajana.work.spring.model.User;
/**
* @author <NAME> on 31.03.2018
*/
@RestController
public class MainRestController {
@RequestMapping(value = "/employees", method = RequestMethod.GET)
public @ResponseBody User getEmployee(@PathVariable("id") int empId, Pageable pageable, Sort sort) {
//logger.info("Start getEmployee. ID="+empId);
//return empData.get(empId);
return null;
}
}
|
linliff/AndroidGo
|
app/src/main/java/com/github/hailouwang/demosforapi/widget/lifecycle/RecyclerViewAdapter.java
|
package com.github.hailouwang.demosforapi.widget.lifecycle;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.github.hailouwang.demosforapi.widget.recyclerview.test1.vh.BaseRecyclerViewAdapterVh1;
import com.github.hailouwang.demosforapi.widget.recyclerview.test1.vh.TextRecyclerViewItem;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<BaseRecyclerViewAdapterVh1> {
private static final int VIEW_TYPE_STRING = 1;
private List<String> datas = new ArrayList<>();
public RecyclerViewAdapter(List<String> datas) {
this.datas.addAll(datas);
}
@NonNull
@Override
public BaseRecyclerViewAdapterVh1 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new TextRecyclerViewItem(parent);
}
@Override
public void onBindViewHolder(@NonNull BaseRecyclerViewAdapterVh1 holder, int position) {
String data = (position >= datas.size()) ? "" : datas.get(position);
holder.onBindRecyclerViewHolder(holder, position, data);
}
@Override
public int getItemViewType(int position) {
return VIEW_TYPE_STRING;
}
@Override
public int getItemCount() {
int size = this.datas.size();
return size;
}
}
|
giuseppe/quay
|
static/js/directives/ui/set-repo-permissions.js
|
/**
* An element which displays a table for setting permissions for an entity to repositories under
* a namespace.
*/
angular.module('quay').directive('setRepoPermissions', function () {
var directiveDefinitionObject = {
priority: 0,
templateUrl: '/static/directives/set-repo-permissions.html',
replace: false,
transclude: true,
restrict: 'C',
scope: {
'namespace': '=namespace',
'entityName': '=entityName',
'entityKind': '=entityKind',
'setPermissions': '=setPermissions',
'hasCheckedRepositories': '=hasCheckedRepositories',
'hasChangedRepositories': '=hasChangedRepositories',
'repositoriesLoaded': '&repositoriesLoaded',
'settingPermissions': '&settingPermissions',
'permissionsSet': '&permissionsSet',
},
controller: function($scope, $element, ApiService, UIService, TableService, RolesService, UserService) {
$scope.TableService = TableService;
$scope.options = {
'predicate': 'last_modified_datetime',
'reverse': false,
'filter': ''
};
$scope.repositories = null;
$scope.currentNamespace = null;
$scope.currentEntityName = null;
$scope.orderedRepositories = [];
$scope.reposPerPage = 25;
$scope.maxPopularity = 0;
$scope.options = {
'predicate': 'popularity',
'reverse': false,
'filter': null,
'page': 0
};
var checkForChanges = function() {
var hasChanges = false;
if (!$scope.repositories) {
return;
}
$scope.repositories.forEach(function(repo) {
if (repo['permission'] != repo['original_permission']) {
hasChanges = true;
}
});
$scope.hasCheckedRepositories = !!$scope.checkedRepos.checked.length;
$scope.hasChangedRepositories = hasChanges;
};
var handleRepoCheckChange = function() {
if (!$scope.repositories) {
return;
}
$scope.repositories.forEach(function(repo) {
if ($scope.checkedRepos.isChecked(repo)) {
if (repo['permission'] == 'none') {
repo['permission'] = 'read';
}
} else {
repo['permission'] = 'none';
}
});
checkForChanges();
};
var setRepoState = function() {
if (!$scope.repositories) {
return;
}
$scope.orderedRepositories = TableService.buildOrderedItems(
$scope.repositories, $scope.options,
['namespace', 'name'],
['last_modified_datetime']);
};
var loadRepositoriesAndPermissions = function() {
if (!$scope.namespace || !$scope.entityName || !$scope.entityKind) {
return;
}
if (($scope.entityName == $scope.currentEntityName) &&
($scope.namespace == $scope.currentNamespace)) {
return;
}
$scope.currentNamespace = $scope.namespace;
$scope.currentEntityName = $scope.entityName;
// Load the repository permissions for the entity first. We then load the full repo list
// and compare.
RolesService.getRepoPermissions($scope.namespace, $scope.entityKind, $scope.entityName,
function(permissions) {
if (permissions == null) {
$scope.currentNamespace = null;
$scope.currentEntityName = null;
return;
}
var existingPermissionsMap = {};
permissions.forEach(function(existingPermission) {
existingPermissionsMap[existingPermission.repository.name] = existingPermission.role;
});
loadRepositories(existingPermissionsMap);
});
};
var loadRepositories = function(existingPermissionsMap) {
$scope.namespaceInfo = UserService.getNamespace($scope.namespace);
// Load the repositories under the entity's namespace, along with the current repo
// permissions for the entity.
var params = {
'namespace': $scope.namespace,
'last_modified': true
};
ApiService.listReposAsResource().withPagination('repositories').withOptions(params).get(
function(resp) {
$scope.currentNamespace = $scope.namespace;
var repos = [];
if (!resp || !resp['repositories'] || resp['repositories'].length == 0) {
$scope.repositoriesLoaded({'repositories': []});
return;
}
resp['repositories'].forEach(function(repo) {
var existingPermission = existingPermissionsMap[repo.name] || 'none';
repos.push({
'namespace': repo.namespace,
'name': repo.name,
'last_modified': repo.last_modified,
'last_modified_datetime': TableService.getReversedTimestamp(repo.last_modified),
'permission': existingPermission,
'original_permission': existingPermission
});
});
$scope.repositories = repos;
$scope.checkedRepos = UIService.createCheckStateController($scope.repositories, 'name');
repos.forEach(function(repo) {
if (repo.permission != 'none') {
$scope.checkedRepos.checkItem(repo);
}
});
$scope.checkedRepos.listen(handleRepoCheckChange);
setRepoState();
$scope.repositoriesLoaded({'repositories': repos});
}
);
};
var setPermissions = function() {
if (!$scope.checkedRepos || !$scope.namespace || !$scope.repositories) {
return;
}
$scope.settingPermissions();
var repos = $scope.repositories;
var counter = 0;
var setPerm = function() {
if (counter >= repos.length) {
$scope.permissionsSet({'repositories': $scope.checkedRepos.checked});
$scope.checkedRepos.setChecked([]);
return;
}
var repo = repos[counter];
if (repo['permission'] == repo['original_permission']) {
// Skip changing it.
counter++;
setPerm();
return;
}
RolesService.setRepositoryRole(repo, repo.permission, $scope.entityKind,
$scope.entityName, function(status) {
if (status) {
counter++;
setPerm();
}
});
};
setPerm();
};
$scope.setRole = function(role, repo) {
repo['permission'] = role;
if (role == 'none') {
$scope.checkedRepos.uncheckItem(repo);
} else {
$scope.checkedRepos.checkItem(repo);
}
checkForChanges();
};
$scope.allRepositoriesFilter = function(item) {
return true;
};
$scope.noRepositoriesFilter = function(item) {
return false;
};
$scope.missingPermsRepositoriesFilter = function(item) {
return !item.perm;
};
$scope.$watch('options.predicate', setRepoState);
$scope.$watch('options.reverse', setRepoState);
$scope.$watch('options.filter', setRepoState);
$scope.$watch('namespace', loadRepositoriesAndPermissions);
$scope.$watch('entityName', loadRepositoriesAndPermissions);
$scope.$watch('entityKind', loadRepositoriesAndPermissions);
$scope.$watch('setPermissions', function(value) {
if (value) {
setPermissions();
}
});
}
};
return directiveDefinitionObject;
});
|
khuebeo/scrape
|
src/NestedBlock/SharpBlock/BinaryComparison/ComparisonE.cc
|
#include <string>
#include <stdexcept>
#include <algorithm>
#include "NestedBlock/SharpBlock/BinaryComparison/ComparisonE.h"
#include <memory>
bool ComparisonE::getBool() const
{
return left->getValue()==right->getValue();
}
|
Mario-Kart-Felix/AopArms
|
aop-arms/src/main/java/cn/com/superLei/aoparms/aspect/InterceptAspect.java
|
<gh_stars>100-1000
package cn.com.superLei.aoparms.aspect;
import android.text.TextUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import cn.com.superLei.aoparms.AopArms;
import cn.com.superLei.aoparms.annotation.Intercept;
/**
* description $desc$
* created by jerry on 2019/5/30.
*/
@Aspect
public class InterceptAspect {
private static final String POINTCUT_METHOD = "execution(@cn.com.superLei.aoparms.annotation.Intercept * *(..))";
@Pointcut(POINTCUT_METHOD)
public void onInterceptMethod() {
}
@Around("onInterceptMethod() && @annotation(intercept)")
public Object doInterceptMethod(ProceedingJoinPoint joinPoint, Intercept intercept) throws Throwable {
if (AopArms.getInterceptor() == null)return joinPoint.proceed();
String value = intercept.value();
if (!TextUtils.isEmpty(value)){
//拦截
boolean result = proceedIntercept(intercept.value(), joinPoint);
return result ? null : joinPoint.proceed();
}
return joinPoint.proceed();
}
private boolean proceedIntercept(String value, ProceedingJoinPoint joinPoint) throws Throwable {
boolean intercept = AopArms.getInterceptor().intercept(value, joinPoint.getSignature().getName());
if (intercept){
return true;
}
return false;
}
}
|
kvpradap/py_entitymatching
|
py_entitymatching/explorer/pandastable/pandastable_wrapper.py
|
<filename>py_entitymatching/explorer/pandastable/pandastable_wrapper.py
try:
from tkinter import *
except ImportError as e:
from Tkinter import *
from py_entitymatching.utils.validation_helper import validate_object_type
import pandas as pd
def data_explore_pandastable(df):
"""
Wrapper function for pandastable. Gives user a GUI to examine and edit
the dataframe passed in using pandastable.
Args:
df (Dataframe): The pandas dataframe to be explored with pandastable.
Raises:
AssertionError: If `df` is not of type pandas DataFrame.
Examples:
>>> import py_entitymatching as em
>>> A = em.read_csv_metadata('path_to_csv_dir/table.csv', key='ID')
>>> em.data_explore_pandastable(A)
"""
# Validate input parameters
# # We expect the df to be of type pandas DataFrame
validate_object_type(df, pd.DataFrame, 'Input df')
DataExplorePandastable(df)
class DataExplorePandastable(Frame):
"""
A wrapper for pandastable.
"""
def __init__(self, df):
# Import
try:
from pandastable import Table, TableModel
except ImportError:
raise ImportError('Pandastable is not installed. Please install pandastable to use '
'pandastable data exploration functions.')
self.parent = None
Frame.__init__(self)
self.main = self.master
self.main.geometry('600x400+200+100')
self.main.title('Explore Data')
f = Frame(self.main)
f.pack(fill=BOTH, expand=1)
# set the table in the GUI
self.table = pt = Table(f, dataframe=df,
showtoolbar=True, showstatusbar=True)
pt.show()
self.mainloop()
|
Amity-Network/amity
|
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/WebKit.framework/Versions/A/Headers/HIWebView.h
|
/*
* Copyright (C) 2004, 2005 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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.
*/
#ifndef __HIWebView__
#define __HIWebView__
#ifndef __LP64__
#include <Carbon/Carbon.h>
#include <WebKit/WebKitAvailability.h>
#if PRAGMA_ONCE
#pragma once
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __OBJC__
@class WebView;
#endif
/*
* HIWebViewCreate()
*
* Summary:
* Creates a new web view.
*
* Parameters:
*
* outControl:
* The new web view.
*
* Result:
* An operating system status code.
*
* Availability:
* Mac OS X: in version 10.2.7 and later [32-bit only]
* CarbonLib: not available
* Non-Carbon CFM: not available
*/
extern OSStatus
HIWebViewCreate(HIViewRef * outControl) CF_DEPRECATED_MAC(10_3, 10_6);
#ifdef __OBJC__
/*
* HIWebViewGetWebView()
*
* Summary:
* Returns the WebKit WebView for a given HIWebView.
*
* Parameters:
*
* inView:
* The view to inspect.
*
* Result:
* A pointer to a web view object, or NULL.
*
* Availability:
* Mac OS X: in version 10.2.7 and later [32-bit only]
* CarbonLib: not available
* Non-Carbon CFM: not available
*/
extern WebView *
HIWebViewGetWebView(HIViewRef inView) CF_DEPRECATED_MAC(10_3, 10_6);
#endif
#ifdef __cplusplus
}
#endif
#endif
#endif /* __HIWebView__ */
|
mtcrawshaw/meta-world
|
meta/report/plot.py
|
<gh_stars>1-10
""" Plotting for performance metrics. """
from typing import Dict, List, Union, Any
import numpy as np
import matplotlib.pyplot as plt
from meta.utils.metrics import Metrics
def plot(
metrics: Union[Metrics, Dict[str, Metrics]],
plot_path: str,
summary: Dict[str, Any] = None,
) -> None:
"""
Plot the metrics from `metrics`, store image at `plot_path`. `metrics` should be a
`Metrics` object in the case that the metrics from a single training run should be
plotted. Otherwise, `metrics` should be a dictionary whose keys are names of methods
and whose values are `Metrics` objects holding metric values from training with the
corresponding methods. These multiple `Metrics` objects should hold values for the
same metrics and each of these metrics should have the same history length. In this
case, the results from different methods will be plotted on the same chart. Summary
should be provided (as computed by `experiment()`) only in the case that `metrics`
is a `dict`.
"""
# Count the number of plots. We create a plot for each unique basename among all
# basenames from the given metrics with non-empty history.
basenames = []
if isinstance(metrics, Metrics):
basenames = get_basenames(metrics)
elif isinstance(metrics, dict):
first_metrics = list(metrics.values())[0]
basenames = get_basenames(first_metrics)
for method_metrics in metrics.values():
assert basenames == get_basenames(method_metrics)
else:
raise NotImplementedError
# Add an extra plot which will just contain a table.
num_plots = len(basenames) + 1
# Create subplots.
fig_width = 12.8
plot_height = 4.8
table_height_ratio = 0.3
fig, axs = plt.subplots(
num_plots,
figsize=(fig_width, plot_height * (num_plots - (1.0 - table_height_ratio))),
gridspec_kw={"height_ratios": [1.0] * (num_plots - 1) + [table_height_ratio]},
)
# Wrap a single axis in a list to make sure that axs is iterable.
if not isinstance(axs, np.ndarray):
axs = [axs]
# Create figure title.
fig.suptitle("Training Metrics")
# Find bound of x-axis for each plot.
if isinstance(metrics, Metrics):
max_metric_len = get_max_metric_len(metrics)
elif isinstance(metrics, dict):
first_metrics = list(metrics.values())[0]
max_metric_len = get_max_metric_len(first_metrics)
for method_metrics in metrics.values():
assert max_metric_len == get_max_metric_len(method_metrics)
else:
raise NotImplementedError
# Plot each metric set on a separate plot.
plotted_metrics = []
for i, basename in enumerate(basenames):
# Construct metric names and find max metric length (scale of x-axis).
legend = []
if isinstance(metrics, Metrics):
metric_names = get_metric_names(metrics, basename)
elif isinstance(metrics, dict):
first_metrics = list(metrics.values())[0]
metric_names = get_metric_names(first_metrics, basename)
for method_metrics in metrics.values():
assert metric_names == get_metric_names(method_metrics, basename)
else:
raise NotImplementedError
for metric_name in metric_names:
# Get metric state values.
mean_arrs = []
stdev_arrs = []
method_names = []
if isinstance(metrics, Metrics):
metric = metrics.metric_dict[metric_name]
mean_arrs = [np.array(metric.mean)]
stdev_arrs = [np.array(metric.stdev)]
assert len(mean_arrs[0]) == len(stdev_arrs[0])
elif isinstance(metrics, Dict):
for j, (method, method_metrics) in enumerate(metrics.items()):
metric = method_metrics.metric_dict[metric_name]
mean_arr = np.array(metric.mean)
stdev_arr = np.array(metric.stdev)
assert len(mean_arr) == len(stdev_arr)
if j != 0:
assert len(mean_arr) == len(mean_arrs[0])
mean_arrs.append(mean_arr)
stdev_arrs.append(stdev_arr)
method_names.append(method)
else:
raise NotImplementedError
# Assign x-axis values to each data point.
num_points = len(mean_arrs[0])
num_intervals = num_points if num_points > 1 else 1
x_axis = [(j * max_metric_len) // num_intervals for j in range(num_points)]
# Plot mean.
for j in range(len(mean_arrs)):
axs[i].plot(x_axis, mean_arrs[j])
if isinstance(metrics, Metrics):
legend.append(metric_name)
elif isinstance(metrics, dict):
legend.append(f"{method_names[j]}_{metric_name}")
else:
raise NotImplementedError
# Fill space between mean and upper/lower std devs.
upper_dev_array = mean_arrs[j] + stdev_arrs[j]
lower_dev_array = mean_arrs[j] - stdev_arrs[j]
axs[i].fill_between(x_axis, lower_dev_array, upper_dev_array, alpha=0.2)
# Add x-axis label.
axs[i].set_xlabel("Training episodes")
plotted_metrics.append(metric_name)
# Add legend to subplot.
axs[i].legend(legend, loc="upper left")
# Helper function for constructing cell text.
possibly_none = lambda val: "%.5f" % val if val is not None else "None"
# Write out table of final metrics.
axs[-1].axis("off")
cell_text = []
if isinstance(metrics, Metrics):
row_labels = list(plotted_metrics)
col_labels = ["Best", "Final"]
for metric_name in plotted_metrics:
metric = metrics.metric_dict[metric_name]
row_text = []
row_text.append(possibly_none(metric.best))
if len(metric.mean) == 0:
row_text.append("None")
else:
row_text.append(possibly_none(metric.mean[-1]))
cell_text.append(list(row_text))
elif isinstance(metrics, dict):
row_labels = list(summary.keys())
col_labels = list(metrics.keys())
for metric_name in summary:
row_text = []
for method, method_metrics in metrics.items():
method_results = summary[metric_name][method]
mean = method_results["mean_performance"]
CI = method_results["CI"]
rad = (CI[1] - CI[0]) / 2
if mean is None:
row_text.append(None)
else:
row_text.append(f"{mean:.5f} += {rad:.5f}")
cell_text.append(list(row_text))
else:
raise NotImplementedError
axs[-1].table(
cellText=cell_text,
rowLabels=row_labels,
colLabels=col_labels,
colWidths=[0.2] * len(col_labels),
loc="upper center",
)
# Save out plot.
plt.savefig(plot_path)
plt.close()
def get_basenames(metrics: Metrics) -> List[str]:
""" Utility function to aggregate basenames from a `Metrics` objects. """
basenames = []
for metric in metrics.metric_dict.values():
if len(metric.history) > 0 and metric.basename not in basenames:
basenames.append(metric.basename)
return basenames
def get_max_metric_len(metrics: Metrics) -> List[str]:
""" Utility function to get maximum length of a metric from `metrics`. """
return max([len(metric.mean) for metric in metrics.metric_dict.values()])
def get_metric_names(metrics: Metrics, basename: str) -> List[str]:
"""
Utility function to aggregate metric names with a given basename from a `Metrics`
object.
"""
return [
metric_name
for metric_name, metric in metrics.metric_dict.items()
if metric.basename == basename
]
|
mankeyl/elasticsearch
|
server/src/main/java/org/elasticsearch/search/RescoreDocIds.java
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
/**
* Since {@link org.elasticsearch.search.internal.SearchContext} no longer hold the states of search, the top K results
* (i.e., documents that will be rescored by query rescorers) need to be serialized/ deserialized between search phases.
* A {@link RescoreDocIds} encapsulates the top K results for each rescorer by its ordinal index.
*/
public final class RescoreDocIds implements Writeable {
public static final RescoreDocIds EMPTY = new RescoreDocIds(Map.of());
private final Map<Integer, Set<Integer>> docIds;
public RescoreDocIds(Map<Integer, Set<Integer>> docIds) {
this.docIds = docIds;
}
public RescoreDocIds(StreamInput in) throws IOException {
docIds = in.readMap(StreamInput::readVInt, i -> i.readSet(StreamInput::readVInt));
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeMap(docIds, StreamOutput::writeVInt, (o, v) -> o.writeCollection(v, StreamOutput::writeVInt));
}
public Set<Integer> getId(int index) {
return docIds.get(index);
}
}
|
foxsake/infuzion-sgp
|
kernel/common/arch/arm/mach-s5pc100/mach-smdkc100.c
|
/* linux/arch/arm/mach-s5pc100/mach-smdkc100.c
*
* Copyright 2009 Samsung Electronics Co.
* Author: <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/map.h>
#include <mach/regs-fb.h>
#include <video/platform_lcd.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <plat/gpio-cfg.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/s5pc100.h>
#include <plat/fb.h>
#include <plat/iic.h>
/* Following are default values for UCON, ULCON and UFCON UART registers */
#define S5PC100_UCON_DEFAULT (S3C2410_UCON_TXILEVEL | \
S3C2410_UCON_RXILEVEL | \
S3C2410_UCON_TXIRQMODE | \
S3C2410_UCON_RXIRQMODE | \
S3C2410_UCON_RXFIFO_TOI | \
S3C2443_UCON_RXERR_IRQEN)
#define S5PC100_ULCON_DEFAULT S3C2410_LCON_CS8
#define S5PC100_UFCON_DEFAULT (S3C2410_UFCON_FIFOMODE | \
S3C2440_UFCON_RXTRIG8 | \
S3C2440_UFCON_TXTRIG16)
static struct s3c2410_uartcfg smdkc100_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = S5PC100_UCON_DEFAULT,
.ulcon = S5PC100_ULCON_DEFAULT,
.ufcon = S5PC100_UFCON_DEFAULT,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = S5PC100_UCON_DEFAULT,
.ulcon = S5PC100_ULCON_DEFAULT,
.ufcon = S5PC100_UFCON_DEFAULT,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = S5PC100_UCON_DEFAULT,
.ulcon = S5PC100_ULCON_DEFAULT,
.ufcon = S5PC100_UFCON_DEFAULT,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = S5PC100_UCON_DEFAULT,
.ulcon = S5PC100_ULCON_DEFAULT,
.ufcon = S5PC100_UFCON_DEFAULT,
},
};
/* I2C0 */
static struct i2c_board_info i2c_devs0[] __initdata = {
};
/* I2C1 */
static struct i2c_board_info i2c_devs1[] __initdata = {
};
/* LCD power controller */
static void smdkc100_lcd_power_set(struct plat_lcd_data *pd,
unsigned int power)
{
/* backlight */
gpio_direction_output(S5PC100_GPD(0), power);
if (power) {
/* module reset */
gpio_direction_output(S5PC100_GPH0(6), 1);
mdelay(100);
gpio_direction_output(S5PC100_GPH0(6), 0);
mdelay(10);
gpio_direction_output(S5PC100_GPH0(6), 1);
mdelay(10);
}
}
static struct plat_lcd_data smdkc100_lcd_power_data = {
.set_power = smdkc100_lcd_power_set,
};
static struct platform_device smdkc100_lcd_powerdev = {
.name = "platform-lcd",
.dev.parent = &s3c_device_fb.dev,
.dev.platform_data = &smdkc100_lcd_power_data,
};
/* Frame Buffer */
static struct s3c_fb_pd_win smdkc100_fb_win0 = {
/* this is to ensure we use win0 */
.win_mode = {
.pixclock = 1000000000000ULL / ((8+13+3+800)*(7+5+1+480)*80),
.left_margin = 8,
.right_margin = 13,
.upper_margin = 7,
.lower_margin = 5,
.hsync_len = 3,
.vsync_len = 1,
.xres = 800,
.yres = 480,
},
.max_bpp = 32,
.default_bpp = 16,
};
static struct s3c_fb_platdata smdkc100_lcd_pdata __initdata = {
.win[0] = &smdkc100_fb_win0,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC,
.setup_gpio = s5pc100_fb_gpio_setup_24bpp,
};
static struct platform_device *smdkc100_devices[] __initdata = {
&s3c_device_i2c0,
&s3c_device_i2c1,
&s3c_device_fb,
&s3c_device_hsmmc0,
&s3c_device_hsmmc1,
&s3c_device_hsmmc2,
&smdkc100_lcd_powerdev,
&s5pc100_device_iis0,
&s5pc100_device_ac97,
};
static void __init smdkc100_map_io(void)
{
s5p_init_io(NULL, 0, S5P_VA_CHIPID);
s3c24xx_init_clocks(12000000);
s3c24xx_init_uarts(smdkc100_uartcfgs, ARRAY_SIZE(smdkc100_uartcfgs));
}
static void __init smdkc100_machine_init(void)
{
/* I2C */
s3c_i2c0_set_platdata(NULL);
s3c_i2c1_set_platdata(NULL);
i2c_register_board_info(0, i2c_devs0, ARRAY_SIZE(i2c_devs0));
i2c_register_board_info(1, i2c_devs1, ARRAY_SIZE(i2c_devs1));
s3c_fb_set_platdata(&smdkc100_lcd_pdata);
/* LCD init */
gpio_request(S5PC100_GPD(0), "GPD");
gpio_request(S5PC100_GPH0(6), "GPH0");
smdkc100_lcd_power_set(&smdkc100_lcd_power_data, 0);
platform_add_devices(smdkc100_devices, ARRAY_SIZE(smdkc100_devices));
}
MACHINE_START(SMDKC100, "SMDKC100")
/* Maintainer: <NAME> <<EMAIL>> */
.phys_io = S3C_PA_UART & 0xfff00000,
.io_pg_offst = (((u32)S3C_VA_UART) >> 18) & 0xfffc,
.boot_params = S5P_PA_SDRAM + 0x100,
.init_irq = s5pc100_init_irq,
.map_io = smdkc100_map_io,
.init_machine = smdkc100_machine_init,
.timer = &s3c24xx_timer,
MACHINE_END
|
Jumpscale/ays9
|
templates/nodes/node.kvm/actions.py
|
def install(job):
prefab = job.service.executor.prefab
data = job.service.model.data
name = job.service.name
image = job.service.producers['image_os'][0]
image_name = image.model.data.url.split('/')[-1]
nics = data.nics
vm = prefab.virtualization.kvm.machines.create(
name=name,
os=image_name,
disks=list(data.disks),
nics=nics,
memory=data.memory,
cpucount=data.cpu,
cloud_init=True,
username=data.sshLogin,
passwd=data.sshPassword,
sshkey=None, # TODO: decide if we send a key in this level or from the os.ssh layer above this service
start=True,
resetPassword=False,
)
job.service.model.actions['uninstall'].state = 'new'
job.service.saveAll()
job.service.executeAction('start', inprocess=True)
def start(job):
prefab = job.service.executor.prefab
data = job.service.model.data
name = job.service.name
vm = prefab.virtualization.kvm.machines.get_by_name(name)
vm.start()
ip = vm.ip
if ip is None:
raise j.exceptions.RuntimeError("vm {} didn't receive an IP address".format(name))
data.ipPrivate = ip
data.ipPublic = prefab._executor.addr
job.service.model.actions['stop'].state = 'new'
job.service.saveAll()
def stop(job):
prefab = job.service.executor.prefab
data = job.service.model.data
name = job.service.name
vm = prefab.virtualization.kvm.machines.get_by_name(name)
vm.stop()
data.ipPrivate = ''
data.ipPublic = ''
job.service.model.actions['start'].state = 'new'
job.service.saveAll()
def uninstall(job):
prefab = job.service.executor.prefab
name = job.service.name
vm = prefab.virtualization.kvm.machines.get_by_name(name)
if vm.is_started:
vm.stop()
vm.delete()
job.service.model.data.ipPrivate = ''
job.service.model.data.ipPublic = ''
job.service.model.actions['install'].state = 'new'
job.service.saveAll()
|
mbarall/opensha-dev
|
src/scratch/kevin/BinaryFileRandomWriteTest.java
|
package scratch.kevin;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class BinaryFileRandomWriteTest {
private static void printFile(File binaryFile) throws IOException {
DataInputStream in = new DataInputStream(new FileInputStream(binaryFile));
System.out.println("CONTENTS");
int index = 0;
while (true) {
try {
System.out.println("\t"+(index++)+": "+in.readInt());
} catch (IOException e) {
System.out.println("---END---");
break;
}
}
in.close();
}
public static void main(String[] args) throws IOException {
File file = new File("/tmp/bin_test.bin");
DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
for (int i=0; i<10; i++)
out.writeInt(i);
out.close();
printFile(file);
FileOutputStream appendOut = new FileOutputStream(file, true);
out = new DataOutputStream(appendOut);
for (int i=0; i<10; i++)
out.writeInt(i);
out.close();
printFile(file);
// now try to rewrite the last part
RandomAccessFile raFile = new RandomAccessFile(file, "rw");
raFile.seek(40l);
appendOut = new FileOutputStream(raFile.getFD());
out = new DataOutputStream(appendOut);
for (int i=0; i<20; i++)
out.writeInt(i+1000);
out.close();
printFile(file);
}
}
|
lgoldstein/communitychest
|
chest/base-utils/jmx/src/main/java/net/community/chest/jmx/AbstractDynamicMBean.java
|
<filename>chest/base-utils/jmx/src/main/java/net/community/chest/jmx/AbstractDynamicMBean.java
package net.community.chest.jmx;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.DynamicMBean;
import net.community.chest.reflect.ClassUtil;
/**
* <P>Copyright 2007 as per GPLv2</P>
*
* <P>Provides some useful "shortcut" implementations for the {@link DynamicMBean}
* implementing classes</P>
*
* @author <NAME>.
* @since Aug 14, 2007 1:44:06 PM
*/
public abstract class AbstractDynamicMBean extends EmbeddedJMXErrorHandler implements DynamicMBean {
protected AbstractDynamicMBean (JMXErrorHandler eh)
{
super(eh);
}
protected AbstractDynamicMBean ()
{
this(null);
}
protected void handleSetAttributeException (final Attribute a, final Throwable t)
{
if ((null == a) || (null == t)) // just so compiler does not complain about un-referenced objects
throw errorThrowable(new IllegalArgumentException(ClassUtil.getExceptionLocation(getClass(), "handleSetAttributeException") + " incomplete arguments"));
}
/*
* @see javax.management.DynamicMBean#setAttributes(javax.management.AttributeList)
*/
@Override
public AttributeList setAttributes (final AttributeList attributes)
{
final int numAttrs=(null == attributes) ? 0 : attributes.size();
final AttributeList retVals=(numAttrs <= 0) ? new AttributeList() : new AttributeList(numAttrs);
for (int aIndex=0; aIndex < numAttrs; aIndex++)
{
final Attribute a=(Attribute) attributes.get(aIndex);
try
{
setAttribute(a);
retVals.add(a);
}
catch(Exception e)
{
handleSetAttributeException(a, e);
}
}
return retVals;
}
protected void handleGetAttributeException (final String attrName, final Throwable t)
{
if ((null == attrName) || (attrName.length() <= 0) || (null == t)) // just so compiler does not complain about un-referenced objects
throw errorThrowable(new IllegalArgumentException(ClassUtil.getExceptionLocation(getClass(), "handleGetAttributeException") + " incomplete arguments"));
}
/*
* @see javax.management.DynamicMBean#getAttributes(java.lang.String[])
*/
@Override
public AttributeList getAttributes (final String[] attributes)
{
final int numAttrs=(null == attributes) ? 0 : attributes.length;
final AttributeList retVals=(numAttrs <= 0) ? new AttributeList() : new AttributeList(numAttrs);
for (int aIndex=0; aIndex < numAttrs; aIndex++)
{
final String attrName=attributes[aIndex];
try
{
final Object attrValue=getAttribute(attrName);
final Attribute a=new Attribute(attrName, attrValue);
retVals.add(a);
}
catch(Exception e)
{
handleGetAttributeException(attrName, e);
}
}
return retVals;
}
}
|
ele-dev/IT-S_GameClient
|
src/GamePieces/SniperPiece.java
|
<filename>src/GamePieces/SniperPiece.java
package GamePieces;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import javax.swing.Timer;
import Particles.EmptyShell;
import Particles.TrailParticle;
import Projectiles.Bullet;
import Sound.SoundEffect;
import Stage.BoardRectangle;
import Stage.Commons;
import Stage.StagePanel;
public class SniperPiece extends GamePiece{
private Bullet sniperBullet;
public SniperPiece(boolean isRed, BoardRectangle boardRect) {
super(isRed, Commons.nameSniper, boardRect, Commons.dmgSniper, 2,Commons.neededLOSSniper);
attackDelayTimer = new Timer(1500,new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
angle = angleDesired;
shootOnce();
}
});
attackDelayTimer.setRepeats(false);
}
public void update() {
if(targetGamePiece != null) {
updateAngle(targetGamePiece.getPos());
}else if(targetDestructibleObject != null){
updateAngle(targetDestructibleObject.getPos());
}
updateAttack();
}
@Override
public boolean isAttacking() {
return attackDelayTimer.isRunning();
}
@Override
public void drawAttack(Graphics2D g2d) {}
// checks if the parameter Pos is a valid attack position (also if it is in line of sight)
@Override
public boolean checkAttacks(int selectedRow, int selectedColumn, int myRow, int myColumn) {
Rectangle rect1 = new Rectangle(myColumn-3,myRow-1,7,3);
Rectangle rect2 = new Rectangle(myColumn-1,myRow-3,3,7);
return rect1.contains(new Point(selectedColumn,selectedRow)) || rect2.contains(new Point(selectedColumn,selectedRow));
}
public void shootOnce() {
Arc2D aimArc = new Arc2D.Double(boardRect.getCenterX()-StagePanel.boardRectSize/2, boardRect.getCenterY()-StagePanel.boardRectSize/2,
StagePanel.boardRectSize, StagePanel.boardRectSize, 0, -angle-90, Arc2D.PIE);
Shape shape = targetGamePiece != null?targetGamePiece.getRectHitbox():
targetDestructibleObject.getRectHitbox();
sniperBullet = new Bullet((int)aimArc.getEndPoint().getX(), (int)aimArc.getEndPoint().getY(), StagePanel.boardRectSize/10, StagePanel.boardRectSize/4, isRed(),1,
angle, shape, targetDestructibleObject);
StagePanel.particles.add(new EmptyShell((float)getCenterX(), (float)getCenterY(),StagePanel.boardRectSize/8, StagePanel.boardRectSize/3, (float)angle -90, c,(float)(Math.random()*3+2)));
int i = 0;
while(true) {
if(i%2==0) {
int greyTone = (int)(Math.random()*90+10);
StagePanel.particles.add(new TrailParticle((int)(sniperBullet.getX() + (Math.random()-0.5)*10), (int)(sniperBullet.getY() + (Math.random()-0.5)*10),
(int)(Math.random()*3+5),(float)(Math.random()*-180),new Color(greyTone,greyTone,greyTone),(float) (Math.random()*0.1),
(float)(Math.random()*0.2+0.6),0));
}
sniperBullet.move();
sniperBullet.checkHitAnyTarget();
if(sniperBullet.hasHitTarget()) {
break;
}
i++;
// failsave
if(i > 500) {
break;
}
}
if(targetGamePiece != null) {
targetGamePiece.gamePieceBase.getDamaged(getDmg());
targetGamePiece = null;
}else {
targetDestructibleObject.getDamaged(getDmg(),sniperBullet.angle,isRed());
targetDestructibleObject = null;
}
sniperBullet = null;
StagePanel.applyScreenShake(5, 30);
SoundEffect.play("SniperShot.wav");
}
@Override
public void updateAttack() {}
}
|
shisheng-1/tapestry-5
|
tapestry-ioc/src/main/java/org/apache/tapestry5/ioc/def/ContributionDef.java
|
// 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.apache.tapestry5.ioc.def;
import org.apache.tapestry5.commons.*;
import org.apache.tapestry5.ioc.ModuleBuilderSource;
import org.apache.tapestry5.ioc.ServiceResources;
/**
* Contribution to a service configuration.
*
* The toString() method of the ContributionDef will be used for some exception reporting and should clearly identify
* where the contribution comes from; the normal behavior is to identify the class and method of the contribution
* method.
*/
public interface ContributionDef
{
/**
* Identifies the service contributed to.
*/
String getServiceId();
/**
* Performs the work needed to contribute into the standard, unordered configuration.
*
* @param moduleSource the source, if needed, of the module instance associated with the contribution
* @param resources allows access to services visible to the module
* @param configuration the unordered configuration into which values should be loaded. This instance will
* encapsulate all related error checks (such as passing of nulls or inappropriate classes).
*/
void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
Configuration configuration);
/**
* Performs the work needed to contribute into the ordered configuration.
*
* @param moduleSource the source, if needed, of the module instance associated with the contribution
* @param resources allows access to services visible to the module
* @param configuration the ordered configuration into which values should be loaded. This instance will encapsulate
* all related error checks (such as passing of nulls or inappropriate classes).
*/
void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
OrderedConfiguration configuration);
/**
* Performs the work needed to contribute into the mapped configuration.
*
* @param moduleSource the source, if needed, of the module instance associated with the contribution
* @param resources allows access to services visible to the module
* @param configuration the mapped configuration into which values should be loaded. This instance will encapsulate
* all related error checks (such as passing of null keys or values or inappropriate classes,
* or duplicate keys).
*/
void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
MappedConfiguration configuration);
}
|
kruegener/AutoPas
|
src/autopas/iterators/SingleCellIteratorWrapper.h
|
/**
* @file SingleCellIteratorWrapper.h
*
* @date 31 May 2018
* @author seckler
*/
#pragma once
#include "autopas/iterators/SingleCellIteratorInterface.h"
#include "autopas/utils/ExceptionHandler.h"
namespace autopas {
/**
* SingleCellIteratorWrapper class is the main class visible to the user to iterate over particles in one cell.
* The particles can be accessed using "iterator->" or "*iterator". The next particle using the ++operator, e.g.
* "++iteratorWrapper".
* @note The wrapper class provides an easy way to access the functions of the SingleCellIteratorInterface, e.g.
* allowing "iteratorWrapper->getR()" or "++iteratorWrapper". Without the wrapper class and using the
* ParticleIteratorInterface the calls would require de-referencing like:
* (*iteratorInterface)->getR() or "++(*iteratorWrapper)"
* @tparam Particle type of the particle that is accessed
*/
template <class Particle>
class SingleCellIteratorWrapper : public SingleCellIteratorInterface<Particle> {
public:
/**
* Constructor of the ParticleIteratorWrapper
* @param particleIteratorInterface
* @tparam InterfacePtrType type of the interface ptr
*/
template <class InterfacePtrType>
explicit SingleCellIteratorWrapper(InterfacePtrType *particleIteratorInterface)
: _particleIterator(
static_cast<internal::SingleCellIteratorInterfaceImpl<Particle> *>(particleIteratorInterface)) {}
/**
* copy constructor
* @param otherParticleIteratorWrapper the other ParticleIteratorWrapper
*/
SingleCellIteratorWrapper(const SingleCellIteratorWrapper &otherParticleIteratorWrapper) {
_particleIterator = std::unique_ptr<internal::SingleCellIteratorInterfaceImpl<Particle>>(
otherParticleIteratorWrapper._particleIterator->clone());
}
/**
* copy assignment constructor
* @param otherParticleIteratorWrapper the other ParticleIteratorWrapper
* @return the modified SingleCellIteratorWrapper
*/
SingleCellIteratorWrapper &operator=(const SingleCellIteratorWrapper &otherParticleIteratorWrapper) {
_particleIterator = std::unique_ptr<internal::SingleCellIteratorInterfaceImpl<Particle>>(
otherParticleIteratorWrapper._particleIterator->clone());
return *this;
}
inline SingleCellIteratorWrapper<Particle> &operator++() override final {
_particleIterator->operator++();
return *this;
}
inline Particle &operator*() const override final { return _particleIterator->operator*(); }
inline void deleteCurrentParticle() override final { _particleIterator->deleteCurrentParticle(); }
inline bool isValid() const override final { return _particleIterator->isValid(); }
inline bool operator==(const SingleCellIteratorInterface<Particle> &rhs) const override final {
return _particleIterator->operator==(rhs);
}
inline bool operator!=(const SingleCellIteratorInterface<Particle> &rhs) const override final {
return _particleIterator->operator!=(rhs);
}
inline size_t getIndex() const override final { return _particleIterator->getIndex(); }
/**
* Returns the stored single cell iterator.
* @return
*/
inline SingleCellIteratorInterface<Particle> *get() const { return _particleIterator.get(); }
private:
std::unique_ptr<internal::SingleCellIteratorInterfaceImpl<Particle>> _particleIterator;
};
} // namespace autopas
|
vusec/dsn-2016-osiris
|
llvm/tools/hypermemloganalyze/testpicker/testpicker.c
|
<reponame>vusec/dsn-2016-osiris
#include <assert.h>
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "coverage.h"
#include "debug.h"
#include "function.h"
#include "helper.h"
#include "minixtestlogsummarize.h"
#include "minixteststats.h"
#include "module.h"
struct list_onetest_test {
char *name;
};
struct list_onetest_fault {
struct list_onetest_fault *next;
char *faultspec;
size_t runtestcount;
const struct minixtest_stats_test **runtests;
};
static struct list_onetest_fault *list_onetest_faults;
static struct module_ll *modules;
static struct minixtest_stats stats;
static struct string_ll *setting_extratest;
static int setting_excludeboot;
static struct string_ll *setting_excludetest;
static int setting_multitest = 0;
static int setting_onetest = 0;
static int setting_posttest = 0;
static int setting_pretest = 0;
static int setting_printfaultspec = 0;
static void load_log(const char *logpath) {
struct run_classification classification;
struct minixtest_log_summary summary;
dbgprintf("loading log file %s\n", logpath);
minixtest_log_summarize(logpath, NULL, &summary);
minixtest_stats_add(&stats, &classification, &summary, 0, 0);
minixtest_log_summary_free(&summary);
}
static void load_map(const char *mappath) {
dbgprintf("loading map file %s\n", mappath);
module_load_from_map_ll(mappath, &modules);
}
static int faultspec_to_bbindex(const char *faultspec) {
int bbindex = -1;
int bbindex_glob, bbindex_mod;
const struct module *module;
const char *name;
ptrdiff_t namelen;
const char *p = faultspec;
if (!*faultspec) return -1;
for (;;) {
/* parse module name */
name = p;
while (*p && *p != ':') p++;
namelen = p - name;
if (namelen <= 0 || *p != ':') goto fail;
p++;
/* parse bb index */
bbindex_mod = 0;
while (*p >= '0' && *p <= '9') {
bbindex_mod = bbindex_mod * 10 + (*p - '0');
p++;
}
if (bbindex_mod <= 0) goto fail;
/* look up global bb index; note that bbindex_mod is 1-nased */
module = module_find_with_namelen(modules, name, namelen);
if (!module) {
fprintf(stderr, "warning: cannot find module %.*s in faultspec\n",
(int) namelen, name);
continue;
}
bbindex_glob = module_bbindex_to_global(module, bbindex_mod - 1);
if (bbindex_glob < 0) {
fprintf(stderr, "warning: cannot resolve faultspec "
"basic block index %.*s:%d\n",
(int) namelen, name, bbindex_mod);
continue;
}
if (bbindex < 0) {
bbindex = bbindex_glob;
} else if (bbindex != bbindex_glob) {
fprintf(stderr, "warning: inconsistent basic blocks "
"in faultspec: %s\n", faultspec);
return -1;
}
if (!*p) break;
if (*p != ':') goto fail;
p++;
}
return bbindex;
fail:
fprintf(stderr, "warning: incorrect faultspec: %s\n", faultspec);
return -1;
}
double stats_z2value(const struct stats *stats, double z) {
return stats_mean(stats) + z * stats_stdev(stats);
}
struct test_list_entry {
const struct minixtest_stats_test *test;
double runtime;
int covered;
int excluded;
int order;
int selected;
};
static int test_list_build_compare(const void *p1, const void *p2) {
const struct test_list_entry *entry1 = p1;
const struct test_list_entry *entry2 = p2;
if (entry1->order < entry2->order) return -1;
if (entry1->order > entry2->order) return 1;
return 0;
}
static void test_list_build(
struct test_list_entry **tests_p,
size_t *testcount_p,
int bbindex,
double runtimestdev) {
struct test_list_entry *entry;
const struct minixtest_stats_test *test;
struct test_list_entry *tests;
size_t testcount, testindex;
assert(tests_p);
assert(testcount_p);
/* if requested, avoid boot-time faults */
if (setting_excludeboot && stats.boot.coverage.bbs[bbindex] > 0) {
dbgprintf("skipping boot-time fault\n");
*testcount_p = 0;
*tests_p = NULL;
return;
}
/* allocate list of tests */
testcount = *testcount_p = minixtest_stats_counttests(stats.tests);
tests = *tests_p = CALLOC(testcount, struct test_list_entry);
/* fill list of tests */
testindex = 0;
dbgprintf("list of known tests\n");
for (test = stats.tests; test; test = test->next) {
entry = &tests[testindex++];
entry->test = test;
entry->runtime = stats_z2value(&test->duration, runtimestdev);
entry->covered = test->coverage.bbs[bbindex] > 0;
entry->excluded = string_ll_find(setting_excludetest, test->name);
entry->order = rand();
dbgprintf(" test %s covered=%d runtime=%.1fs\n",
test->name, entry->covered, entry->runtime);
}
assert(testindex == testcount);
/* shuffle by sorting on random key */
qsort(tests, testcount, sizeof(*tests), test_list_build_compare);
}
static int test_list_select_one(
struct test_list_entry *tests,
size_t testcount,
double *runtime_p,
int covered) {
int i;
int retry;
double runtime = *runtime_p;
int runtimefactor;
int selectedmax = 0;
struct test_list_entry *test;
assert(tests || testcount == 0);
assert(runtime_p);
assert(covered == 0 || covered == 1);
if (covered) {
runtimefactor = 1;
} else {
runtimefactor = setting_pretest + setting_posttest;
assert(runtimefactor > 0);
}
/* select one test and adjust the remaining runtime accordingly */
do {
retry = 0;
for (i = 0; i < testcount; i++) {
test = &tests[i];
if (test->excluded) continue;
if (test->covered != covered) continue;
if (test->runtime * runtimefactor > runtime) continue;
if (test->selected > selectedmax) {
if (setting_multitest) retry = 1;
continue;
}
*runtime_p = runtime - test->runtime * runtimefactor;
test->selected++;
dbgprintf("test %s selected covered=%d\n",
test->test->name, covered);
return 1;
}
selectedmax++;
} while (retry);
return 0;
}
static void test_list_select(
struct test_list_entry *tests,
size_t testcount,
double runtime,
int *selected_p) {
int uncovered = setting_pretest || setting_posttest;
assert(tests || testcount == 0);
dbgprintf("runtime before selecting tests: %.1fs\n", runtime);
/* require at least one covered test */
if (!test_list_select_one(tests, testcount, &runtime, 1)) return;
*selected_p = 1;
/* alternately select covered and uncovered tests until runtime runs out */
while ((uncovered && test_list_select_one(tests, testcount, &runtime, 0)) ||
test_list_select_one(tests, testcount, &runtime, 1)) {
}
dbgprintf("runtime after selecting tests: %.1fs\n", runtime);
}
static void test_list_print(
const struct test_list_entry *tests,
size_t testcount,
const char *faultspec) {
int covered, first = 1, i, retry, selected, step;
const struct test_list_entry *test;
/* sequence:
* - uncovered tests (pre-test)
* - covered tests (workload)
* - covered tests again (workload)
* - uncovered tests again (post-test)
*/
for (step = 0; step < 3; step++) {
if (step == 0 && !setting_pretest) continue;
if (step == 2 && !setting_posttest) continue;
covered = step == 1;
selected = 1;
do {
retry = 0;
for (i = 0; i < testcount; i++) {
test = &tests[i];
if (test->selected < selected) continue;
if (test->covered != covered) continue;
if (first) {
first = 0;
if (setting_printfaultspec) {
printf("%s\t", faultspec);
}
} else {
printf(" ");
}
printf("%s", test->test->name);
if (test->selected > selected) retry = 1;
}
selected++;
} while(retry);
}
if (!first || !setting_printfaultspec) {
printf("\n");
}
}
static size_t test_list_select_onetest_iterate(
struct test_list_entry *tests,
size_t testcount,
const struct minixtest_stats_test **runtests) {
size_t count = 0;
int i;
struct test_list_entry *test;
for (i = 0; i < testcount; i++) {
test = &tests[i];
if (!test->covered) continue;
if (test->excluded) continue;
if (runtests) runtests[count] = test->test;
count++;
}
return count;
}
static void test_list_select_onetest(
struct test_list_entry *tests,
size_t testcount,
int *selected_p,
const char *faultspec) {
struct list_onetest_fault *fault = CALLOC(1, struct list_onetest_fault);
/* add fault to linked list */
fault->next = list_onetest_faults;
fault->faultspec = STRDUP(faultspec);
list_onetest_faults = fault;
/* count tests */
fault->runtestcount = test_list_select_onetest_iterate(
tests, testcount, NULL);
/* list tests */
fault->runtests = CALLOC(fault->runtestcount,
const struct minixtest_stats_test *);
test_list_select_onetest_iterate(
tests, testcount, fault->runtests);
if (fault->runtestcount > 0) *selected_p = 1;
}
static void select_test_with_faultspec(
const char *faultspec,
double runtime,
double runtimestdev,
int *selected_p) {
int bbindex;
const struct minixtest_stats_test *test;
struct string_ll *testname;
struct test_list_entry *tests;
size_t testcount;
dbgprintf("selecting tests for faultspec %s\n", faultspec);
/* look up which global basic block this faultspec refers to */
bbindex = faultspec_to_bbindex(faultspec);
if (bbindex < 0) {
dbgprintf("bb index not found for faultspec %s\n", faultspec);
printf("\n");
return;
}
dbgprintf("bb index %d for faultspec %s\n", bbindex, faultspec);
/* make a list of tests */
test_list_build(&tests, &testcount, bbindex, runtimestdev);
/* adjust available for boot time and time between tests */
runtime -= stats_z2value(&stats.boot.duration, runtimestdev);
runtime -= stats_z2value(&stats.between.duration, runtimestdev);
for (testname = setting_extratest; testname; testname = testname->next) {
test = minixtest_stats_find_test(&stats, testname->str);
if (!test) {
fprintf(stderr, "warning: extra test %s not "
"in golden run\n", testname->str);
continue;
}
runtime -= stats_z2value(&test->duration, runtimestdev);
}
if (runtime <= 0) {
fprintf(stderr, "error: not enough runtime after "
"boot+extra tests: %.1fs\n", runtime);
exit(1);
}
if (setting_onetest) {
/* select and print one test at a time */
test_list_select_onetest(tests, testcount,
selected_p, faultspec);
} else {
/* select a suitable number of tests */
test_list_select(tests, testcount, runtime, selected_p);
/* print a list of selected tests, uncovered ones first (as pre-test) */
test_list_print(tests, testcount, faultspec);
}
if (tests) FREE(tests);
}
static void select_tests_with_faultfile(
FILE *faultfile,
double runtime,
double runtimestdev,
int *selected_p) {
int c;
int comment = 0;
char faultspec[1024];
size_t faultspeclen = 0;
assert(faultfile);
/* parse the file line by line; ech line has any number of
* modulename:bbindex pairs separated by colons, optionally followed by
* and @-sign and a comment. The specified bbindex is 1-based.
*/
for (;;) {
c = fgetc(faultfile);
if (c == EOF || c == '\n') {
if (c == EOF && faultspeclen == 0) break;
faultspec[faultspeclen] = 0;
select_test_with_faultspec(faultspec, runtime, runtimestdev, selected_p);
if (c == EOF) break;
faultspeclen = 0;
comment = 0;
continue;
}
if (comment) continue;
if (c == '@') {
comment = 1;
continue;
}
if (faultspeclen + 1 >= sizeof(faultspec)) {
fprintf(stderr, "error: faultspec too long\n");
return;
}
faultspec[faultspeclen++] = c;
}
}
static void select_tests(
const char *faultpath,
double runtime,
double runtimestdev,
int *selected_p) {
FILE *file;
assert(faultpath);
file = fopen(faultpath, "r");
if (!file) {
fprintf(stderr, "error: could not open fault file %s: %s\n",
faultpath, strerror(errno));
return;
}
select_tests_with_faultfile(file, runtime, runtimestdev, selected_p);
fclose(file);
}
static void print_tests_onetest(void) {
int done, index;
const struct list_onetest_fault *fault;
index = 0;
do {
done = 1;
for (fault = list_onetest_faults; fault; fault = fault->next) {
if (index >= fault->runtestcount) continue;
if (setting_printfaultspec) {
printf("%s\t", fault->faultspec);
}
printf("%1$s %1$s\n", fault->runtests[index]->name);
done = 0;
}
index++;
} while (!done);
}
static void list_onetest_free(void) {
struct list_onetest_fault *fault, *faultnext;
fault = list_onetest_faults;
while (fault) {
faultnext = fault->next;
if (fault->faultspec) FREE(fault->faultspec);
if (fault->runtests) FREE(fault->runtests);
FREE(fault);
fault = faultnext;
}
}
static void usage(const char *msg) {
printf("%s\n", msg);
printf("\n");
printf("usage:\n");
printf(" testpicker [-bfmopP] [-r runtime] [-R stdev] [-s seed] [-x testname]...\n");
printf(" [-X testname]... faultpath mappath... logpath...\n");
printf("\n");
printf("faultpath indicates where the faultpicker output is stored. Each line\n");
printf("in this file specifies a colon-separated list of module:bbindex pairs,\n");
printf("optionally followed by an @-sign and a comment. The output lines match\n");
printf("match up with lines from this file.\n");
printf("\n");
printf("Optional parameters:\n");
printf("-b - Don't pick tests for faults triggered during boot\n");
printf("-f - Write the faultspec followed by a tab at the start of each line,\n");
printf(" omitting faultspecs that are not reached by any tests.\n");
printf("-m - Allow tests to be run multiple times to fill up available time.\n");
printf("-o - Select just one test and run it twice; fault types can be\n");
printf(" repeated if they have multiple triggering tests.\n");
printf("-p - Pretest: run uncovered tests before covered tests.\n");
printf("-P - Posttest: run uncovered tests after covered tests\n");
printf(" (same as pretest if both specified).\n");
printf("-r runtime - Total runtime (in seconds) available to boot the system and\n");
printf(" execute all the tests; default: 14 minutes.\n");
printf("-R stdev - How many standard deviations to add to the average runtime\n");
printf(" to account for variation; default: 2.\n");
printf("-s seed - Random seed used to get reproducable results. If not specified,\n");
printf(" a random seed is derived from the current system time.\n");
printf("-x testname - Add extra runtime corresponding to the specified test.\n");
printf("-X testname - Exclude (do not select) the test with the specified name.\n");
exit(1);
}
int main(int argc, char **argv) {
const char *faultpath, *path;
struct function_hashtable *functions;
int r;
double runtime = 600; /* 10 minutes */
int runtime_spec = 0;
double runtimestdev = 1;
int runtimestdev_spec = 0;
int seed = 0, seed_spec = 0;
int selected = 0;
struct timeval timeval;
/* handle options */
while ((r = getopt(argc, argv, "bfmopPr:R:s:x:X:")) >= 0) {
switch (r) {
case 'b':
setting_excludeboot = 1;
break;
case 'f':
setting_printfaultspec = 1;
break;
case 'm':
setting_multitest = 1;
break;
case 'o':
setting_onetest = 1;
break;
case 'p':
setting_pretest = 1;
break;
case 'P':
setting_posttest = 1;
break;
case 'r':
if (runtime_spec) usage("Parameter -r specified multiple times");
runtime = atof(optarg);
runtime_spec = 1;
if (runtime <= 0) usage("Parameter runtime has an invalid value");
break;
case 'R':
if (runtimestdev_spec) usage("Parameter -R specified multiple times");
runtimestdev = atof(optarg);
runtimestdev_spec = 1;
break;
case 's':
if (seed_spec) usage("Parameter -s specified multiple times");
seed = atoi(optarg);
seed_spec = 1;
break;
case 'x':
string_ll_add(&setting_extratest, optarg);
break;
case 'X':
string_ll_add(&setting_excludetest, optarg);
break;
default:
usage("Unknown flag specified");
break;
}
}
if (setting_onetest && !setting_printfaultspec) usage("Parameter -o requires -f");
if (setting_onetest && setting_multitest) usage("Parameter -o cannot be combined with -m");
if (setting_onetest && setting_pretest) usage("Parameter -o cannot be combined with -p");
if (setting_onetest && setting_posttest) usage("Parameter -o cannot be combined with -P");
if (setting_onetest && runtime_spec) usage("Parameter -o cannot be combined with -r");
if (setting_onetest && runtimestdev_spec) usage("Parameter -o cannot be combined with -R");
/* read faultpath parameter */
if (optind >= argc) usage("Parameter faultpath not specified");
faultpath = argv[optind++];
/* load map files */
while (optind < argc) {
path = argv[optind++];
if (ends_with(path, ".map", 1)) {
load_map(path);
} else {
load_log(path);
}
}
if (!modules) usage("No map files specified");
/* further initalization */
if (!seed_spec) {
timeval = gettimeofday_checked();
seed = 1000000 * timeval.tv_sec + timeval.tv_usec;
}
dbgprintf("seed=%d\n", seed);
srand(seed);
/* make overview of functions */
functions = functions_build_table(modules);
minixtest_stats_init_coverage(&stats, functions);
/* select tests */
select_tests(faultpath, runtime, runtimestdev, &selected);
if (!selected) {
fprintf(stderr, "error: no faults selected\n");
return -1;
}
/* in case of onetest, interleave tests for different faults */
if (setting_onetest) {
print_tests_onetest();
}
/* clean up */
list_onetest_free();
minixtest_stats_free(&stats);
functions_free(functions);
modules_free(modules);
modules = NULL;
return 0;
}
|
whywhywhyw/o3de
|
Gems/AWSCore/Code/Source/ResourceMapping/AWSResourceMappingConstants.h
|
<reponame>whywhywhyw/o3de
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
namespace AWSCore
{
static constexpr const char AWSChinaRegionPrefix[] = "cn-";
static constexpr const char AWSFeatureGemRESTApiIdKeyNameSuffix[] = ".RESTApiId";
static constexpr const char AWSFeatureGemRESTApiStageKeyNameSuffix[] = ".RESTApiStage";
static constexpr const char ResourceMappingAccountIdKeyName[] = "AccountId";
static constexpr const char ResourceMappingResourcesKeyName[] = "AWSResourceMappings";
static constexpr const char ResourceMappingNameIdKeyName[] = "Name/ID";
static constexpr const char ResourceMappingRegionKeyName[] = "Region";
static constexpr const char ResourceMappingTypeKeyName[] = "Type";
static constexpr const char ResourceMappingVersionKeyName[] = "Version";
static constexpr const char ResourceMapppingJsonSchemaFilePath[] =
"Gems/AWSCore/resource_mapping_schema.json";
} // namespace AWSCore
|
leandog/brazenhead
|
features/step_definitions/robotium_steps.rb
|
<filename>features/step_definitions/robotium_steps.rb
When /^I do nothing but "(.*?)"$/ do |method|
@driver.send method
end
Then /^I should receive "(.*?)"$/ do |json|
@driver.last_response.body.should match json
end
When /^I call a method with an integer$/ do
@driver.scroll_up_list(0)
end
When /^I call a method with a string$/ do
@driver.search_button('will not find')
end
When /^I call a method with a long$/ do
@driver.wait_for_text('Views', 1, 5000)
end
When /^I call a method with a float$/ do
@driver.click_on_screen(100.0, 100.0)
end
When /^I call a method with a boolean$/ do
@driver.search_text('Views', true)
end
Then /^I should receive a successful result$/ do
@driver.last_response.code.should eq '200'
end
When /^I call "(.*?)" and then I call "(.*?)"$/ do |first_method, next_method|
@driver.chain_calls do |driver|
driver.send first_method
driver.send next_method
end
end
Then /^the result should match "(.*?)"$/ do |result|
@driver.last_response.body.should match Regexp.new(result)
end
Then /^I should see "(.*?)"$/ do |text|
@driver.search_text text
@driver.last_json.should be_true
end
|
kahammond/kontent-docs-samples
|
android/filtering-content/GetItemById.java
|
// DocSection: filtering_get_item_by_id
List<object> items = deliveryService.<object>items()
// Gets item by its ID
.equalsFilter("system.id", "2f7288a1-cfc8-47be-9bf1-b1d312f7da18")
// EndDocSection
|
charbu01/galen
|
src/test/java/net/mindengine/galen/tests/action/GalenPageActionRunJavascriptTest.java
|
<gh_stars>0
/*******************************************************************************
* Copyright 2014 <NAME> http://mindengine.net
*
* 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 net.mindengine.galen.tests.action;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import net.mindengine.galen.browser.Browser;
import net.mindengine.galen.browser.SeleniumBrowser;
import net.mindengine.galen.suite.GalenPageTest;
import net.mindengine.galen.suite.actions.GalenPageActionRunJavascript;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class GalenPageActionRunJavascriptTest {
private static final String TEST_URL = "file://" + GalenPageActionCheckTest.class.getResource("/html/page-for-js-check.html").getPath();
@Test public void shouldRun_javascriptFile_andPerformActions_onBrowser() throws Exception {
WebDriver driver = new FirefoxDriver();
Browser browser = new SeleniumBrowser(driver);
browser.load(TEST_URL);
WebElement element = driver.findElement(By.id("search-query"));
assertThat("Search input should not contain any text yet", element.getAttribute("value"), is(""));
GalenPageActionRunJavascript action = new GalenPageActionRunJavascript("/scripts/to-run-1.js");
action.setJsonArguments("{prefix: 'This was'}");
action.execute(browser, new GalenPageTest(), null);
assertThat("Search input should contain text", element.getAttribute("value"), is("This was typed by a selenium from javascript text from imported script"));
browser.quit();
}
}
|
szerfas1/or-tools
|
docs/cpp_linear/search/enumvalues_10.js
|
var searchData=
[
['xpress_5flinear_5fprogramming_1807',['XPRESS_LINEAR_PROGRAMMING',['../classoperations__research_1_1_m_p_solver.html#a76c87990aabadd148304b95332a60ff8a3097f16057930e83bce90546640bdd82',1,'operations_research::MPSolver']]],
['xpress_5fmixed_5finteger_5fprogramming_1808',['XPRESS_MIXED_INTEGER_PROGRAMMING',['../classoperations__research_1_1_m_p_solver.html#a76c87990aabadd148304b95332a60ff8a5a62faa5ec0ffed2abbc2d526bd53286',1,'operations_research::MPSolver']]]
];
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/c-c++-common/raw-string-9.c
|
// Make sure that we properly handle trigraphs in raw strings when
// trigraphs are disabled, too.
// { dg-options "-std=gnu99" { target c } }
// { dg-options "-std=gnu++0x" { target c++ } }
// { dg-do run }
const char b[] = "??>"; // { dg-message "-trigraphs" }
const char a[] = R"(??>??)??/
??)";
#define TEST(str, val) \
if (sizeof (str) != sizeof (val) \
|| __builtin_memcmp (str, val, sizeof (str)) != 0) \
__builtin_abort ()
int main()
{
TEST (a, "?\?>?\?)?\?/\n?\?");
}
|
sammiler/GDStash_Pro
|
src/org/gdstash/ui/character/GDCharShrineAct1Pane.java
|
<filename>src/org/gdstash/ui/character/GDCharShrineAct1Pane.java
/* */ package org.gdstash.ui.character;
/* */ import java.awt.*;
/* */
/* */ import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/* */ import java.util.LinkedList;
import java.util.List;
/* */ import javax.swing.BorderFactory;
/* */ import javax.swing.GroupLayout;
/* */ import javax.swing.JCheckBox;
/* */ import javax.swing.UIManager;
/* */ import javax.swing.border.Border;
/* */ import javax.swing.border.TitledBorder;
/* */ import org.gdstash.character.GDChar;
/* */ import org.gdstash.character.GDCharShrineList;
/* */ import org.gdstash.character.GDCharUID;
/* */ import org.gdstash.db.DBShrine;
/* */ import org.gdstash.ui.GDStashFrame;
/* */ import org.gdstash.ui.util.GDAbstractShrinePane;
import org.gdstash.util.GDMsgFormatter;
/* */
/* */ public class GDCharShrineAct1Pane extends GDAbstractShrinePane {
/* */ private JCheckBox cbBurialHill;
/* */ private JCheckBox cbDevilsAquifier;
/* */ private JCheckBox cbWightmireCavern;
/* */ private JCheckBox cbFloodedPassage;
/* */ private JCheckBox cbBurialCave;
/* */ private JCheckBox cbHallowedHill;
/* */ private JCheckBox cbBurrwitchEstates;
/* */ private JCheckBox cbUndergroundTransit;
/* */ private JCheckBox cbCraigsCrags;
/* */ private JCheckBox cbGuardianDreeg;
/* */ private JCheckBox cbTempleThree;
/* */ private int difficulty;
/* */ private boolean changed;
/* */
/* */ private class ChangeActionListener implements ActionListener {
/* */ public void actionPerformed(ActionEvent e) {
/* 36 */ GDCharShrineAct1Pane.this.changed = true;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ private ChangeActionListener() {}
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public GDCharShrineAct1Pane(int difficulty, int direction) {
/* 56 */ this.difficulty = difficulty;
/* 57 */ this.changed = false;
/* */
/* 59 */ adjustUI();
/* */
/* 61 */ GroupLayout layout = null;
/* 62 */ GroupLayout.SequentialGroup hGroup = null;
/* 63 */ GroupLayout.SequentialGroup vGroup = null;
/* */
/* 65 */ layout = new GroupLayout((Container)this);
/* 66 */ setLayout(layout);
/* */
/* 68 */ layout.setAutoCreateGaps(true);
/* */
/* */
/* 71 */ layout.setAutoCreateContainerGaps(true);
/* */
/* */
/* 74 */ hGroup = layout.createSequentialGroup();
/* */
/* */
/* 77 */ hGroup
/* 78 */ .addGroup(layout.createParallelGroup()
/* 79 */ .addComponent(this.cbBurialHill)
/* 80 */ .addComponent(this.cbDevilsAquifier)
/* 81 */ .addComponent(this.cbWightmireCavern)
/* 82 */ .addComponent(this.cbFloodedPassage)
/* 83 */ .addComponent(this.cbBurialCave)
/* 84 */ .addComponent(this.cbHallowedHill)
/* 85 */ .addComponent(this.cbBurrwitchEstates)
/* 86 */ .addComponent(this.cbUndergroundTransit)
/* 87 */ .addComponent(this.cbCraigsCrags)
/* 88 */ .addComponent(this.cbGuardianDreeg)
/* 89 */ .addComponent(this.cbTempleThree));
/* */
/* */
/* 92 */ vGroup = layout.createSequentialGroup();
/* */
/* */
/* 95 */ vGroup
/* 96 */ .addGroup(layout.createParallelGroup()
/* 97 */ .addComponent(this.cbBurialHill))
/* 98 */ .addGroup(layout.createParallelGroup()
/* 99 */ .addComponent(this.cbDevilsAquifier))
/* 100 */ .addGroup(layout.createParallelGroup()
/* 101 */ .addComponent(this.cbWightmireCavern))
/* 102 */ .addGroup(layout.createParallelGroup()
/* 103 */ .addComponent(this.cbFloodedPassage))
/* 104 */ .addGroup(layout.createParallelGroup()
/* 105 */ .addComponent(this.cbBurialCave))
/* 106 */ .addGroup(layout.createParallelGroup()
/* 107 */ .addComponent(this.cbHallowedHill))
/* 108 */ .addGroup(layout.createParallelGroup()
/* 109 */ .addComponent(this.cbBurrwitchEstates))
/* 110 */ .addGroup(layout.createParallelGroup()
/* 111 */ .addComponent(this.cbUndergroundTransit))
/* 112 */ .addGroup(layout.createParallelGroup()
/* 113 */ .addComponent(this.cbCraigsCrags))
/* 114 */ .addGroup(layout.createParallelGroup()
/* 115 */ .addComponent(this.cbGuardianDreeg))
/* 116 */ .addGroup(layout.createParallelGroup()
/* 117 */ .addComponent(this.cbTempleThree));
/* */
/* 119 */ if (direction == 0) {
/* 120 */ layout.setHorizontalGroup(vGroup);
/* 121 */ layout.setVerticalGroup(hGroup);
/* */ } else {
/* 123 */ layout.setHorizontalGroup(hGroup);
/* 124 */ layout.setVerticalGroup(vGroup);
/* */ }
/* */
/* 127 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbDevilsAquifier });
/* 128 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbWightmireCavern });
/* 129 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbFloodedPassage });
/* 130 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbBurialCave });
/* 131 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbHallowedHill });
/* 132 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbBurrwitchEstates });
/* 133 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbUndergroundTransit });
/* 134 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbCraigsCrags });
/* 135 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbGuardianDreeg });
/* 136 */ layout.linkSize(0, new Component[] { this.cbBurialHill, this.cbTempleThree });
/* */
/* 138 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbDevilsAquifier });
/* 139 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbWightmireCavern });
/* 140 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbFloodedPassage });
/* 141 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbBurialCave });
/* 142 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbHallowedHill });
/* 143 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbBurrwitchEstates });
/* 144 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbUndergroundTransit });
/* 145 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbCraigsCrags });
/* 146 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbGuardianDreeg });
/* 147 */ layout.linkSize(1, new Component[] { this.cbBurialHill, this.cbTempleThree });
/* */ }
/* */
/* */
/* */ public void adjustUI() {
/* 152 */ Font fntLabel = UIManager.getDefaults().getFont("Label.font");
/* 153 */ Font fntCheck = UIManager.getDefaults().getFont("CheckBox.font");
/* 154 */ if (fntCheck == null) fntCheck = fntLabel;
/* 155 */ Font fntBorder = UIManager.getDefaults().getFont("TitledBorder.font");
/* 156 */ if (fntBorder == null) fntBorder = fntLabel;
/* */
/* 158 */ fntLabel = fntLabel.deriveFont(GDStashFrame.iniConfig.sectUI.fontSize);
/* 159 */ fntCheck = fntCheck.deriveFont(GDStashFrame.iniConfig.sectUI.fontSize);
/* 160 */ fntBorder = fntBorder.deriveFont(GDStashFrame.iniConfig.sectUI.fontSize);
/* */
/* 162 */ Border lowered = BorderFactory.createEtchedBorder(1);
/* 163 */ Border raised = BorderFactory.createEtchedBorder(0);
/* 164 */ Border compound = BorderFactory.createCompoundBorder(raised, lowered);
/* 165 */ TitledBorder text = BorderFactory.createTitledBorder(compound, GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_ACT1"));
/* 166 */ text.setTitleFont(fntBorder);
/* */
/* 168 */ setBorder(text);
/* */
/* 170 */ if (this.cbBurialHill == null) {
/* 171 */ this.cbBurialHill = new JCheckBox();
/* */
/* 173 */ this.cbBurialHill.addActionListener(new ChangeActionListener());
/* */ }
/* 175 */ this.cbBurialHill.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_BURIAL_HILL"));
/* 176 */ this.cbBurialHill.setFont(fntCheck);
/* */
/* 178 */ if (this.cbDevilsAquifier == null) {
/* 179 */ this.cbDevilsAquifier = new JCheckBox();
/* */
/* 181 */ this.cbDevilsAquifier.addActionListener(new ChangeActionListener());
/* */ }
/* 183 */ this.cbDevilsAquifier.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_DEVILS_AQUIFIER"));
/* 184 */ this.cbDevilsAquifier.setFont(fntCheck);
/* */
/* 186 */ if (this.cbWightmireCavern == null) {
/* 187 */ this.cbWightmireCavern = new JCheckBox();
/* */
/* 189 */ this.cbWightmireCavern.addActionListener(new ChangeActionListener());
/* */ }
/* 191 */ this.cbWightmireCavern.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_WIGHTMIRE_CAVERN"));
/* 192 */ this.cbWightmireCavern.setFont(fntCheck);
/* */
/* 194 */ if (this.cbFloodedPassage == null) {
/* 195 */ this.cbFloodedPassage = new JCheckBox();
/* */
/* 197 */ this.cbFloodedPassage.addActionListener(new ChangeActionListener());
/* */ }
/* 199 */ this.cbFloodedPassage.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_FLOODED_PASSAGE"));
/* 200 */ this.cbFloodedPassage.setFont(fntCheck);
/* */
/* 202 */ if (this.cbBurialCave == null) {
/* 203 */ this.cbBurialCave = new JCheckBox();
/* */
/* 205 */ this.cbBurialCave.addActionListener(new ChangeActionListener());
/* */ }
/* 207 */ this.cbBurialCave.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_BURIAL_CAVE"));
/* 208 */ this.cbBurialCave.setFont(fntCheck);
/* */
/* 210 */ if (this.cbHallowedHill == null) {
/* 211 */ this.cbHallowedHill = new JCheckBox();
/* */
/* 213 */ this.cbHallowedHill.addActionListener(new ChangeActionListener());
/* */ }
/* 215 */ this.cbHallowedHill.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_HALLOWED_HILL"));
/* 216 */ this.cbHallowedHill.setFont(fntCheck);
/* */
/* 218 */ if (this.cbBurrwitchEstates == null) {
/* 219 */ this.cbBurrwitchEstates = new JCheckBox();
/* */
/* 221 */ this.cbBurrwitchEstates.addActionListener(new ChangeActionListener());
/* */ }
/* 223 */ this.cbBurrwitchEstates.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_BURRWITCH_ESTATES"));
/* 224 */ this.cbBurrwitchEstates.setFont(fntCheck);
/* */
/* 226 */ if (this.cbUndergroundTransit == null) {
/* 227 */ this.cbUndergroundTransit = new JCheckBox();
/* */
/* 229 */ this.cbUndergroundTransit.addActionListener(new ChangeActionListener());
/* */ }
/* 231 */ this.cbUndergroundTransit.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_UNDERGROUND_TRANSIT"));
/* 232 */ this.cbUndergroundTransit.setFont(fntCheck);
/* */
/* 234 */ if (this.cbCraigsCrags == null) {
/* 235 */ this.cbCraigsCrags = new JCheckBox();
/* */
/* 237 */ this.cbCraigsCrags.addActionListener(new ChangeActionListener());
/* */ }
/* 239 */ this.cbCraigsCrags.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_CRAIGS_CRAGS"));
/* 240 */ this.cbCraigsCrags.setFont(fntCheck);
/* */
/* 242 */ if (this.cbGuardianDreeg == null) {
/* 243 */ this.cbGuardianDreeg = new JCheckBox();
/* */
/* 245 */ this.cbGuardianDreeg.setEnabled(false);
/* */ }
/* */
/* 248 */ this.cbGuardianDreeg.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_GUARDIAN_OF_DREEG"));
/* 249 */ this.cbGuardianDreeg.setFont(fntCheck);
/* */
/* 251 */ if (this.cbTempleThree == null) {
/* 252 */ this.cbTempleThree = new JCheckBox();
/* */
/* 254 */ this.cbTempleThree.addActionListener(new ChangeActionListener());
/* */ }
/* 256 */ this.cbTempleThree.setText(GDMsgFormatter.getString(GDMsgFormatter.rbGD, "TXT_SHRINE_01_TEMPLE_OF_THE_THREE"));
/* 257 */ this.cbTempleThree.setFont(fntCheck);
/* */ }
/* */
/* */
/* */ public boolean hasChanged() {
/* 262 */ return this.changed;
/* */ }
/* */
/* */
/* */ public void setChanged(boolean changed) {
/* 267 */ this.changed = changed;
/* */ }
/* */
/* */ public void setSelected(boolean selected) {
/* 271 */ this.cbBurialHill.setSelected(selected);
/* 272 */ this.cbDevilsAquifier.setSelected(selected);
/* 273 */ this.cbWightmireCavern.setSelected(selected);
/* 274 */ this.cbFloodedPassage.setSelected(selected);
/* 275 */ this.cbBurialCave.setSelected(selected);
/* 276 */ this.cbHallowedHill.setSelected(selected);
/* 277 */ this.cbBurrwitchEstates.setSelected(selected);
/* 278 */ this.cbUndergroundTransit.setSelected(selected);
/* 279 */ this.cbCraigsCrags.setSelected(selected);
/* 280 */ this.cbGuardianDreeg.setSelected(selected);
/* 281 */ this.cbTempleThree.setSelected(selected);
/* */ }
/* */
/* */
/* */ public List<GDCharUID> getShrineList(boolean found) {
/* 286 */ List<GDCharUID> list = new LinkedList<>();
/* */
/* 288 */ if (this.cbBurialHill.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_BURIAL_HILL);
/* 289 */ if (this.cbDevilsAquifier.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_DEVILS_AQUIFIER);
/* 290 */ if (this.cbWightmireCavern.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_WIGHTMIRE_CAVERN);
/* 291 */ if (this.cbFloodedPassage.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_FLOODED_PASSAGE);
/* 292 */ if (this.cbBurialCave.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_BURIAL_CAVE);
/* 293 */ if (this.cbHallowedHill.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_HALLOWED_HILL);
/* 294 */ if (this.cbBurrwitchEstates.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_BURRWITCH_ESTATES);
/* 295 */ if (this.cbUndergroundTransit.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_UNDERGROUND_TRANSIT);
/* 296 */ if (this.cbCraigsCrags.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_CRAIGS_CRAGS);
/* 297 */ if (this.cbGuardianDreeg.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_GUARDIAN_DREEG);
/* 298 */ if (this.cbTempleThree.isSelected() == found) list.add(GDCharShrineList.UID_SHRINE_01_TEMPLE_THREE);
/* */
/* 300 */ return list;
/* */ }
/* */
/* */
/* */ public void setChar(GDChar gdc) {
/* 305 */ setSelected(false);
/* */
/* 307 */ this.changed = false;
/* */
/* 309 */ boolean expFG = GDStashFrame.expansionForgottenGods;
/* */
/* 311 */ if (gdc != null) {
/* 312 */ expFG = (expFG || gdc.isForgottenGodsChar());
/* */ }
/* */
/* 315 */ DBShrine.Info info = null;
/* */
/* 317 */ info = DBShrine.getShrineInfo("devotionshrinea01.dbr", this.difficulty);
/* 318 */ this.cbBurialHill.setEnabled(info.active);
/* */
/* 320 */ info = DBShrine.getShrineInfo("devotionshrinea06.dbr", this.difficulty);
/* 321 */ this.cbDevilsAquifier.setEnabled(info.active);
/* */
/* 323 */ info = DBShrine.getShrineInfo("devotionshrinea02.dbr", this.difficulty);
/* 324 */ this.cbWightmireCavern.setEnabled(info.active);
/* */
/* 326 */ info = DBShrine.getShrineInfo("devotionshrinea04.dbr", this.difficulty);
/* 327 */ this.cbFloodedPassage.setEnabled(info.active);
/* */
/* 329 */ info = DBShrine.getShrineInfo("devotionshrinea03.dbr", this.difficulty);
/* 330 */ this.cbBurialCave.setEnabled(info.active);
/* */
/* 332 */ info = DBShrine.getShrineInfo("devotionshrinen04.dbr", this.difficulty);
/* 333 */ this.cbHallowedHill.setEnabled(info.active);
/* 334 */ this.cbHallowedHill.setVisible((info.exists || expFG));
/* */
/* 336 */ info = DBShrine.getShrineInfo("devotionshrinea05.dbr", this.difficulty);
/* 337 */ this.cbBurrwitchEstates.setEnabled(info.active);
/* */
/* 339 */ info = DBShrine.getShrineInfo("devotionshrinea07.dbr", this.difficulty);
/* 340 */ this.cbUndergroundTransit.setEnabled(info.active);
/* */
/* 342 */ info = DBShrine.getShrineInfo("devotionshrinea08.dbr", this.difficulty);
/* 343 */ this.cbCraigsCrags.setEnabled(info.active);
/* */
/* 345 */ info = DBShrine.getShrineInfo("devotionshrinen10.dbr", this.difficulty);
/* 346 */ this.cbGuardianDreeg.setEnabled(info.active);
/* 347 */ this.cbGuardianDreeg.setVisible((info.exists || expFG));
/* */
/* 349 */ info = DBShrine.getShrineInfo("devotionshrinen03.dbr", this.difficulty);
/* 350 */ this.cbTempleThree.setEnabled(info.active);
/* 351 */ this.cbTempleThree.setVisible((info.exists || expFG));
/* */
/* 353 */ if (gdc == null)
/* */ return;
/* 355 */ List<GDCharUID> list = gdc.getRestoredShrinesList(this.difficulty);
/* */
/* 357 */ for (GDCharUID uid : list) {
/* 358 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_BURIAL_HILL)) this.cbBurialHill.setSelected(true);
/* 359 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_DEVILS_AQUIFIER)) this.cbDevilsAquifier.setSelected(true);
/* 360 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_WIGHTMIRE_CAVERN)) this.cbWightmireCavern.setSelected(true);
/* 361 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_FLOODED_PASSAGE)) this.cbFloodedPassage.setSelected(true);
/* 362 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_BURIAL_CAVE)) this.cbBurialCave.setSelected(true);
/* 363 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_HALLOWED_HILL)) this.cbHallowedHill.setSelected(true);
/* 364 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_BURRWITCH_ESTATES)) this.cbBurrwitchEstates.setSelected(true);
/* 365 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_UNDERGROUND_TRANSIT)) this.cbUndergroundTransit.setSelected(true);
/* 366 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_CRAIGS_CRAGS)) this.cbCraigsCrags.setSelected(true);
/* 367 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_GUARDIAN_DREEG)) this.cbGuardianDreeg.setSelected(true);
/* 368 */ if (uid.equals(GDCharShrineList.UID_SHRINE_01_TEMPLE_THREE)) this.cbTempleThree.setSelected(true);
/* */ }
/* */ }
/* */ }
/* Location: C:\game\Grim Dawn\GDStash.jar!\org\gdstas\\ui\character\GDCharShrineAct1Pane.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
alissonkbprado/orange-talents-07-template-ecommerce
|
src/main/java/br/com/zupacademy/alissonprado/mercadolivre/model/ImagemProduto.java
|
<filename>src/main/java/br/com/zupacademy/alissonprado/mercadolivre/model/ImagemProduto.java<gh_stars>0
package br.com.zupacademy.alissonprado.mercadolivre.model;
import org.hibernate.validator.constraints.URL;
import org.springframework.util.Assert;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Entity
public class ImagemProduto {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String nome;
private String url;
@ManyToOne
private Produto produto;
/**
* Não utilizar.
* Criado por exigencia da JPA
*/
@Deprecated
public ImagemProduto() {
}
public ImagemProduto(Long id) {
this.id = id;
}
/**
*
* @param nome NotBlank
* @param produtoUsuarioLogado NotNull, Produto deve pertencer ao Usuario logado.
*/
public ImagemProduto(@NotBlank String nome, @NotBlank @URL String url, @NotNull Produto produtoUsuarioLogado) {
Assert.hasText(nome, "Você deve passar o nome da imagem.");
Assert.hasText(url, "Você deve passar a url da imagem do produto");
Assert.notNull(produtoUsuarioLogado, "O Produto não pode ser nulo");
this.nome = nome;
this.url = url;
this.produto = produtoUsuarioLogado;
}
public Long getId() {
return id;
}
public String getNome() {
return nome;
}
public String getUrl() {
return url;
}
}
|
EnanderW/Minestom
|
src/main/java/net/minestom/server/event/EntityEvent.java
|
package net.minestom.server.event;
import net.minestom.server.entity.Entity;
import org.jetbrains.annotations.NotNull;
public class EntityEvent extends Event {
protected final Entity entity;
public EntityEvent(@NotNull Entity entity) {
this.entity = entity;
}
/**
* Gets the entity of this event.
*
* @return the entity
*/
@NotNull
public Entity getEntity() {
return entity;
}
}
|
LarryNguyen/ECSim-
|
INET_EC/physicallayer/contract/packetlevel/IPathLoss.h
|
//
// Copyright (C) 2013 OpenSim Ltd.
//
// This program 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
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#ifndef __INET_IPATHLOSS_H
#define __INET_IPATHLOSS_H
#include "inet/physicallayer/contract/packetlevel/IArrival.h"
#include "inet/physicallayer/contract/packetlevel/ITransmission.h"
namespace inet {
namespace physicallayer {
/**
* This interface models path loss (or path attenuation) that is the reduction
* in power density of a radio signal as it propagates through space.
*/
class INET_API IPathLoss : public IPrintableObject
{
public:
/**
* Returns the loss factor for the provided transmission and arrival.
* The value is in the range [0, 1] where 1 means no loss at all and 0
* means all power is lost.
*/
virtual double computePathLoss(const ITransmission *transmission, const IArrival *arrival) const = 0;
/**
* Returns the loss factor as a function of propagation speed, carrier
* frequency and distance. The value is in the range [0, 1] where 1 means
* no loss at all and 0 means all power is lost.
*/
virtual double computePathLoss(mps propagationSpeed, Hz frequency, m distance) const = 0;
/**
* Returns the range for the given loss factor. The value is in the range
* [0, +infinity) or NaN if unspecified.
*/
virtual m computeRange(mps propagationSpeed, Hz frequency, double loss) const = 0;
};
} // namespace physicallayer
} // namespace inet
#endif // ifndef __INET_IPATHLOSS_H
|
yura-hb/sesame-sampled-pairs
|
samples/36/b.java
|
<filename>samples/36/b.java
import java.util.LinkedList;
class MemoryHistory implements History {
/**
* Return the content of the current buffer.
*/
public CharSequence current() {
if (index >= size()) {
return "";
}
return items.get(index);
}
private int index = 0;
private final LinkedList<CharSequence> items = new LinkedList<CharSequence>();
public int size() {
return items.size();
}
}
|
google-cloud-sdk-unofficial/google-cloud-sdk
|
lib/googlecloudsdk/command_lib/beyondcorp/app/connectors/hooks.py
|
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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.
"""Hooks for beyondcorp app connections commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.beyondcorp.app import util as api_util
from googlecloudsdk.command_lib.beyondcorp.app import util as command_util
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import exceptions
def CheckFieldsSpecified(unused_ref, args, patch_request):
"""Check that update command has one of these flags specified."""
update_args = [
'clear_labels',
'remove_labels',
'update_labels',
'display_name',
]
if any(args.IsSpecified(update_arg) for update_arg in update_args):
return patch_request
raise exceptions.Error(
'Must specify at least one field to update. Try --help.')
def UpdateLabels(unused_ref, args, patch_request):
"""Updates labels of connector."""
labels_diff = labels_util.Diff.FromUpdateArgs(args)
if labels_diff.MayHaveUpdates():
patch_request = command_util.AddFieldToUpdateMask('labels', patch_request)
messages = api_util.GetMessagesModule(args.calliope_command.ReleaseTrack())
if patch_request.connector is None:
patch_request.connector = messages.Connector()
new_labels = labels_diff.Apply(messages.Connector.LabelsValue,
patch_request.connector.labels).GetOrNone()
if new_labels:
patch_request.connector.labels = new_labels
return patch_request
def UpdateLabelsFlags():
"""Defines flags for updating labels."""
return command_util.UpdateLabelsFlags()
|
fciubotaru/z-pec
|
ZimbraServer/src/java-test/com/zimbra/cs/service/mail/SearchTest.java
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2012 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.service.mail;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.collect.Maps;
import com.zimbra.common.soap.Element;
import com.zimbra.common.soap.MailConstants;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.DeliveryOptions;
import com.zimbra.cs.mailbox.Flag;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.mailbox.Message;
public class SearchTest {
@BeforeClass
public static void init() throws Exception {
MailboxTestUtil.initServer();
Provisioning prov = Provisioning.getInstance();
prov.createAccount("<EMAIL>", "secret", Maps.<String, Object>newHashMap());
}
@Before
public void setUp() throws Exception {
MailboxTestUtil.clearData();
}
@Test
public void mute() throws Exception {
Account acct = Provisioning.getInstance().getAccountById(MockProvisioning.DEFAULT_ACCOUNT_ID);
Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(acct);
// setup: add a message
DeliveryOptions dopt = new DeliveryOptions().setFolderId(Mailbox.ID_FOLDER_INBOX).setFlags(Flag.BITMASK_UNREAD | Flag.BITMASK_MUTED);
Message msg = mbox.addMessage(null, MailboxTestUtil.generateMessage("test subject"), dopt, null);
Assert.assertTrue("root unread", msg.isUnread());
Assert.assertTrue("root muted", msg.isTagged(Flag.FlagInfo.MUTED));
// search for the conversation (normal)
Element request = new Element.XMLElement(MailConstants.SEARCH_REQUEST).addAttribute(MailConstants.A_SEARCH_TYPES, "conversation");
request.addAttribute(MailConstants.E_QUERY, "test", Element.Disposition.CONTENT);
Element response = new Search().handle(request, ServiceTestUtil.getRequestContext(acct));
List<Element> hits = response.listElements(MailConstants.E_CONV);
Assert.assertEquals("1 hit", 1, hits.size());
Assert.assertEquals("correct hit", msg.getConversationId(), hits.get(0).getAttributeLong(MailConstants.A_ID));
// search for the conversation (no muted items)
request.addAttribute(MailConstants.A_INCLUDE_TAG_MUTED, false);
response = new Search().handle(request, ServiceTestUtil.getRequestContext(acct));
hits = response.listElements(MailConstants.E_CONV);
Assert.assertTrue("no hits", hits.isEmpty());
}
}
|
ACS106129/uml-editor
|
src/uml/listener/tool/ToolListenerStub.java
|
package uml.listener.tool;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import uml.listener.Listener;
public class ToolListenerStub extends ComponentAdapter implements Listener, ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
e.getSource();
}
@Override
public void addToComponent(final Component comp) {
}
}
|
kapw001/Workcation
|
app/src/main/java/com/droidsonroids/workcation/screens/main/map/DetailsFragment.java
|
package com.droidsonroids.workcation.screens.main.map;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Scene;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import butterknife.BindView;
import com.droidsonroids.workcation.R;
import com.droidsonroids.workcation.common.maps.MapBitmapCache;
import com.droidsonroids.workcation.common.maps.PulseOverlayLayout;
import com.droidsonroids.workcation.common.model.Place;
import com.droidsonroids.workcation.common.mvp.MvpFragment;
import com.droidsonroids.workcation.common.transitions.ScaleDownImageTransition;
import com.droidsonroids.workcation.common.transitions.TransitionUtils;
import com.droidsonroids.workcation.common.views.HorizontalRecyclerViewScrollListener;
import com.droidsonroids.workcation.common.views.TranslateItemAnimator;
import com.droidsonroids.workcation.screens.main.MainActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import java.util.ArrayList;
import java.util.List;
public class DetailsFragment extends MvpFragment<DetailsFragmentView, DetailsFragmentPresenter>
implements DetailsFragmentView, OnMapReadyCallback, BaliPlacesAdapter.OnPlaceClickListener, HorizontalRecyclerViewScrollListener.OnItemCoverListener {
public static final String TAG = DetailsFragment.class.getSimpleName();
@BindView(R.id.recyclerview) RecyclerView recyclerView;
@BindView(R.id.container) FrameLayout containerLayout;
@BindView(R.id.mapOverlayLayout) PulseOverlayLayout mapOverlayLayout;
private List<Place> baliPlaces;
private BaliPlacesAdapter baliAdapter;
private String currentTransitionName;
private Scene detailsScene;
public static Fragment newInstance(final Context ctx) {
DetailsFragment fragment = new DetailsFragment();
ScaleDownImageTransition transition = new ScaleDownImageTransition(ctx, MapBitmapCache.instance().getBitmap());
transition.addTarget(ctx.getString(R.string.mapPlaceholderTransition));
transition.setDuration(600);
fragment.setEnterTransition(transition);
return fragment;
}
@Override
protected DetailsFragmentPresenter createPresenter() {
return new DetailsFragmentPresenterImpl();
}
@Override
public void onBackPressed() {
if (detailsScene != null) {
presenter.onBackPressedWithScene();
} else {
((MainActivity) getActivity()).superOnBackPressed();
}
}
private View getSharedViewByPosition(final int childPosition) {
for (int i = 0; i < recyclerView.getChildCount(); i++) {
if (childPosition == recyclerView.getChildAdapterPosition(recyclerView.getChildAt(i))) {
return recyclerView.getChildAt(i);
}
}
return null;
}
@Override
public int getLayout() {
return R.layout.fragment_details;
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupBaliData();
setupMapFragment();
setupRecyclerView();
}
private void setupBaliData() {
presenter.provideBaliData();
}
private void setupMapFragment() {
((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.mapFragment)).getMapAsync(this);
}
private void setupRecyclerView() {
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
baliAdapter = new BaliPlacesAdapter(this, getActivity());
}
@Override
public void onMapReady(final GoogleMap googleMap) {
mapOverlayLayout.setupMap(googleMap);
setupGoogleMap();
addDataToRecyclerView();
}
private void setupGoogleMap() {
presenter.moveMapAndAddMarker();
}
private void addDataToRecyclerView() {
recyclerView.setItemAnimator(new TranslateItemAnimator());
recyclerView.setAdapter(baliAdapter);
baliAdapter.setPlacesList(baliPlaces);
recyclerView.addOnScrollListener(new HorizontalRecyclerViewScrollListener(this));
}
@Override
public void onPlaceClicked(final View sharedView, final String transitionName, final int position) {
currentTransitionName = transitionName;
detailsScene = DetailsLayout.showScene(getActivity(), containerLayout, sharedView, transitionName, baliPlaces.get(position));
drawRoute(position);
hideAllMarkers();
}
private void drawRoute(final int position) {
presenter.drawRoute(mapOverlayLayout.getCurrentLatLng(), position);
}
private void hideAllMarkers() {
mapOverlayLayout.setOnCameraIdleListener(null);
mapOverlayLayout.hideAllMarkers();
}
@Override
public void drawPolylinesOnMap(final ArrayList<LatLng> polylines) {
getActivity().runOnUiThread(() -> mapOverlayLayout.addPolyline(polylines));
}
@Override
public void provideBaliData(final List<Place> places) {
baliPlaces = places;
}
@Override
public void onBackPressedWithScene(final LatLngBounds latLngBounds) {
int childPosition = TransitionUtils.getItemPositionFromTransition(currentTransitionName);
DetailsLayout.hideScene(getActivity(), containerLayout, getSharedViewByPosition(childPosition), currentTransitionName);
notifyLayoutAfterBackPress(childPosition);
mapOverlayLayout.onBackPressed(latLngBounds);
detailsScene = null;
}
private void notifyLayoutAfterBackPress(final int childPosition) {
containerLayout.removeAllViews();
containerLayout.addView(recyclerView);
recyclerView.requestLayout();
baliAdapter.notifyItemChanged(childPosition);
}
@Override
public void moveMapAndAddMaker(final LatLngBounds latLngBounds) {
mapOverlayLayout.moveCamera(latLngBounds);
mapOverlayLayout.setOnCameraIdleListener(() -> {
for (int i = 0; i < baliPlaces.size(); i++) {
mapOverlayLayout.createAndShowMarker(i, baliPlaces.get(i).getLatLng());
}
mapOverlayLayout.setOnCameraIdleListener(null);
});
mapOverlayLayout.setOnCameraMoveListener(mapOverlayLayout::refresh);
}
@Override
public void updateMapZoomAndRegion(final LatLng northeastLatLng, final LatLng southwestLatLng) {
getActivity().runOnUiThread(() -> {
mapOverlayLayout.animateCamera(new LatLngBounds(southwestLatLng, northeastLatLng));
mapOverlayLayout.setOnCameraIdleListener(() -> mapOverlayLayout.drawStartAndFinishMarker());
});
}
@Override
public void onItemCover(final int position) {
mapOverlayLayout.showMarker(position);
}
}
|
antoinelefloch/cpp-netlib
|
libs/network/example/rss/main.cpp
|
// Copyright (c) <NAME> 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "rss.hpp"
#include <boost/network/protocol/http/client.hpp>
#include <boost/foreach.hpp>
#include <iostream>
int main(int argc, char * argv[]) {
using namespace boost::network;
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <url>" << std::endl;
return 1;
}
try {
http::client client;
http::client::request request(argv[1]);
request << header("Connection", "close");
http::client::response response = client.get(request);
rss::channel channel(response);
std::cout << "Channel: " << channel.title() << " (" << channel.description() << ")" << std::endl;
BOOST_FOREACH(const rss::item &item, channel) {
std::cout << item.title() << " (" << item.author() << ")" << std::endl;
}
}
catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
|
b15145456/learning_cpp
|
Operator Overloading/main.cpp
|
<reponame>b15145456/learning_cpp
#include <iostream>
#include "Sally.h"
#include "Sally.cpp"
using namespace std;
int main(){
Sally a(34);
Sally b(21);
Sally c;
c = a + b;
cout << c.num << endl;
}
|
VitaliPekelis/Android-Interviews
|
src/arrays/MergeSortedArray.java
|
<reponame>VitaliPekelis/Android-Interviews
package arrays;
import java.util.Arrays;
public class MergeSortedArray {
/**
* 88. Merge Sorted Array (little changed)
* https://leetcode.com/problems/merge-sorted-array/
* */
public static int[] mergeSortedArray(int[] numbers1, int[] numbers2) {
if(numbers1 == null && numbers2 == null) {
return new int[0];
} else if (numbers1 == null) {
return numbers2;
} else if (numbers2 == null) {
return numbers1;
}
int index1 = 0, index2 = 0, resultIndex = 0;
int[] result = new int[numbers1.length + numbers2.length];
while(index1 <= numbers1.length - 1 && index2 <= numbers2.length - 1) {
if(numbers1[index1] <= numbers2[index2]) {
result[resultIndex] = numbers1[index1++];
} else if(numbers2[index2] < numbers1[index1]) {
result[resultIndex] = numbers2[index2++];
}
resultIndex++;
}
while (index1 <= numbers1.length - 1) {
result[resultIndex++] = numbers1[index1++];
}
while (index2 <= numbers2.length - 1) {
result[resultIndex++] = numbers2[index2++];
}
return result;
}
public static void main(String[] args) {
int[] arr1 = {1, 5, 9, 19};
int[] arr2 = {2, 3, 3, 6, 10};
long startTime = System.nanoTime();
System.out.println("increment one result " + Arrays.toString(mergeSortedArray(arr1, arr2)));
long endTime = System.nanoTime();
System.out.println("That took " + (endTime - startTime) + " nano milliseconds " + "and milliseconds = " +(endTime - startTime)/1000000);
}
}
|
Process-Creative/Slate
|
packages/slate-ajax-collection/src/filter/CollectionFilters.js
|
<reponame>Process-Creative/Slate
import { Filter, TagFilter, OPERATION_AND } from './filters/';
export class CollectionFilters {
constructor(template) {
this.template = template;
this.filters = [];
this.facets = [];
}
isFiltering() {
return this.filters.some(f => {
if(f.getSettings() && f.getSettings().length) return true;
return false;
});
}
addFilter(filter) {
if(this.filters.indexOf(filter) !== -1) return;
this.filters.push(filter);
}
addFacet(facet) {
if(this.facets.indexOf(facet) !== -1) return;
this.facets.push(facet);
facet.print();
}
removeFilter(filter) {
let index = this.filters.indexOf(filter);
if(index === -1) return;
this.filters.splice(index, 1);
}
removeFacet(facet) {
let index = this.facets.indexOf(facet);
if(index === -1) return;
this.facets.splice(index, 1);
}
clearFilters() {
this.filters.forEach(f => f.setSettings(null));
}
load() {
let { settings } = this.template.settings;
//Take the settinsg and give them to our filters
Object.entries(settings).forEach(([key,value]) => {
this.filters.some(filter => {
if(!filter || filter.handle != key) return false;
filter.setSettings(value);
return true;
});
});
if(settings.tags) {
// let done = this.filters.some(filter => {
// if(!(filter instanceof TagFilter)) return false;
// if(settings.tags.length > 1 && filter.operation !== OPERATION_AND) return false;
// filter.setSettings(settings.tags);
// return true;
// });
//
// if(!done) {
this.urlTagFilter = new TagFilter(this.template, 'tags', OPERATION_AND, settings.tags)
this.addFilter(this.urlTagFilter);
// }
}
this.facets.forEach(facet => facet.print());
}
onFilterUpdate() {
//Filters should call this when something causes them to change.
//This function will trigger facets to be redrawn, followed by products, and then settings to be saved
let settings = {};
this.filters.forEach(filter => settings[filter.handle] = filter.getSettings());
this.template.settings.setSettings(settings);
this.facets.forEach(facet => facet.onFilterUpdate());
//Fire pre-queue event
if(this.template.onFilterChange) this.template.onFilterChange();
//Queue a redraw of products
this.template.draw.queueDraw();
}
onProductsFetched() {
this.facets.forEach(facet => facet.onProductsFetched());
}
onProductsDrawn() {
this.facets.forEach(facet => facet.onProductsDrawn());
}
}
|
gummybuns/dorm
|
tests/cerami/datatype/translator/integer_translator_test.py
|
from tests.helpers.testbase import TestBase
from cerami.datatype import Number
from cerami.datatype.translator import IntegerTranslator
class TestIntegerTranslator(TestBase):
def setUp(self):
self.dt = Number()
self.translator = IntegerTranslator(self.dt)
def test_format_for_dynamodb(self):
"""it returns the value as a string"""
assert self.translator.format_for_dynamodb(1) == '1'
def test_format_for_cerami(self):
"""it returns the value as an int"""
assert self.translator.format_for_cerami('1') == 1
|
PolRod/aleph
|
lib/github/commit.rb
|
module Github
module Commit
ENDPOINT = URI.join(Github::ROOT_ENDPOINT, 'repos/', "#{Github::OWNER}/", "#{Github::REPO}/", 'git/', 'commits').to_s
AUTHOR_KEYS = %w(
name
email
date
)
def self.get(sha)
raise 'invalid sha #{sha} when retrieving github commit' unless Github.valid_sha?(sha)
resp = Github.get("#{ENDPOINT}/#{sha}")
raise "Github commit retrieve failed with http code: #{resp.code}" if resp.code != '200'
ActiveSupport::JSON.decode(resp.body)
end
# @param - message: The commit message
# @param - tree: The SHA of the tree object this commit points to
# @param - parents: Array of strings.
# The SHAs of the commits that were the parents of this commit. If omitted or empty, the commit will be written as a root commit.
# For a single parent, an array of one SHA should be provided; for a merge commit, an array of more than one should be provided.
# @return - commit sha
def self.create(message, tree, parents, author={})
input = {
'message' => message,
'tree' => tree,
'parents' => parents
}
author.slice!(*AUTHOR_KEYS)
input.merge!({'author' => author}) if author.present?
resp = Github.post(ENDPOINT, input)
raise "Github commit POST failed with http code: #{resp.code}" if resp.code != '201'
ActiveSupport::JSON.decode(resp.body)['sha']
end
end
end
|
KwangjoJeong/Boost
|
Example/interprocess_09/main.cpp
|
#include <boost/interprocess/managed_shared_memory.hpp>
#include <iostream>
using namespace boost::interprocess;
int main()
{
shared_memory_object::remove("Boost");
managed_shared_memory managed_shm{open_or_create, "Boost", 1024};
int *i = managed_shm.find_or_construct<int>("Integer")(99);
std::cout << *i << '\n';
managed_shm.destroy<int>("Integer");
std::pair<int*, std::size_t> p = managed_shm.find<int>("Integer");
std::cout << p.first << '\n';
}
|
warchef/TaViNAV
|
src/main/java/hu/warchef/nav/domain/alpha/InvoiceQueryParamsType.java
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2
// See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2021.03.31 at 04:47:25 PM CEST
//
package hu.warchef.nav.domain.alpha;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* Invoice query parameters
*
* <p>Java class for InvoiceQueryParamsType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="InvoiceQueryParamsType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="invoiceIssueDateFrom" type="{http://schemas.nav.gov.hu/OSA/1.0/data}DateType"/>
* <element name="invoiceIssueDateTo" type="{http://schemas.nav.gov.hu/OSA/1.0/data}DateType"/>
* <element name="customerTaxNumber" type="{http://schemas.nav.gov.hu/OSA/1.0/data}TaxpayerIdType" minOccurs="0"/>
* <element name="invoiceCategory" type="{http://schemas.nav.gov.hu/OSA/1.0/data}InvoiceCategoryType" minOccurs="0"/>
* <element name="paymentMethod" type="{http://schemas.nav.gov.hu/OSA/1.0/data}PaymentMethodType" minOccurs="0"/>
* <element name="invoiceAppearance" type="{http://schemas.nav.gov.hu/OSA/1.0/data}InvoiceAppearanceType" minOccurs="0"/>
* <element name="source" type="{http://schemas.nav.gov.hu/OSA/1.0/api}SourceType" minOccurs="0"/>
* <element name="invoiceDeliveryGreaterThan" type="{http://schemas.nav.gov.hu/OSA/1.0/data}DateType" minOccurs="0"/>
* <element name="invoiceDeliveryLessThan" type="{http://schemas.nav.gov.hu/OSA/1.0/data}DateType" minOccurs="0"/>
* <element name="currency" type="{http://schemas.nav.gov.hu/OSA/1.0/data}CurrencyType" minOccurs="0"/>
* <element name="invoiceNetAmountGreaterThan" type="{http://schemas.nav.gov.hu/OSA/1.0/data}MonetaryType" minOccurs="0"/>
* <element name="invoiceNetAmountLessThan" type="{http://schemas.nav.gov.hu/OSA/1.0/data}MonetaryType" minOccurs="0"/>
* <element name="invoiceVatAmountHUFGreaterThan" type="{http://schemas.nav.gov.hu/OSA/1.0/data}MonetaryType" minOccurs="0"/>
* <element name="invoiceVatAmountHUFLessThan" type="{http://schemas.nav.gov.hu/OSA/1.0/data}MonetaryType" minOccurs="0"/>
* <element name="transactionParams" type="{http://schemas.nav.gov.hu/OSA/1.0/api}InvoiceQueryTransactionType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InvoiceQueryParamsType", namespace = "http://schemas.nav.gov.hu/OSA/1.0/api", propOrder = {
"invoiceIssueDateFrom",
"invoiceIssueDateTo",
"customerTaxNumber",
"invoiceCategory",
"paymentMethod",
"invoiceAppearance",
"source",
"invoiceDeliveryGreaterThan",
"invoiceDeliveryLessThan",
"currency",
"invoiceNetAmountGreaterThan",
"invoiceNetAmountLessThan",
"invoiceVatAmountHUFGreaterThan",
"invoiceVatAmountHUFLessThan",
"transactionParams"
})
public class InvoiceQueryParamsType {
@XmlElement(required = true)
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar invoiceIssueDateFrom;
@XmlElement(required = true)
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar invoiceIssueDateTo;
protected String customerTaxNumber;
@XmlSchemaType(name = "string")
protected InvoiceCategoryType invoiceCategory;
@XmlSchemaType(name = "string")
protected PaymentMethodType paymentMethod;
@XmlSchemaType(name = "string")
protected InvoiceAppearanceType invoiceAppearance;
@XmlSchemaType(name = "string")
protected SourceType source;
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar invoiceDeliveryGreaterThan;
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar invoiceDeliveryLessThan;
protected String currency;
protected BigDecimal invoiceNetAmountGreaterThan;
protected BigDecimal invoiceNetAmountLessThan;
protected BigDecimal invoiceVatAmountHUFGreaterThan;
protected BigDecimal invoiceVatAmountHUFLessThan;
protected InvoiceQueryTransactionType transactionParams;
/**
* Gets the value of the invoiceIssueDateFrom property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInvoiceIssueDateFrom() {
return invoiceIssueDateFrom;
}
/**
* Sets the value of the invoiceIssueDateFrom property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setInvoiceIssueDateFrom(XMLGregorianCalendar value) {
this.invoiceIssueDateFrom = value;
}
/**
* Gets the value of the invoiceIssueDateTo property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInvoiceIssueDateTo() {
return invoiceIssueDateTo;
}
/**
* Sets the value of the invoiceIssueDateTo property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setInvoiceIssueDateTo(XMLGregorianCalendar value) {
this.invoiceIssueDateTo = value;
}
/**
* Gets the value of the customerTaxNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCustomerTaxNumber() {
return customerTaxNumber;
}
/**
* Sets the value of the customerTaxNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCustomerTaxNumber(String value) {
this.customerTaxNumber = value;
}
/**
* Gets the value of the invoiceCategory property.
*
* @return
* possible object is
* {@link InvoiceCategoryType }
*
*/
public InvoiceCategoryType getInvoiceCategory() {
return invoiceCategory;
}
/**
* Sets the value of the invoiceCategory property.
*
* @param value
* allowed object is
* {@link InvoiceCategoryType }
*
*/
public void setInvoiceCategory(InvoiceCategoryType value) {
this.invoiceCategory = value;
}
/**
* Gets the value of the paymentMethod property.
*
* @return
* possible object is
* {@link PaymentMethodType }
*
*/
public PaymentMethodType getPaymentMethod() {
return paymentMethod;
}
/**
* Sets the value of the paymentMethod property.
*
* @param value
* allowed object is
* {@link PaymentMethodType }
*
*/
public void setPaymentMethod(PaymentMethodType value) {
this.paymentMethod = value;
}
/**
* Gets the value of the invoiceAppearance property.
*
* @return
* possible object is
* {@link InvoiceAppearanceType }
*
*/
public InvoiceAppearanceType getInvoiceAppearance() {
return invoiceAppearance;
}
/**
* Sets the value of the invoiceAppearance property.
*
* @param value
* allowed object is
* {@link InvoiceAppearanceType }
*
*/
public void setInvoiceAppearance(InvoiceAppearanceType value) {
this.invoiceAppearance = value;
}
/**
* Gets the value of the source property.
*
* @return
* possible object is
* {@link SourceType }
*
*/
public SourceType getSource() {
return source;
}
/**
* Sets the value of the source property.
*
* @param value
* allowed object is
* {@link SourceType }
*
*/
public void setSource(SourceType value) {
this.source = value;
}
/**
* Gets the value of the invoiceDeliveryGreaterThan property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInvoiceDeliveryGreaterThan() {
return invoiceDeliveryGreaterThan;
}
/**
* Sets the value of the invoiceDeliveryGreaterThan property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setInvoiceDeliveryGreaterThan(XMLGregorianCalendar value) {
this.invoiceDeliveryGreaterThan = value;
}
/**
* Gets the value of the invoiceDeliveryLessThan property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInvoiceDeliveryLessThan() {
return invoiceDeliveryLessThan;
}
/**
* Sets the value of the invoiceDeliveryLessThan property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setInvoiceDeliveryLessThan(XMLGregorianCalendar value) {
this.invoiceDeliveryLessThan = value;
}
/**
* Gets the value of the currency property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCurrency() {
return currency;
}
/**
* Sets the value of the currency property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCurrency(String value) {
this.currency = value;
}
/**
* Gets the value of the invoiceNetAmountGreaterThan property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getInvoiceNetAmountGreaterThan() {
return invoiceNetAmountGreaterThan;
}
/**
* Sets the value of the invoiceNetAmountGreaterThan property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setInvoiceNetAmountGreaterThan(BigDecimal value) {
this.invoiceNetAmountGreaterThan = value;
}
/**
* Gets the value of the invoiceNetAmountLessThan property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getInvoiceNetAmountLessThan() {
return invoiceNetAmountLessThan;
}
/**
* Sets the value of the invoiceNetAmountLessThan property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setInvoiceNetAmountLessThan(BigDecimal value) {
this.invoiceNetAmountLessThan = value;
}
/**
* Gets the value of the invoiceVatAmountHUFGreaterThan property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getInvoiceVatAmountHUFGreaterThan() {
return invoiceVatAmountHUFGreaterThan;
}
/**
* Sets the value of the invoiceVatAmountHUFGreaterThan property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setInvoiceVatAmountHUFGreaterThan(BigDecimal value) {
this.invoiceVatAmountHUFGreaterThan = value;
}
/**
* Gets the value of the invoiceVatAmountHUFLessThan property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getInvoiceVatAmountHUFLessThan() {
return invoiceVatAmountHUFLessThan;
}
/**
* Sets the value of the invoiceVatAmountHUFLessThan property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setInvoiceVatAmountHUFLessThan(BigDecimal value) {
this.invoiceVatAmountHUFLessThan = value;
}
/**
* Gets the value of the transactionParams property.
*
* @return
* possible object is
* {@link InvoiceQueryTransactionType }
*
*/
public InvoiceQueryTransactionType getTransactionParams() {
return transactionParams;
}
/**
* Sets the value of the transactionParams property.
*
* @param value
* allowed object is
* {@link InvoiceQueryTransactionType }
*
*/
public void setTransactionParams(InvoiceQueryTransactionType value) {
this.transactionParams = value;
}
}
|
raggi/xgt
|
libraries/vendor/rocksdb/db/compaction/compaction_service_test.cc
|
<gh_stars>10-100
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
#ifndef ROCKSDB_LITE
#include "db/db_test_util.h"
#include "port/stack_trace.h"
namespace ROCKSDB_NAMESPACE {
class MyTestCompactionService : public CompactionService {
public:
MyTestCompactionService(const std::string& db_path,
std::shared_ptr<FileSystem> fs, Options& options)
: db_path_(db_path), fs_(fs), options_(options) {}
static const char* kClassName() { return "MyTestCompactionService"; }
const char* Name() const override { return kClassName(); }
CompactionServiceJobStatus Start(const std::string& compaction_service_input,
int job_id) override {
InstrumentedMutexLock l(&mutex_);
jobs_.emplace(job_id, compaction_service_input);
CompactionServiceJobStatus s = CompactionServiceJobStatus::kSuccess;
TEST_SYNC_POINT_CALLBACK("MyTestCompactionService::Start::End", &s);
return s;
}
CompactionServiceJobStatus WaitForComplete(
int job_id, std::string* compaction_service_result) override {
std::string compaction_input;
{
InstrumentedMutexLock l(&mutex_);
auto i = jobs_.find(job_id);
if (i == jobs_.end()) {
return CompactionServiceJobStatus::kFailure;
}
compaction_input = std::move(i->second);
jobs_.erase(i);
}
CompactionServiceOptionsOverride options_override;
options_override.env = options_.env;
options_override.file_checksum_gen_factory =
options_.file_checksum_gen_factory;
options_override.comparator = options_.comparator;
options_override.merge_operator = options_.merge_operator;
options_override.compaction_filter = options_.compaction_filter;
options_override.compaction_filter_factory =
options_.compaction_filter_factory;
options_override.prefix_extractor = options_.prefix_extractor;
options_override.table_factory = options_.table_factory;
options_override.sst_partitioner_factory = options_.sst_partitioner_factory;
Status s = DB::OpenAndCompact(
db_path_, db_path_ + "/" + ROCKSDB_NAMESPACE::ToString(job_id),
compaction_input, compaction_service_result, options_override);
TEST_SYNC_POINT_CALLBACK("MyTestCompactionService::WaitForComplete::End",
compaction_service_result);
compaction_num_.fetch_add(1);
if (s.ok()) {
return CompactionServiceJobStatus::kSuccess;
} else {
return CompactionServiceJobStatus::kFailure;
}
}
int GetCompactionNum() { return compaction_num_.load(); }
private:
InstrumentedMutex mutex_;
std::atomic_int compaction_num_{0};
std::map<int, std::string> jobs_;
const std::string db_path_;
std::shared_ptr<FileSystem> fs_;
Options options_;
};
class CompactionServiceTest : public DBTestBase {
public:
explicit CompactionServiceTest()
: DBTestBase("compaction_service_test", true) {}
protected:
void GenerateTestData() {
// Generate 20 files @ L2
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
int key_id = i * 10 + j;
ASSERT_OK(Put(Key(key_id), "value" + ToString(key_id)));
}
ASSERT_OK(Flush());
}
MoveFilesToLevel(2);
// Generate 10 files @ L1 overlap with all 20 files @ L2
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
int key_id = <KEY>;
ASSERT_OK(Put(Key(key_id), "value_new" + ToString(key_id)));
}
ASSERT_OK(Flush());
}
MoveFilesToLevel(1);
ASSERT_EQ(FilesPerLevel(), "0,10,20");
}
void VerifyTestData() {
for (int i = 0; i < 200; i++) {
auto result = Get(Key(i));
if (i % 2) {
ASSERT_EQ(result, "value" + ToString(i));
} else {
ASSERT_EQ(result, "value_new" + ToString(i));
}
}
}
};
TEST_F(CompactionServiceTest, BasicCompactions) {
Options options = CurrentOptions();
options.env = env_;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
DestroyAndReopen(options);
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
int key_id = i * 10 + j;
ASSERT_OK(Put(Key(key_id), "value" + ToString(key_id)));
}
ASSERT_OK(Flush());
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
int key_id = i * 20 + j * 2;
ASSERT_OK(Put(Key(key_id), "value_new" + ToString(key_id)));
}
ASSERT_OK(Flush());
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
// verify result
for (int i = 0; i < 200; i++) {
auto result = Get(Key(i));
if (i % 2) {
ASSERT_EQ(result, "value" + ToString(i));
} else {
ASSERT_EQ(result, "value_new" + ToString(i));
}
}
auto my_cs =
dynamic_cast<MyTestCompactionService*>(options.compaction_service.get());
ASSERT_GE(my_cs->GetCompactionNum(), 1);
// Test failed compaction
SyncPoint::GetInstance()->SetCallBack(
"DBImplSecondary::CompactWithoutInstallation::End", [&](void* status) {
// override job status
Status* s = static_cast<Status*>(status);
*s = Status::Aborted("MyTestCompactionService failed to compact!");
});
SyncPoint::GetInstance()->EnableProcessing();
Status s;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
int key_id = <KEY>
s = Put(Key(key_id), "value_new" + ToString(key_id));
if (s.IsAborted()) {
break;
}
}
if (s.IsAborted()) {
break;
}
s = Flush();
if (s.IsAborted()) {
break;
}
s = dbfull()->TEST_WaitForCompact();
if (s.IsAborted()) {
break;
}
}
ASSERT_TRUE(s.IsAborted());
}
TEST_F(CompactionServiceTest, ManualCompaction) {
Options options = CurrentOptions();
options.env = env_;
options.disable_auto_compactions = true;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
DestroyAndReopen(options);
GenerateTestData();
auto my_cs =
dynamic_cast<MyTestCompactionService*>(options.compaction_service.get());
std::string start_str = Key(15);
std::string end_str = Key(45);
Slice start(start_str);
Slice end(end_str);
uint64_t comp_num = my_cs->GetCompactionNum();
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &end));
ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
VerifyTestData();
start_str = Key(120);
start = start_str;
comp_num = my_cs->GetCompactionNum();
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, nullptr));
ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
VerifyTestData();
end_str = Key(92);
end = end_str;
comp_num = my_cs->GetCompactionNum();
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, &end));
ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
VerifyTestData();
comp_num = my_cs->GetCompactionNum();
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
VerifyTestData();
}
TEST_F(CompactionServiceTest, FailedToStart) {
Options options = CurrentOptions();
options.env = env_;
options.disable_auto_compactions = true;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
DestroyAndReopen(options);
GenerateTestData();
SyncPoint::GetInstance()->SetCallBack(
"MyTestCompactionService::Start::End", [&](void* status) {
// override job status
auto s = static_cast<CompactionServiceJobStatus*>(status);
*s = CompactionServiceJobStatus::kFailure;
});
SyncPoint::GetInstance()->EnableProcessing();
std::string start_str = Key(15);
std::string end_str = Key(45);
Slice start(start_str);
Slice end(end_str);
Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
ASSERT_TRUE(s.IsIncomplete());
}
TEST_F(CompactionServiceTest, InvalidResult) {
Options options = CurrentOptions();
options.env = env_;
options.disable_auto_compactions = true;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
DestroyAndReopen(options);
GenerateTestData();
SyncPoint::GetInstance()->SetCallBack(
"MyTestCompactionService::WaitForComplete::End", [&](void* result) {
// override job status
auto result_str = static_cast<std::string*>(result);
*result_str = "Invalid Str";
});
SyncPoint::GetInstance()->EnableProcessing();
std::string start_str = Key(15);
std::string end_str = Key(45);
Slice start(start_str);
Slice end(end_str);
Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
ASSERT_FALSE(s.ok());
}
// TODO: support sub-compaction
TEST_F(CompactionServiceTest, DISABLED_SubCompaction) {
Options options = CurrentOptions();
options.env = env_;
options.max_subcompactions = 10;
options.target_file_size_base = 1 << 10; // 1KB
options.disable_auto_compactions = true;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
DestroyAndReopen(options);
GenerateTestData();
auto cro = CompactRangeOptions();
cro.max_subcompactions = 10;
db_->CompactRange(cro, nullptr, nullptr);
}
class PartialDeleteCompactionFilter : public CompactionFilter {
public:
CompactionFilter::Decision FilterV2(
int /*level*/, const Slice& key, ValueType /*value_type*/,
const Slice& /*existing_value*/, std::string* /*new_value*/,
std::string* /*skip_until*/) const override {
int i = std::stoi(key.ToString().substr(3));
if (i > 5 && i <= 105) {
return CompactionFilter::Decision::kRemove;
}
return CompactionFilter::Decision::kKeep;
}
const char* Name() const override { return "PartialDeleteCompactionFilter"; }
};
TEST_F(CompactionServiceTest, CompactionFilter) {
Options options = CurrentOptions();
options.env = env_;
auto delete_comp_filter = PartialDeleteCompactionFilter();
options.compaction_filter = &delete_comp_filter;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
DestroyAndReopen(options);
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
int key_id = i * 10 + j;
ASSERT_OK(Put(Key(key_id), "value" + ToString(key_id)));
}
ASSERT_OK(Flush());
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
int key_id = <KEY>;
ASSERT_OK(Put(Key(key_id), "value_new" + ToString(key_id)));
}
ASSERT_OK(Flush());
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
// verify result
for (int i = 0; i < 200; i++) {
auto result = Get(Key(i));
if (i > 5 && i <= 105) {
ASSERT_EQ(result, "NOT_FOUND");
} else if (i % 2) {
ASSERT_EQ(result, "value" + ToString(i));
} else {
ASSERT_EQ(result, "value_new" + ToString(i));
}
}
auto my_cs =
dynamic_cast<MyTestCompactionService*>(options.compaction_service.get());
ASSERT_GE(my_cs->GetCompactionNum(), 1);
}
TEST_F(CompactionServiceTest, Snapshot) {
Options options = CurrentOptions();
options.env = env_;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
DestroyAndReopen(options);
ASSERT_OK(Put(Key(1), "value1"));
ASSERT_OK(Put(Key(2), "value1"));
const Snapshot* s1 = db_->GetSnapshot();
ASSERT_OK(Flush());
ASSERT_OK(Put(Key(1), "value2"));
ASSERT_OK(Put(Key(3), "value2"));
ASSERT_OK(Flush());
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
auto my_cs =
dynamic_cast<MyTestCompactionService*>(options.compaction_service.get());
ASSERT_GE(my_cs->GetCompactionNum(), 1);
ASSERT_EQ("value1", Get(Key(1), s1));
ASSERT_EQ("value2", Get(Key(1)));
db_->ReleaseSnapshot(s1);
}
TEST_F(CompactionServiceTest, ConcurrentCompaction) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 100;
options.env = env_;
options.compaction_service = std::make_shared<MyTestCompactionService>(
dbname_, env_->GetFileSystem(), options);
options.max_background_jobs = 20;
DestroyAndReopen(options);
GenerateTestData();
ColumnFamilyMetaData meta;
db_->GetColumnFamilyMetaData(&meta);
std::vector<std::thread> threads;
for (const auto& file : meta.levels[1].files) {
threads.push_back(std::thread([&]() {
std::string fname = file.db_path + "/" + file.name;
ASSERT_OK(db_->CompactFiles(CompactionOptions(), {fname}, 2));
}));
}
for (auto& thread : threads) {
thread.join();
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
// verify result
for (int i = 0; i < 200; i++) {
auto result = Get(Key(i));
if (i % 2) {
ASSERT_EQ(result, "value" + ToString(i));
} else {
ASSERT_EQ(result, "value_new" + ToString(i));
}
}
auto my_cs =
dynamic_cast<MyTestCompactionService*>(options.compaction_service.get());
ASSERT_EQ(my_cs->GetCompactionNum(), 10);
ASSERT_EQ(FilesPerLevel(), "0,0,10");
}
} // namespace ROCKSDB_NAMESPACE
#ifdef ROCKSDB_UNITTESTS_WITH_CUSTOM_OBJECTS_FROM_STATIC_LIBS
extern "C" {
void RegisterCustomObjects(int argc, char** argv);
}
#else
void RegisterCustomObjects(int /*argc*/, char** /*argv*/) {}
#endif // !ROCKSDB_UNITTESTS_WITH_CUSTOM_OBJECTS_FROM_STATIC_LIBS
int main(int argc, char** argv) {
ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
::testing::InitGoogleTest(&argc, argv);
RegisterCustomObjects(argc, argv);
return RUN_ALL_TESTS();
}
#else
#include <stdio.h>
int main(int /*argc*/, char** /*argv*/) {
fprintf(stderr,
"SKIPPED as CompactionService is not supported in ROCKSDB_LITE\n");
return 0;
}
#endif // ROCKSDB_LITE
|
rsdoherty/azure-sdk-for-python
|
sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_query_operations.py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import datetime
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class QueryOperations(object):
"""QueryOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~monitor_query_client.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
workspace_id, # type: str
query, # type: str
timespan=None, # type: Optional[datetime.timedelta]
**kwargs # type: Any
):
# type: (...) -> "_models.QueryResults"
"""Execute an Analytics query.
Executes an Analytics query for data.
:param workspace_id: ID of the workspace. This is Workspace ID from the Properties blade in the
Azure portal.
:type workspace_id: str
:param query: The Analytics query. Learn more about the `Analytics query syntax
<https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
:type query: str
:param timespan: Optional. The timespan over which to query data. This is an ISO8601 time
period value. This timespan is applied in addition to any that are specified in the query
expression.
:type timespan: ~datetime.timedelta
:keyword callable cls: A custom type or function that will be passed the direct response
:return: QueryResults, or the result of cls(response)
:rtype: ~monitor_query_client.models.QueryResults
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResults"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'workspaceId': self._serialize.url("workspace_id", workspace_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['query'] = self._serialize.query("query", query, 'str')
if timespan is not None:
query_parameters['timespan'] = self._serialize.query("timespan", timespan, 'duration')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('QueryResults', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/workspaces/{workspaceId}/query'} # type: ignore
def execute(
self,
workspace_id, # type: str
body, # type: "_models.QueryBody"
prefer=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> "_models.QueryResults"
"""Execute an Analytics query.
Executes an Analytics query for data. `Here <https://dev.loganalytics.io/documentation/Using-
the-API>`_ is an example for using POST with an Analytics query.
:param workspace_id: ID of the workspace. This is Workspace ID from the Properties blade in the
Azure portal.
:type workspace_id: str
:param body: The Analytics query. Learn more about the `Analytics query syntax
<https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
:type body: ~monitor_query_client.models.QueryBody
:param prefer: Optional. The prefer header to set server timeout, query statistics and
visualization information.
:type prefer: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: QueryResults, or the result of cls(response)
:rtype: ~monitor_query_client.models.QueryResults
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResults"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.execute.metadata['url'] # type: ignore
path_format_arguments = {
'workspaceId': self._serialize.url("workspace_id", workspace_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
if prefer is not None:
header_parameters['Prefer'] = self._serialize.header("prefer", prefer, 'str')
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'QueryBody')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('QueryResults', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
execute.metadata = {'url': '/workspaces/{workspaceId}/query'} # type: ignore
def batch(
self,
body, # type: "_models.BatchRequest"
**kwargs # type: Any
):
# type: (...) -> "_models.BatchResponse"
"""Execute a batch of Analytics queries.
Executes a batch of Analytics queries for data. `Here
<https://dev.loganalytics.io/documentation/Using-the-API>`_ is an example for using POST with
an Analytics query.
:param body: The batch request body.
:type body: ~monitor_query_client.models.BatchRequest
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BatchResponse, or the result of cls(response)
:rtype: ~monitor_query_client.models.BatchResponse
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BatchResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.batch.metadata['url'] # type: ignore
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'BatchRequest')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('BatchResponse', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
batch.metadata = {'url': '/$batch'} # type: ignore
|
kaist-plrg/jest
|
src/main/scala/kr/ac/kaist/jest/model/algorithm/AsyncArrowFunction1Contains0.scala
|
<filename>src/main/scala/kr/ac/kaist/jest/model/algorithm/AsyncArrowFunction1Contains0.scala
package kr.ac.kaist.jest.model
import kr.ac.kaist.jest.ir._
import kr.ac.kaist.jest.ir.Parser._
object AsyncArrowFunction1Contains0 extends Algorithm {
val name: String = "AsyncArrowFunction1Contains0"
val length: Int = 0
val lang: Boolean = true
val func: Func = FixUIdWalker(parseFunc(""""AsyncArrowFunction1Contains0" (this, CoverCallExpressionAndAsyncArrowHead, AsyncConciseBody, symbol) => {
if (! (|| (|| (|| (|| (is-instance-of symbol NewTarget) (is-instance-of symbol SuperProperty)) (is-instance-of symbol SuperCall)) (= symbol "super")) (= symbol "this"))) return false else {}
access __x0__ = (CoverCallExpressionAndAsyncArrowHead "CoveredAsyncArrowHead")
let head = __x0__
access __x1__ = (head "Contains")
app __x2__ = (__x1__ symbol)
if (= __x2__ true) return true else {}
access __x3__ = (AsyncConciseBody "Contains")
app __x4__ = (__x3__ symbol)
return __x4__
}"""), this)
}
|
abakus-ntnu/abacash-api
|
src/models/user.model.js
|
<reponame>abakus-ntnu/abacash-api
import Bluebird from 'bluebird';
import bcrypt from 'bcrypt';
import _ from 'lodash';
import { createToken } from '../auth';
import { sendInviteEmail, sendResetEmail } from '../components/mail';
Bluebird.promisifyAll(bcrypt);
export default function(sequelize, DataTypes) {
const User = sequelize.define('user', {
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
validate: {
isEmail: true
}
},
isAdmin: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
name: DataTypes.STRING,
hash: DataTypes.STRING
});
User.register = function(body, password) {
return bcrypt
.genSaltAsync()
.then(salt => bcrypt.hashAsync(password, salt))
.then(hash =>
User.create({
...body,
hash
})
);
};
User.invite = function(body) {
let userInstance;
return User.create(body)
.then(user => {
userInstance = user;
return user.sendInvite();
})
.then(() => userInstance);
};
User.prototype.authenticate = function(password) {
return bcrypt.compareAsync(password, this.hash);
};
User.prototype.toJSON = function() {
const values = this.get({ plain: true });
return _.omit(values, 'hash');
};
User.prototype.sendInvite = function() {
const token = createToken({ ...this.toJSON(), invite: true }, '5h');
return sendInviteEmail(this, token);
};
User.prototype.passwordReset = function() {
const token = createToken({ ...this.toJSON(), reset: true }, '5h');
return sendResetEmail(this, token);
};
User.prototype.updatePassword = function(password) {
return bcrypt
.genSaltAsync()
.then(salt => bcrypt.hashAsync(password, salt))
.then(hash => {
this.hash = hash;
return this.save();
});
};
return User;
}
|
jmgilman/fapi
|
app/tests/core/storage/test_redis.py
|
<filename>app/tests/core/storage/test_redis.py
from unittest import mock
from app.core import settings
from app.core.storage.redis import RedisConfig, RedisStorage
import redis
@mock.patch("bdantic.models.BeancountFile.parse")
@mock.patch("bdantic.models.BeancountFile.decompress")
@mock.patch("beancount.loader.load_string")
@mock.patch("redis.StrictRedis.pubsub")
@mock.patch("redis.StrictRedis.get")
def test_load(get, pubsub, loader, decompress, parse):
contents = ([], [], {})
ps = mock.Mock(redis.client.PubSub)
pubsub.return_value = ps
get.return_value = b"test"
loader.return_value = contents
parse.return_value = "parsed"
stgs = settings.Settings()
stgs.redis = RedisConfig()
storage = RedisStorage(stgs)
result = storage.load()
assert result == "parsed"
ps.subscribe.assert_called_once_with(stgs.redis.channel)
get.assert_called_once_with(stgs.redis.key)
loader.assert_called_once_with("test")
parse.assert_called_once_with(contents)
# Cached
get.return_value = "bytes"
stgs.redis.cached = True
storage = RedisStorage(stgs)
result = storage.load()
decompress.assert_called_once_with("bytes")
|
viticm/web-pap
|
server/Server/Skills/SpecialObjLogics.h
|
///////////////////////////////////////////////////////////////////////////////
// 文件名:SpecialObjLogics.h
// 程序员:高骐
// 功能说明:所有特殊对象逻辑的头文件总合
//
// 修改记录:
//
//
//
///////////////////////////////////////////////////////////////////////////////
#ifndef SPECIALOBJLOGICS_H
#define SPECIALOBJLOGICS_H
#include "SpecialObjLogic.h"
#include "TrapLogic.h"
namespace Combat_Module
{
namespace Special_Obj_Module
{
};
};
#endif //SPECIALOBJLOGICS_H
|
anuragxel/generic-document-library
|
src/detail/libre_api/libre_chart_func.cpp
|
//! \file
//! \brief Libre Office Cell Related Internal Functions
#ifndef _LIBRE_CHART_FUNC_CPP
#define _LIBRE_CHART_FUNC_CPP
// Copyright <NAME> 2015.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/throw_exception.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/awt/Size.hpp>
#include <com/sun/star/beans/Property.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <com/sun/star/chart/XDiagram.hpp>
#include <com/sun/star/chart/XChartDocument.hpp>
#include <com/sun/star/chart/XAxisSupplier.hpp>
#include <com/sun/star/chart/XAxis.hpp>
#include <com/sun/star/chart/XAxisXSupplier.hpp>
#include <com/sun/star/chart/XAxisYSupplier.hpp>
#include <com/sun/star/chart/XAxisZSupplier.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/document/XEmbeddedObjectSupplier.hpp>
#include <com/sun/star/drawing/XDrawPages.hpp>
#include <com/sun/star/drawing/XDrawPage.hpp>
#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#include <com/sun/star/drawing/XShapes.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XCellRangeAddressable.hpp>
#include <com/sun/star/table/XCell.hpp>
#include <com/sun/star/table/CellRangeAddress.hpp>
#include <com/sun/star/table/XCellRange.hpp>
#include <com/sun/star/table/XTableChart.hpp>
#include <com/sun/star/table/XTableCharts.hpp>
#include <com/sun/star/table/XTableChartsSupplier.hpp>
#include <boost/document/detail/chart_type.hpp>
#include <boost/document/detail/chart_axis.hpp>
#include <boost/document/detail/document_exception.hpp>
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sheet;
using namespace com::sun::star::table;
using namespace com::sun::star::chart;
using namespace com::sun::star::awt;
using namespace com::sun::star::sheet;
using namespace com::sun::star::container;
using namespace com::sun::star::document;
using namespace com::sun::star::drawing;
using namespace rtl;
using namespace cppu;
using ::rtl::OString;
using ::rtl::OUString;
using ::rtl::OUStringToOString;
namespace boost { namespace doc { namespace libre_chart_func {
//! \fn Helper function to throw an unwrapped
//! exception
//!
void throw_document_exception(Exception& e) {
OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
boost::throw_exception(document_exception(o.pData->buffer));
}
/*template<typename U>
void __debug_find_props(Reference < U > xSomething) {
Reference < XPropertySet > xChartProps(xSomething, UNO_QUERY);
Reference < XPropertySetInfo > xPropInfo(xChartProps->getPropertySetInfo());
Sequence < Property > props = xPropInfo->getProperties();
for(int i = 0; i < props.getLength(); i++) {
std::cout << props[i].Name << std::endl;
}
}*/
template<typename U, typename T>
void set_chart_property(Reference < U > xSomething, const OUString& prop, const T& val) {
try {
Reference < XPropertySet > xChartProps(xSomething, UNO_QUERY);
Any propVal;
propVal <<= val;
xChartProps->setPropertyValue(prop, propVal);
}
catch( Exception &e ){
throw_document_exception(e);
}
}
template<typename U>
Any get_chart_property(Reference < U > xSomething, const OUString& prop) {
try {
Reference < XPropertySet > xChartProps(xSomething, UNO_QUERY);
return xChartProps->getPropertyValue(prop);
}
catch( Exception &e ){
throw_document_exception(e);
}
}
void set_title(Reference<XChartDocument> xChart, const std::string& title) {
set_chart_property(xChart, OUString::createFromAscii("HasMainTitle"), (sal_Bool)true);
set_chart_property(xChart->getTitle(), OUString::createFromAscii("String"), OUString::createFromAscii(title.c_str()));
}
void set_legend(Reference<XChartDocument> xChart, bool set) {
set_chart_property(xChart, OUString::createFromAscii("HasLegend"), (sal_Bool)set);
}
Reference<XDiagram> helper_get_XDiagram(Reference<XChartDocument> xChart, std::string service_name) {
Reference<XMultiServiceFactory> xMSF(xChart, UNO_QUERY);
Reference<XDiagram> xDiag(xMSF->createInstance(OUString::createFromAscii(service_name.c_str())), UNO_QUERY);
return xDiag;
}
// MS Office : https://msdn.microsoft.com/en-us/library/office/ff838409.aspx
// OpenOffice : https://www.openoffice.org/api/docs/common/ref/com/sun/star/chart/module-ix.html
void set_type(Reference<XChartDocument> xChart, boost::chart_type::type t, bool enable_3d) {
Reference<XDiagram> xDiag = NULL;
bool v,o;
switch(t) {
case boost::chart_type::AREA :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.AreaDiagram");
break;
case boost::chart_type::BAR :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.BarDiagram");
break;
case boost::chart_type::BUBBLE :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.BubbleDiagram");
break;
case boost::chart_type::DONUT :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.DonutDiagram");
break;
case boost::chart_type::LINE :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.LineDiagram");
break;
case boost::chart_type::RADAR :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.NetDiagram");
break;
case boost::chart_type::PIE :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.PieDiagram");
break;
case boost::chart_type::STOCK :
case boost::chart_type::STOCKO :
case boost::chart_type::STOCKV :
case boost::chart_type::STOCKVO :
if(t == boost::chart_type::STOCK) { v = false; o = false; }
else if(t == boost::chart_type::STOCKO) { v = false; o = true; }
else if(t == boost::chart_type::STOCKV) { v = true; o = false;}
else { v = true; o = true; }
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.StockDiagram");
set_chart_property(xDiag, OUString::createFromAscii("Volume"), (sal_Bool)v);
set_chart_property(xDiag, OUString::createFromAscii("UpDown"), (sal_Bool)o);
break;
case boost::chart_type::SCATTER :
xDiag = helper_get_XDiagram(xChart, "com.sun.star.chart.XYDiagram");
break;
}
set_chart_property(xDiag, OUString::createFromAscii("Dim3D"), (sal_Bool)enable_3d);
xChart->setDiagram(xDiag);
}
Reference < XChartDocument >
add_chart(Reference<XSpreadsheet> xSheet, const std::string& name, const std::string& cell_range,
int left, int top, int width, int height) {
try {
Rectangle oRect(left, top, width, height);
Reference<XCellRange> oRange(xSheet, UNO_QUERY);
Reference<XCellRange> xRange = oRange->getCellRangeByName(OUString::createFromAscii(cell_range.c_str()));
Reference<XCellRangeAddressable> oRangeAddr(xRange, UNO_QUERY);
CellRangeAddress xAddr = oRangeAddr->getRangeAddress();
Sequence < CellRangeAddress > oAddr(1);
oAddr[0] = xAddr;
// Adding the chart to the destination
Reference<XTableChartsSupplier> oSupp(xSheet, UNO_QUERY);
Reference<XTableCharts> oCharts = oSupp->getCharts();
oCharts->addNewByName(OUString::createFromAscii(name.c_str()), oRect, oAddr, true, true);
// Get the XChartDocument object which is the Chart interface
Reference<XNameAccess> xNamed(oCharts, UNO_QUERY);
Any oChart = xNamed->getByName(OUString::createFromAscii(name.c_str()));
Reference<XEmbeddedObjectSupplier> oEOS(oChart, UNO_QUERY);
Reference<XInterface> oInt = oEOS->getEmbeddedObject();
Reference<XChartDocument> xChart(oInt, UNO_QUERY);
set_title(xChart, name);
set_legend(xChart, true);
/*std::cout << "Chart Props\n\n\n" << std::endl;
__debug_find_props(xChart);
std::cout << "Diagram Props\n\n\n" << std::endl;
__debug_find_props(xChart->getDiagram());
std::cout << "Legend Props\n\n\n" << std::endl;
__debug_find_props(xChart->getLegend());*/
return xChart;
}
catch( Exception &e ){
throw_document_exception(e);
}
}
Reference < XChartDocument >
get_chart(Reference<XSpreadsheet> xSheet, const std::string& name) {
try{
Reference<XTableChartsSupplier> oSupp(xSheet, UNO_QUERY);
Reference<XTableCharts> oCharts = oSupp->getCharts();
Reference<XNameAccess> xNamed(oCharts, UNO_QUERY);
Any oChart = xNamed->getByName(OUString::createFromAscii(name.c_str()));
Reference<XEmbeddedObjectSupplier> oEOS(oChart, UNO_QUERY);
Reference<XInterface> oInt = oEOS->getEmbeddedObject();
Reference<XChartDocument> xChart(oInt, UNO_QUERY);
return xChart
}
catch( Exception& e){
throw_document_exception(e);
}
}
void set_rectangle(Reference < XChartDocument > xChart, Reference < XSpreadsheet > xSheet, int left, int top, int width, int height) {
try {
// Deprecated :/
Reference< XDrawPageSupplier > xDPS(xSheet, UNO_QUERY);
Reference< XDrawPage > xDrawPage(xDPS->getDrawPage(), UNO_QUERY);
Reference< XShapes > xShapes(xDrawPage, UNO_QUERY);
Reference< XIndexAccess > xIA(xShapes, UNO_QUERY);
int count = xIA->getCount();
if(count == 1) {
Reference< XShape > xShape(xIA->getByIndex(0), UNO_QUERY);
Point pos(left, top);
// specific to libreoffice, openoffice uses Point
Size siz(width, height);
xShape->setPosition(pos);
xShape->setSize(siz);
}
else {
// Multiple shapes, then?
// How to identify?
for(int i = 0; i < count; i++){
}
}
}
catch( Exception &e){
throw_document_exception(e);
}
}
void set_cell_range(Reference < XChartDocument > xChart, Reference < XSpreadsheet > xSheet, const std::string& name, const std::string& cell_range){
try {
Reference<XCellRange> oRange(xSheet, UNO_QUERY);
Reference<XCellRange> xRange = oRange->getCellRangeByName(OUString::createFromAscii(cell_range.c_str()));
Reference<XCellRangeAddressable> oRangeAddr(xRange, UNO_QUERY);
CellRangeAddress xAddr = oRangeAddr->getRangeAddress();
Sequence < CellRangeAddress > oAddr(1);
oAddr[0] = xAddr;
Reference<XTableChartsSupplier> oSupp(xSheet, UNO_QUERY);
Reference<XTableCharts> oCharts = oSupp->getCharts();
Reference<XNameAccess> xNamed(oCharts, UNO_QUERY);
Any oChart = xNamed->getByName(OUString::createFromAscii(name.c_str()));
Reference<XTableChart> xTableChart(oChart, UNO_QUERY);
xTableChart->setRanges(oAddr);
}
catch( Exception &e){
throw_document_exception(e);
}
}
void delete_chart(Reference<XSpreadsheet> xSheet, const std::string& name) {
try {
Reference<XTableChartsSupplier> oSupp(xSheet, UNO_QUERY);
Reference<XTableCharts> oCharts = oSupp->getCharts();
oCharts->removeByName(OUString::createFromAscii(name.c_str()));
}
catch( Exception &e ){
throw_document_exception(e);
}
}
void set_axis_title(Reference<XChartDocument> xChart, boost::chart_axis::type t, const std::string& title) {
try {
Any bool_true;
bool_true <<= (sal_Bool)true;
Reference<XAxis> xAxis = NULL;
if(t == boost::chart_axis::X) {
Reference<XAxisXSupplier> xChecker(xChart->getDiagram(), UNO_QUERY);
if(get_chart_property(xChecker, OUString::createFromAscii("HasXAxis")) == bool_true) {
Reference<XAxis> xAxis_tmp(xChecker->getXAxis(), UNO_QUERY);
xAxis = xAxis_tmp;
}
}
else if (t == boost::chart_axis::Y) {
Reference<XAxisYSupplier> xChecker(xChart->getDiagram(), UNO_QUERY);
if(get_chart_property(xChecker, OUString::createFromAscii("HasYAxis")) == bool_true) {
Reference<XAxis> xAxis_tmp(xChecker->getYAxis(), UNO_QUERY);
xAxis = xAxis_tmp;
}
}
else if(t == boost::chart_axis::Z) {
Reference<XAxisZSupplier> xChecker(xChart->getDiagram(), UNO_QUERY);
if(get_chart_property(xChecker, OUString::createFromAscii("HasZAxis")) == bool_true) {
Reference<XAxis> xAxis_tmp(xChecker->getZAxis(), UNO_QUERY);
xAxis = xAxis_tmp;
}
}
// If the axis isn't present at all in the diagram.
if(xAxis == NULL) {
boost::throw_exception(document_exception(
"Error: Chart type doesn't support axis."));
}
//Reference<XAxisSupplier> xAxisSupplier(xChart, UNO_QUERY);
set_chart_property(xAxis->getAxisTitle(), OUString::createFromAscii("String"), OUString::createFromAscii(title.c_str()));
}
catch( Exception &e ){
throw_document_exception(e);
}
}
void set_axis_orientation(Reference<XChartDocument> xChart, boost::chart_axis::type t, bool set) {
try{
Any bool_true;
bool_true <<= (sal_Bool)true;
Reference<XPropertySet> xChartAxis = NULL;
if(t == boost::chart_axis::X) {
Reference<XAxisXSupplier> xChecker(xChart->getDiagram(), UNO_QUERY);
if(get_chart_property(xChecker, OUString::createFromAscii("HasXAxis")) == bool_true) {
xChartAxis = xChecker->getXAxis();
}
}
else if (t == boost::chart_axis::Y) {
Reference<XAxisYSupplier> xChecker(xChart->getDiagram(), UNO_QUERY);
if(get_chart_property(xChecker, OUString::createFromAscii("HasYAxis")) == bool_true) {
xChartAxis = xChecker->getYAxis();
}
}
else if(t == boost::chart_axis::Z) {
Reference<XAxisZSupplier> xChecker(xChart->getDiagram(), UNO_QUERY);
if(get_chart_property(xChecker, OUString::createFromAscii("HasZAxis")) == bool_true) {
xChartAxis = xChecker->getZAxis();
}
}
// If the axis isn't present at all in the diagram.
if(xChartAxis == NULL) {
boost::throw_exception(document_exception(
"Error: Chart type doesn't support axis."));
}
set_chart_property(xChartAxis, OUString::createFromAscii("ReverseDirection"), (sal_Bool)set);
}
catch( Exception &e ) {
throw_document_exception(e);
}
}
}}}
#endif
|
supriyasingh01/github_basics
|
Internetworking Distributed Project/Kernal/linux-3.6.3/arch/m68k/include/asm/m54xxacr.h
|
/*
* Bit definitions for the MCF54xx ACR and CACR registers.
*/
#ifndef m54xxacr_h
#define m54xxacr_h
/*
* Define the Cache register flags.
*/
#define CACR_DEC 0x80000000 /* Enable data cache */
#define CACR_DWP 0x40000000 /* Data write protection */
#define CACR_DESB 0x20000000 /* Enable data store buffer */
#define CACR_DDPI 0x10000000 /* Disable invalidation by CPUSHL */
#define CACR_DHCLK 0x08000000 /* Half data cache lock mode */
#define CACR_DDCM_WT 0x00000000 /* Write through cache*/
#define CACR_DDCM_CP 0x02000000 /* Copyback cache */
#define CACR_DDCM_P 0x04000000 /* No cache, precise */
#define CACR_DDCM_IMP 0x06000000 /* No cache, imprecise */
#define CACR_DCINVA 0x01000000 /* Invalidate data cache */
#define CACR_BEC 0x00080000 /* Enable branch cache */
#define CACR_BCINVA 0x00040000 /* Invalidate branch cache */
#define CACR_IEC 0x00008000 /* Enable instruction cache */
#define CACR_DNFB 0x00002000 /* Inhibited fill buffer */
#define CACR_IDPI 0x00001000 /* Disable CPUSHL */
#define CACR_IHLCK 0x00000800 /* Intruction cache half lock */
#define CACR_IDCM 0x00000400 /* Intruction cache inhibit */
#define CACR_ICINVA 0x00000100 /* Invalidate instr cache */
#define CACR_EUSP 0x00000020 /* Enable separate user a7 */
#define ACR_BASE_POS 24 /* Address Base */
#define ACR_MASK_POS 16 /* Address Mask */
#define ACR_ENABLE 0x00008000 /* Enable address */
#define ACR_USER 0x00000000 /* User mode access only */
#define ACR_SUPER 0x00002000 /* Supervisor mode only */
#define ACR_ANY 0x00004000 /* Match any access mode */
#define ACR_CM_WT 0x00000000 /* Write through mode */
#define ACR_CM_CP 0x00000020 /* Copyback mode */
#define ACR_CM_OFF_PRE 0x00000040 /* No cache, precise */
#define ACR_CM_OFF_IMP 0x00000060 /* No cache, imprecise */
#define ACR_CM 0x00000060 /* Cache mode mask */
#define ACR_SP 0x00000008 /* Supervisor protect */
#define ACR_WPROTECT 0x00000004 /* Write protect */
#define ACR_BA(x) ((x) & 0xff000000)
#define ACR_ADMSK(x) ((((x) - 1) & 0xff000000) >> 8)
#if defined(CONFIG_M5407)
#define ICACHE_SIZE 0x4000 /* instruction - 16k */
#define DCACHE_SIZE 0x2000 /* data - 8k */
#elif defined(CONFIG_M54xx)
#define ICACHE_SIZE 0x8000 /* instruction - 32k */
#define DCACHE_SIZE 0x8000 /* data - 32k */
#elif defined(CONFIG_M5441x)
#define ICACHE_SIZE 0x2000 /* instruction - 8k */
#define DCACHE_SIZE 0x2000 /* data - 8k */
#endif
#define CACHE_LINE_SIZE 0x0010 /* 16 bytes */
#define CACHE_WAYS 4 /* 4 ways */
#define ICACHE_SET_MASK ((ICACHE_SIZE / 64 - 1) << CACHE_WAYS)
#define DCACHE_SET_MASK ((DCACHE_SIZE / 64 - 1) << CACHE_WAYS)
#define ICACHE_MAX_ADDR ICACHE_SET_MASK
#define DCACHE_MAX_ADDR DCACHE_SET_MASK
/*
* Version 4 cores have a true harvard style separate instruction
* and data cache. Enable data and instruction caches, also enable write
* buffers and branch accelerator.
*/
/* attention : enabling CACR_DESB requires a "nop" to flush the store buffer */
/* use '+' instead of '|' for assembler's sake */
/* Enable data cache */
/* Enable data store buffer */
/* outside ACRs : No cache, precise */
/* Enable instruction+branch caches */
#if defined(CONFIG_M5407)
#define CACHE_MODE (CACR_DEC+CACR_DESB+CACR_DDCM_P+CACR_BEC+CACR_IEC)
#else
#define CACHE_MODE (CACR_DEC+CACR_DESB+CACR_DDCM_P+CACR_BEC+CACR_IEC+CACR_EUSP)
#endif
#define CACHE_INIT (CACR_DCINVA+CACR_BCINVA+CACR_ICINVA)
#if defined(CONFIG_MMU)
/*
* If running with the MMU enabled then we need to map the internal
* register region as non-cacheable. And then we map all our RAM as
* cacheable and supervisor access only.
*/
#define ACR0_MODE (ACR_BA(CONFIG_MBAR)+ACR_ADMSK(0x1000000)+ \
ACR_ENABLE+ACR_SUPER+ACR_CM_OFF_PRE+ACR_SP)
#define ACR1_MODE (ACR_BA(CONFIG_RAMBASE)+ACR_ADMSK(CONFIG_RAMSIZE)+ \
ACR_ENABLE+ACR_SUPER+ACR_SP)
#define ACR2_MODE 0
#define ACR3_MODE (ACR_BA(CONFIG_RAMBASE)+ACR_ADMSK(CONFIG_RAMSIZE)+ \
ACR_ENABLE+ACR_SUPER+ACR_SP)
#else
/*
* For the non-MMU enabled case we map all of RAM as cacheable.
*/
#if defined(CONFIG_CACHE_COPYBACK)
#define DATA_CACHE_MODE (ACR_ENABLE+ACR_ANY+ACR_CM_CP)
#else
#define DATA_CACHE_MODE (ACR_ENABLE+ACR_ANY+ACR_CM_WT)
#endif
#define INSN_CACHE_MODE (ACR_ENABLE+ACR_ANY)
#define CACHE_INVALIDATE (CACHE_MODE+CACR_DCINVA+CACR_BCINVA+CACR_ICINVA)
#define CACHE_INVALIDATEI (CACHE_MODE+CACR_BCINVA+CACR_ICINVA)
#define CACHE_INVALIDATED (CACHE_MODE+CACR_DCINVA)
#define ACR0_MODE (0x000f0000+DATA_CACHE_MODE)
#define ACR1_MODE 0
#define ACR2_MODE (0x000f0000+INSN_CACHE_MODE)
#define ACR3_MODE 0
#if ((DATA_CACHE_MODE & ACR_CM) == ACR_CM_CP)
/* Copyback cache mode must push dirty cache lines first */
#define CACHE_PUSH
#endif
#endif /* CONFIG_MMU */
#endif /* m54xxacr_h */
|
giovannistanco/contiki-ng
|
os/net/app-layer/coap/oscore-support/sliding-window.c
|
<reponame>giovannistanco/contiki-ng
#include "sliding-window.h"
#include "assert.h"
/* Log configuration */
#include "sys/log.h"
#define LOG_MODULE "oscore"
#ifdef LOG_CONF_LEVEL_OSCORE
#define LOG_LEVEL LOG_CONF_LEVEL_OSCORE
#else
#define LOG_LEVEL LOG_LEVEL_WARN
#endif
void oscore_sliding_window_init(oscore_sliding_window_t* w)
{
w->largest_seq = OSCORE_INVALID_SEQ;
w->rollback_largest_seq = w->largest_seq;
w->sliding_window = 0;
w->rollback_sliding_window = w->sliding_window;
w->recent_seq = OSCORE_INVALID_SEQ;
}
void oscore_sliding_window_rollback(oscore_sliding_window_t* w)
{
LOG_DBG("Rolling back seq (window %"PRIu32" = %"PRIu32") (seq %"PRIu64" = %"PRIu64")\n",
w->sliding_window, w->rollback_sliding_window,
w->largest_seq, w->rollback_largest_seq);
w->sliding_window = w->rollback_sliding_window;
w->largest_seq = w->rollback_largest_seq;
}
bool oscore_sliding_window_test(const oscore_sliding_window_t* w, uint64_t seq)
{
/* Check that seq is within the sliding window */
if (w->largest_seq == OSCORE_INVALID_SEQ)
{
/* no sliding window yet */
return false;
}
if (seq > w->largest_seq)
{
/* too big */
return false;
}
if (seq + OSCORE_DEFAULT_REPLAY_WINDOW < w->largest_seq)
{
/* too small */
return false;
}
const int64_t shift = w->largest_seq - seq;
return (w->sliding_window & (1 << shift)) != 0;
}
void oscore_sliding_window_set(oscore_sliding_window_t* w, uint64_t seq)
{
if (w->largest_seq == OSCORE_INVALID_SEQ) {
/* Set the 0th bit */
w->sliding_window = (1 << 0);
w->largest_seq = seq;
}
else if (seq > w->largest_seq) {
const int64_t shift = seq - w->largest_seq;
/* Move the window along so the 0th bit is this new seq */
w->sliding_window <<= shift;
/* Set the 0th bit */
w->sliding_window |= (1 << 0);
w->largest_seq = seq;
} else {
assert(oscore_sliding_window_contains(w, seq));
const int64_t shift = w->largest_seq - seq;
assert(shift >= 0);
assert(shift < OSCORE_DEFAULT_REPLAY_WINDOW);
w->sliding_window |= (1 << shift);
}
}
bool oscore_sliding_window_contains(const oscore_sliding_window_t* w, uint64_t seq)
{
/* Seq needs to be in the range (largest_seq - OSCORE_DEFAULT_REPLAY_WINDOW : largest_seq] */
return w->largest_seq != OSCORE_INVALID_SEQ &&
seq <= w->largest_seq &&
/* Rearranged to prevent underflow */
seq + OSCORE_DEFAULT_REPLAY_WINDOW > w->largest_seq;
}
bool oscore_sliding_window_validate(oscore_sliding_window_t* w, uint64_t incoming_seq)
{
LOG_DBG("incoming SEQ %" PRIu64 "\n", incoming_seq);
/* Save the current state for potential rollback */
w->rollback_largest_seq = w->largest_seq;
w->rollback_sliding_window = w->sliding_window;
if(incoming_seq >= OSCORE_SEQ_MAX) {
LOG_WARN("Replay protection, SEQ %" PRIu64 " larger than SEQ_MAX %" PRIu64 ".\n",
incoming_seq, OSCORE_SEQ_MAX);
return false;
}
if(incoming_seq > w->largest_seq || w->largest_seq == OSCORE_INVALID_SEQ) {
oscore_sliding_window_set(w, incoming_seq);
} else if(incoming_seq == w->largest_seq) {
LOG_WARN("Replay protection, replayed SEQ incoming_seq (%" PRIu64 ") == w->largest_seq (%" PRIu64 ").\n",
incoming_seq, w->largest_seq);
return false;
} else { /* seq < recipient_seq */
if(!oscore_sliding_window_contains(w, incoming_seq)) {
LOG_WARN("Replay protection, SEQ outside of replay window "
"(incoming_seq=%" PRIu64 ", replay_window_size=%" PRIu8 ", largest_seq=%" PRIu64 ").\n",
incoming_seq, OSCORE_DEFAULT_REPLAY_WINDOW, w->largest_seq);
return false;
}
const bool set = oscore_sliding_window_test(w, incoming_seq);
if(set) {
LOG_WARN("Replay protection, replayed SEQ %"PRIu64" (sliding_window=%" PRIu32 ").\n",
incoming_seq, w->sliding_window);
return false;
} else {
oscore_sliding_window_set(w, incoming_seq);
}
}
/* Update the last seen seq */
w->recent_seq = incoming_seq;
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.