hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
1f94a1c7c8865e419d559be6a85a57bd836d241c
71
public class java{ private String name; private int age; }
10.142857
23
0.633803
756636a00f1a5f18860cc5951b9869a2455e8acc
411
package org.contentmine.norma.sections; import org.apache.log4j.Level; import org.apache.log4j.Logger; import nu.xom.Element; public class JATSTitleElement extends JATSElement { private static final Logger LOG = Logger.getLogger(JATSTitleElement.class); static { LOG.setLevel(Level.DEBUG); } static final String TAG = "title"; public JATSTitleElement(Element element) { super(element); } }
17.125
76
0.756691
7ead365ddc5372b1bb4ebb3a7dc1bb9c54230644
1,244
package kr.ync.project.admin.persistence; import java.util.List; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import kr.ync.project.admin.domain.CategoryBigVO; @Repository public class CategoryBigDAOImpl implements CategoryBigDAO{ @Inject private SqlSession session; private static String namespace = "kr.ync.project.mapper.categoryMapper"; //대분류 카테고리 생성 @Override public void createCategoryBig(CategoryBigVO vo) { session.insert(namespace + ".createCategoryBig", vo); } //대분류 카테고리 리스트 @Override public List<CategoryBigVO> BiglistAll() throws Exception { return session.selectList(namespace + ".BiglistAll"); } //대분류 카테고리 상세 @Override public CategoryBigVO readCategoryBig(int pBig) throws Exception { return session.selectOne(namespace + ".readCategoryBig", pBig); } //대분류 카테고리 수정 @Override public void updateCategoryBig(CategoryBigVO vo) throws Exception { session.update(namespace + ".updateCategoryBig", vo); } //대분류 카테고리 삭제 @Override public void deleteCategoryBig(int pBig) throws Exception { session.delete(namespace + ".deleteCategoryBig", pBig); } }
23.471698
75
0.729904
4f482407dc2c3c361783ba396382bde014280798
1,225
package javarepl.console.commands; import com.googlecode.totallylazy.Option; import javarepl.Evaluator; import javarepl.completion.CommandCompleter; import javarepl.console.ConsoleLogger; import java.lang.reflect.Type; import static com.googlecode.totallylazy.Strings.startsWith; import static javarepl.rendering.TypeRenderer.renderType; public final class ShowTypeOfExpression extends Command { private static final String COMMAND = ":type"; private final Evaluator evaluator; private final ConsoleLogger logger; public ShowTypeOfExpression(Evaluator evaluator, ConsoleLogger logger) { super(COMMAND + " <expression> - shows the type of an expression without affecting current context", startsWith(COMMAND), new CommandCompleter(COMMAND)); this.evaluator = evaluator; this.logger = logger; } public void execute(String expression) { Option<Type> expressionType = evaluator.typeOfExpression(parseStringCommand(expression).second().getOrElse("")); if (!expressionType.isEmpty()) { logger.success(renderType(expressionType.get())); } else { logger.error("Cannot determine the type of this expression."); } } }
34.027778
161
0.73551
5f1026d83a4a163ec69ae6e925583e45e8577039
8,841
package model.analyzer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.swing.SwingUtilities; import org.jfree.data.DomainOrder; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetChangeListener; import org.jfree.data.general.DatasetGroup; import org.jfree.data.xy.XYDataset; import model.measurement.Diffusivity; import model.measurement.Measurement; public class MeasurementsListDataset implements XYDataset { // ---- PUBLIC API ---- // public MeasurementsListDataset(List<Measurement> mmm, Function<Measurement, Measurement> filter) { this(mmm); this.filterRule = filter; } public MeasurementsListDataset(List<Measurement> mmm) { measurements = mmm; renewCache(); } public void addMeasurement(Measurement m) { measurements.add(m); updateCache(m, true); } public void setFilter(Function<Measurement, Measurement> newFilter) { filterRule = newFilter; renewCache(); } public void changeFetcherX(FetchersX f) { switch (f) { case FREQUENCY: changeFetcherX(XFetchers.FREQUENCY); break; case TEMPERATURE: changeFetcherX(XFetchers.TEMPERATURE); break; case TIME: changeFetcherX(XFetchers.TIME); break; default: break; } } public void changeFetcherY(FetchersY f) { switch (f) { case AMPLITUDE: changeFetcherY(YFetchers.AMPLITUDE); break; case CAPCITANCE: changeFetcherY(YFetchers.CAPACITANCE); break; case DIFFUSIVITY: changeFetcherY(YFetchers.DIFFUSIVITY); break; case FREQUENCY: changeFetcherY(YFetchers.FREQUENCY); break; case PHASE: changeFetcherY(YFetchers.PHASE); break; case TEMPERATURE: changeFetcherY(YFetchers.TEMPERATURE); break; default: break; } } public void setDifferentiationMode(int differentiationMode) { int old = this.differentiationMode; this.differentiationMode = differentiationMode; if (old != differentiationMode) { renewCache(); } } public static enum FetchersX { TEMPERATURE, FREQUENCY, TIME } public static enum FetchersY { DIFFUSIVITY, PHASE, AMPLITUDE, CAPCITANCE, TEMPERATURE, FREQUENCY } public List<Measurement> getMeasurements() { return Collections.unmodifiableList(measurements); } // -- PRIVATE PART -- // final private List<Measurement> measurements; private Function<Measurement, Measurement> filterRule; static class XFetchers { public final static Function<Measurement, Number> TEMPERATURE = m -> m.temperature.isEmpty() ? 0 : m.temperature.get(0).value; public final static Function<Measurement, Number> FREQUENCY = m -> m.frequency; public final static Function<Measurement, Number> TIME = m -> ((m.time) / 1000_000.0 - 10000.0); } static class YFetchers { public final static Function<Measurement, List<Number>> DIFFUSIVITY = ( m) -> m.diffusivity.stream().map(d -> d.diffusivity).collect(Collectors.toList()); public final static Function<Measurement, List<Number>> PHASE = ( m) -> m.diffusivity.stream().map(d -> d.phase).collect(Collectors.toList()); public final static Function<Measurement, List<Number>> AMPLITUDE = ( m) -> m.diffusivity.stream().map(d -> d.amplitude).collect(Collectors.toList()); public final static Function<Measurement, List<Number>> CAPACITANCE = ( m) -> m.diffusivity.stream().map(d -> d.capacitance).collect(Collectors.toList()); public final static Function<Measurement, List<Number>> TEMPERATURE = m -> Collections .singletonList(XFetchers.TEMPERATURE.apply(m)); public final static Function<Measurement, List<Number>> FREQUENCY = m -> Collections .singletonList(XFetchers.FREQUENCY.apply(m)); } public static class DifferentiatorsY { public final static int NONE = 0; public final static int CHANNEL = 1; public final static int FREQUENCY = 2; } Function<Measurement, Number> xValFetcher = XFetchers.TEMPERATURE; Function<Measurement, List<Number>> yValsFetcher = YFetchers.DIFFUSIVITY; private int differentiationMode = DifferentiatorsY.CHANNEL | DifferentiatorsY.FREQUENCY; Function<Measurement, List<String>> yNamesFetcher = (m) -> { List<String> yNames = new ArrayList<>(); for (Diffusivity diff : m.diffusivity) { if (diff != null) { String differentiator = ""; if (differentiationMode == DifferentiatorsY.NONE) { yNames.add(""); } else { if ((differentiationMode & DifferentiatorsY.FREQUENCY) != 0) { differentiator += (diff.frequency + "Гц"); } if ((differentiationMode & DifferentiatorsY.CHANNEL) != 0) { differentiator += "#" + diff.channelNumber; } yNames.add(differentiator); } } } if (yNames.isEmpty()) yNames.add(""); return yNames; }; private void changeFetcherX(Function<Measurement, Number> fetcher) { Function<Measurement, Number> old = xValFetcher; xValFetcher = fetcher; if (!old.equals(fetcher)) { renewCache(); } } private void changeFetcherY(Function<Measurement, List<Number>> fetcher) { Function<Measurement, List<Number>> old = yValsFetcher; yValsFetcher = fetcher; if (!old.equals(fetcher)) { renewCache(); } } private void renewCache() { clearCache(false); updateCache(measurements); notifyListeners(); } private void updateCache(List<Measurement> mms) { if (filterRule == null) { filterRule = (m) -> m; } mms.forEach(m -> updateCache(m, false)); notifyListeners(); } private void updateCache(Measurement m, boolean notify) { m = filterRule.apply(m); synchronized (cacheLock) { Number xVal = xValFetcher.apply(m); List<Number> yVals = yValsFetcher.apply(m); List<String> yNames = yNamesFetcher.apply(m); for (int i = 0; i < yVals.size(); i++) { Number val = yVals.get(i); String name = yNames.get(i); if (!seriesByNames.containsKey(name)) { addSeries(name); } seriesVals.get(seriesByNames.get(name)).add(new Pair<>(xVal, val)); } } if (notify) notifyListeners(); } private void clearCache(boolean notify) { synchronized (cacheLock) { seriesByNames.clear(); seriesByInds.clear(); seriesVals.clear(); counter = 0; } if (notify) notifyListeners(); } private void notifyListeners() { listeners.forEach(l -> SwingUtilities.invokeLater(() -> l .datasetChanged(new DatasetChangeEvent(MeasurementsListDataset.this, MeasurementsListDataset.this)))); } private static class Pair<T> { T x; T y; public Pair(T x, T y) { this.x = x; this.y = y; } } final Object cacheLock = new Object(); private int counter = 0; final Map<String, Integer> seriesByNames = new HashMap<>(10); final Map<Integer, String> seriesByInds = new HashMap<>(10); final Map<Integer, List<Pair<Number>>> seriesVals = new HashMap<>(10); private void addSeries(String name) { final int cntr = counter++; seriesByNames.computeIfAbsent(name, key -> cntr); seriesByInds.computeIfAbsent(cntr, key -> name); seriesVals.computeIfAbsent(cntr, key -> new ArrayList<>()); } // -- XYDATASET INTERFACE IMPLEMENTATION -- // @Override public int getSeriesCount() { return seriesByNames.size(); } @Override public Comparable<?> getSeriesKey(int series) { return seriesByInds.get(series); } @Override public int indexOf(Comparable seriesKey) { return seriesByNames.get(seriesKey); } List<DatasetChangeListener> listeners = new ArrayList<>(); @Override public void addChangeListener(DatasetChangeListener listener) { listeners.add(listener); } @Override public void removeChangeListener(DatasetChangeListener listener) { listeners.remove(listener); } DatasetGroup grp; @Override public DatasetGroup getGroup() { return grp; } @Override public void setGroup(DatasetGroup group) { grp = group; } @Override public DomainOrder getDomainOrder() { return DomainOrder.NONE; } @Override public int getItemCount(int series) { return seriesVals.get(series).size(); } @Override public Number getX(int series, int item) { return seriesVals.get(series).get(item).x; } @Override public double getXValue(int series, int item) { return seriesVals.get(series).get(item).x.doubleValue(); } @Override public Number getY(int series, int item) { return seriesVals.get(series).get(item).y; } @Override public double getYValue(int series, int item) { return seriesVals.get(series).get(item).y.doubleValue(); } }
26.3125
107
0.685217
a1a2df33404fd2569715b2faed3f3bff1c289f70
900
package com.leetcode_restart; public class SearchIn2DMatrixOptimized { public boolean searchMatrix(int[][] matrix, int target) { int maxRow = matrix.length; int maxCol = matrix[0].length; int left = 0; int right = maxRow * maxCol - 1; while (left <= right) { int mid = (left + right) / 2; System.out.println("mid= " + mid); int element = matrix[mid / maxCol][mid % maxCol]; System.out.println("mid= mid / maxCol " + mid / maxCol); System.out.println("mid= mid % maxCol " + mid % maxCol); System.out.println("element " + element); if (element == target) { return true; } else if (target > element) { left = mid + 1; } else { right = mid - 1; } } return false; } }
29.032258
68
0.492222
e84a584e8b0a25a2bc8a4ef8536973e7d0a47f91
1,783
package models.bean.specialities; import application.enums.STATUS; import java.io.Serializable; /** * Created by pkonwar on 7/2/2016. */ public class SpecialityBean implements Serializable { public SpecialityBean() { } public SpecialityBean(Long specialityId) { this.specialityId = specialityId; } public SpecialityBean(Long specialityId, String speciality, STATUS status, Integer journalId) { this.specialityId = specialityId; this.speciality = speciality; this.status = status; this.journalId = journalId; } private Long specialityId; private String speciality; private STATUS status; private String imageUrl; private byte[] imageBlob; //only one of imageUrl or imageBlob need to be filled. private Integer journalId; public Long getSpecialityId() { return specialityId; } public void setSpecialityId(Long specialityId) { this.specialityId = specialityId; } public String getSpeciality() { return speciality; } public void setSpeciality(String speciality) { this.speciality = speciality; } public STATUS getStatus() { return status; } public void setStatus(STATUS status) { this.status = status; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public byte[] getImageBlob() { return imageBlob; } public void setImageBlob(byte[] imageBlob) { this.imageBlob = imageBlob; } public Integer getJournalId() { return journalId; } public void setJournalId(Integer journalId) { this.journalId = journalId; } }
22.012346
99
0.650028
e2f7719c0fb861fbf44f4dbd8c35376ae0f2afd2
213
package ru.sberned.statemachine.state; /** * Created by Evgeniya Patuk ([email protected]) on 31/10/2016. */ public interface StateChanger<T, E> { void moveToState(E state, T item, StateChangedInfo info); }
23.666667
62
0.723005
f9e7900e335baed7ae5d2e02816358e0248af2b1
6,944
package proyectofinalmetodos; import java.util.ArrayList; import java.util.List; /** * PolyEquation * Clase que simula una ecuación polinomial * Fecha de creación: 29/10/16 * Fecha de última modificación: 3/11/16 * Autor original: Josué Morales * Autor de última modificación: Josué Morales * Descripción de última modificación: * "En el método derivate() se agregó que en caso de que ya no quedaran terminos con x que se agregara un término con coeficiente de cero." * Clases que lo llaman: MTH, MNR, MNM, MCMPR, MTH_Panel, MNR_Panel, MNM_Panel, MCMPR_Panel * Clases que llama: ETerm */ public class PolyEquation { //Atributos public List<ETerm> Equation; public double Degree; public double Lowest_Degree; public ArrayList degrees; /** * Constructor de la clase vacio */ public PolyEquation(){ } /** * Método interno que se llama para calcular atributos */ private void createPolyEquation(){ degrees = new ArrayList(); for(ETerm eterm: Equation){ if(!degrees.contains(eterm.Degree)){ degrees.add(eterm.Degree); } } double max = Double.NEGATIVE_INFINITY; double min = Double.POSITIVE_INFINITY; for(Object obj_degree: degrees) { if ((double) obj_degree > max) { max = (double) obj_degree; } if ((double) obj_degree < min) { min = (double) obj_degree; } } Degree = max; Lowest_Degree = min; } /** * Constructor de la clase con List<String> * @param Terms lista de términos */ public PolyEquation(List<String> Terms){ Equation = new ArrayList<ETerm>(); List<ETerm> equation_temp = new ArrayList<ETerm>(); for (String term : Terms) { ETerm term_temp = new ETerm(term); equation_temp.add(term_temp); } degrees = new ArrayList(); for(ETerm eterm: equation_temp){ if(!degrees.contains(eterm.Degree)){ degrees.add(eterm.Degree); } } double max = Double.NEGATIVE_INFINITY; double min = Double.POSITIVE_INFINITY; for(Object obj_degree: degrees){ if((double) obj_degree > max){ max = (double) obj_degree; } if((double) obj_degree < min){ min = (double) obj_degree; } ETerm eterm_degree = new ETerm(); eterm_degree.Degree = (double) obj_degree; Equation.add(eterm_degree); for(int i = 0; i<equation_temp.size(); i++){ if((double)obj_degree == equation_temp.get(i).Degree){ int posicion = 0; ETerm term_sum = null; for(int a = 0; a<Equation.size(); a++){ posicion = a; if(Equation.get(a).Degree == (double) obj_degree){ term_sum = Equation.get(a); break; } } double num1 = equation_temp.get(i).Cons * equation_temp.get(i).Sign; double num2 = term_sum.Cons * term_sum.Sign; double new_Cons = num1 + num2; double new_Sign = 0; if(new_Cons>0){ new_Sign = 1; } else { if(new_Cons<0){ new_Sign = -1; new_Cons = new_Cons * -1; } else { new_Cons = 0; } } term_sum.hasX = equation_temp.get(i).hasX; term_sum.Degree = equation_temp.get(i).Degree; term_sum.Cons = new_Cons; term_sum.Sign = new_Sign; Equation.set(posicion, term_sum); } } } Degree = max; Lowest_Degree = min; } /** * Método que obtiene el coeficiente del grado especificado. * @param degree grado * @return coeficiente en caso de que exista, si no, 0. */ public double getCoefficientAtDegree(double degree){ for (ETerm term: Equation) { if(degree == term.Degree){ return (term.Sign*term.Cons); } } return 0; } /** * Método que determina si existe un grado en la ecuación * @param degree grado a checar * @return boolean (verdadero - existe, falso - no existe) */ public boolean hasEquationDegree(double degree){ return degrees.contains(degree); } /** * Método que convierte a String una ecuación * @return String (ecuación) */ public String toString(){ String Res = ""; for (ETerm term: Equation) { Res = Res +((int)term.Sign>0?"+":"")+(int)term.Sign+"*"+term.Cons+(term.hasX?"x^"+term.Degree:""); } return Res; } /** * Método que evalua un valor x en la función * @param x valor a evaluar * @return double (f(x)) */ public double getFin(double x){ double res = 0; for (ETerm term: Equation) { res = res + (term.Sign*term.Cons*Math.pow(x, term.Degree)); } return res; } /** * Método que regresa la derivada de la ecuación * @return PolyEquation (derivada) */ public PolyEquation derivate(){ List<ETerm> new_terms = new ArrayList<ETerm>(); for(ETerm term : Equation){ if(term.hasX){ ETerm temp = new ETerm(); temp.Degree = term.Degree - (double) 1; if(temp.Degree == 0){ temp.hasX = false; } else{ temp.hasX = true; } temp.Cons = term.Sign * term.Cons * term.Degree; if(temp.Cons>0){ temp.Sign = 1; } else { if(temp.Cons<0){ temp.Sign = -1; temp.Cons = temp.Cons * -1; } else { temp.Cons = 0; } } new_terms.add(temp); } } if(new_terms.isEmpty()){ ETerm term_aux = new ETerm(); term_aux.Degree = 0; term_aux.Sign = 1; term_aux.Cons = 0; term_aux.hasX = false; new_terms.add(term_aux); } PolyEquation Res = new PolyEquation(); Res.Equation = new_terms; Res.createPolyEquation(); return Res; } }
30.725664
139
0.488047
827a36c9e6c00c602d2f80321fd42946b1d964c1
6,698
package malte0811.controlengineering.gui.logic; import com.mojang.blaze3d.vertex.PoseStack; import malte0811.controlengineering.gui.StackedScreen; import malte0811.controlengineering.gui.widget.PageSelector; import malte0811.controlengineering.logic.schematic.client.ClientSymbols; import malte0811.controlengineering.logic.schematic.symbol.SchematicSymbol; import malte0811.controlengineering.logic.schematic.symbol.SchematicSymbols; import malte0811.controlengineering.logic.schematic.symbol.SymbolInstance; import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TextComponent; import net.minecraft.util.Mth; import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; public class CellSelectionScreen extends StackedScreen { private static final float TEXT_SCALE = 4; private static final int BORDER_SIZE_X = 70; private static final int BORDER_SIZE_Y = 30; private static final int BACKGROUND_COLOR = 0xffdddddd; private static final int SELECTED_COLOR = 0xff77dd77; private final Consumer<SymbolInstance<?>> select; private final List<SchematicSymbol<?>> symbols; private int xGrid; private int yGrid; private final int numCols = 4; private final int numRowsPerPage = 4; private PageSelector pageSelector; // Necessary to prevent closing two screens at once, which isn't possible private SymbolInstance<?> selected; public CellSelectionScreen(Consumer<SymbolInstance<?>> select) { super(new TextComponent("Cell selection")); this.select = select; this.symbols = new ArrayList<>(SchematicSymbols.REGISTRY.getValues()); } @Override protected void init() { super.init(); xGrid = (width - 2 * BORDER_SIZE_X) / (numCols * LogicDesignScreen.BASE_SCALE); yGrid = (height - 2 * BORDER_SIZE_Y - PageSelector.HEIGHT) / (numRowsPerPage * LogicDesignScreen.BASE_SCALE); this.pageSelector = addRenderableWidget(new PageSelector( BORDER_SIZE_X, height - BORDER_SIZE_Y - PageSelector.HEIGHT, width - 2 * BORDER_SIZE_X, Mth.positiveCeilDiv(symbols.size(), numCols * numRowsPerPage), this.pageSelector != null ? this.pageSelector.getCurrentPage() : 0 )); } @Override protected void renderForeground( @Nonnull PoseStack matrixStack, int mouseX, int mouseY, float partialTicks ) { matrixStack.pushPose(); matrixStack.translate(BORDER_SIZE_X, BORDER_SIZE_Y, 0); matrixStack.scale(LogicDesignScreen.BASE_SCALE, LogicDesignScreen.BASE_SCALE, 1); final var fontHeight = getTotalFontHeight(); int index = getFirstIndexOnPage(); for (int row = 0; index < symbols.size() && row < numRowsPerPage; ++row) { for (int col = 0; index < symbols.size() && col < numCols; ++col) { SchematicSymbol<?> symbol = symbols.get(index); final int xBase = col * xGrid; final int yBase = row * yGrid; ClientSymbols.renderCenteredInBox( symbol.newInstance(), matrixStack, xBase, yBase + fontHeight, xGrid, yGrid - fontHeight - 1 ); matrixStack.pushPose(); matrixStack.translate(xBase + xGrid / 2., yBase + 1, 0); matrixStack.scale(1 / TEXT_SCALE, 1 / TEXT_SCALE, 1); Component desc = symbol.getDefaultName(); final var offset = -font.width(desc) / 2f; font.draw(matrixStack, desc, offset, 0, 0xff000000); matrixStack.popPose(); ++index; } } matrixStack.popPose(); } @Override protected void renderCustomBackground( @Nonnull PoseStack matrixStack, int mouseX, int mouseY, float partialTicks ) { super.renderCustomBackground(matrixStack, mouseX, mouseY, partialTicks); final int borderRenderSize = 5; fill( matrixStack, BORDER_SIZE_X - borderRenderSize, BORDER_SIZE_Y - borderRenderSize, this.width - BORDER_SIZE_X + borderRenderSize, this.height - BORDER_SIZE_Y - PageSelector.HEIGHT, BACKGROUND_COLOR ); matrixStack.pushPose(); matrixStack.translate(BORDER_SIZE_X, BORDER_SIZE_Y, 0); matrixStack.scale(LogicDesignScreen.BASE_SCALE, LogicDesignScreen.BASE_SCALE, 1); final int selected = getSelectedIndex(mouseX, mouseY) - getFirstIndexOnPage(); if (selected >= 0) { final int row = selected / numCols; final int col = selected % numCols; fill( matrixStack, col * xGrid, row * yGrid, col * xGrid + xGrid, row * yGrid + yGrid, SELECTED_COLOR ); } matrixStack.popPose(); } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (super.mouseClicked(mouseX, mouseY, button)) { return true; } final int selected = getSelectedIndex(mouseX, mouseY); if (selected >= 0) { ClientSymbols.createInstanceWithUI(symbols.get(selected), i -> this.selected = i); return true; } else { return false; } } @Override public void tick() { super.tick(); if (selected != null) { select.accept(selected); onClose(); } } private int getSelectedIndex(double mouseX, double mouseY) { final int col = (int) ((mouseX - BORDER_SIZE_X) / (xGrid * LogicDesignScreen.BASE_SCALE)); final int row = (int) ((mouseY - BORDER_SIZE_Y) / (yGrid * LogicDesignScreen.BASE_SCALE)); if (col < 0 || row < 0 || col >= numCols || row >= numRowsPerPage) { return -1; } final int index = row * numCols + col + getFirstIndexOnPage(); if (index < symbols.size()) { return index; } else { return -1; } } private int getFirstIndexOnPage() { return this.pageSelector.getCurrentPage() * numRowsPerPage * numCols; } private int getTotalFontHeight() { return (int) (Minecraft.getInstance().font.lineHeight / TEXT_SCALE + 1); } private static Level level() { return Objects.requireNonNull(Minecraft.getInstance().level); } }
39.869048
117
0.630188
fe7d202f14435db4983c28794d5b1b3aa29bde85
4,955
/* * 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; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.ml.rest.modelsnapshots; import org.elasticsearch.client.internal.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.core.RestApiVersion; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.RestToXContentListener; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xpack.core.action.util.PageParams; import org.elasticsearch.xpack.core.ml.action.GetModelSnapshotsAction; import org.elasticsearch.xpack.core.ml.action.GetModelSnapshotsAction.Request; import org.elasticsearch.xpack.core.ml.job.config.Job; import java.io.IOException; import java.util.List; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.xpack.ml.MachineLearning.BASE_PATH; import static org.elasticsearch.xpack.ml.MachineLearning.PRE_V7_BASE_PATH; public class RestGetModelSnapshotsAction extends BaseRestHandler { private static final String ALL_SNAPSHOT_IDS = null; // Even though these are null, setting up the defaults in case // we want to change them later private static final String DEFAULT_SORT = null; private static final String DEFAULT_START = null; private static final String DEFAULT_END = null; private static final boolean DEFAULT_DESC_ORDER = true; @Override public List<Route> routes() { return List.of( Route.builder(GET, BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots/{" + Request.SNAPSHOT_ID + "}") .replaces( GET, PRE_V7_BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots/{" + Request.SNAPSHOT_ID + "}", RestApiVersion.V_7 ) .build(), Route.builder(POST, BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots/{" + Request.SNAPSHOT_ID + "}") .replaces( POST, PRE_V7_BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots/{" + Request.SNAPSHOT_ID + "}", RestApiVersion.V_7 ) .build(), Route.builder(GET, BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots") .replaces(GET, PRE_V7_BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots", RestApiVersion.V_7) .build(), Route.builder(POST, BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots") .replaces(POST, PRE_V7_BASE_PATH + "anomaly_detectors/{" + Job.ID + "}/model_snapshots", RestApiVersion.V_7) .build() ); } @Override public String getName() { return "ml_get_model_snapshot_action"; } @Override protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { String jobId = restRequest.param(Job.ID.getPreferredName()); String snapshotId = restRequest.param(Request.SNAPSHOT_ID.getPreferredName()); if (Strings.isAllOrWildcard(snapshotId)) { snapshotId = ALL_SNAPSHOT_IDS; } Request getModelSnapshots; if (restRequest.hasContentOrSourceParam()) { XContentParser parser = restRequest.contentOrSourceParamParser(); getModelSnapshots = Request.parseRequest(jobId, snapshotId, parser); } else { getModelSnapshots = new Request(jobId, snapshotId); getModelSnapshots.setSort(restRequest.param(Request.SORT.getPreferredName(), DEFAULT_SORT)); if (restRequest.hasParam(Request.START.getPreferredName())) { getModelSnapshots.setStart(restRequest.param(Request.START.getPreferredName(), DEFAULT_START)); } if (restRequest.hasParam(Request.END.getPreferredName())) { getModelSnapshots.setEnd(restRequest.param(Request.END.getPreferredName(), DEFAULT_END)); } getModelSnapshots.setDescOrder(restRequest.paramAsBoolean(Request.DESC.getPreferredName(), DEFAULT_DESC_ORDER)); getModelSnapshots.setPageParams( new PageParams( restRequest.paramAsInt(PageParams.FROM.getPreferredName(), PageParams.DEFAULT_FROM), restRequest.paramAsInt(PageParams.SIZE.getPreferredName(), PageParams.DEFAULT_SIZE) ) ); } return channel -> client.execute(GetModelSnapshotsAction.INSTANCE, getModelSnapshots, new RestToXContentListener<>(channel)); } }
48.106796
133
0.680121
318fffdfbd13287ad2e7f49f5a0e968467c0dd66
12,543
package com.kylin.electricassistsys.entity.project; import com.kylin.electricassistsys.entity.BaseEntity; import com.kylin.electricassistsys.entity.enumparam.KeyValueType; import com.kylin.electricassistsys.utility.FieldMeta; import com.kylin.electricassistsys.utility.TagType; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import tk.mybatis.mapper.annotation.NameStyle; import tk.mybatis.mapper.code.Style; import javax.persistence.Table; import javax.persistence.Transient; @NameStyle(Style.normal) @Table(name="Xmqc") public class DwGzGcEntity extends BaseEntity { @NotBlank(message ="必填项" ) @Length(max = 20,message = "20位以内字符") @FieldMeta(description = "项目名称", index = 1,queryField = true, editTagType = TagType.INPUT_TEXT) private String xmmc = ""; @NotBlank(message ="必填项" ) @FieldMeta(description = "运维单位", index = 2, show = false, isExport = false,editTagType = TagType.SELECT, keyValueType = KeyValueType.GDGS) private String ywdwId = ""; @Transient @FieldMeta(description = "运维单位", index = 2, editTagType = TagType.NONE,isImport = false) private String ywdwName = ""; @NotBlank(message ="必填项" ) @FieldMeta(description = "所属区域", index = 3, show = false, isExport = false, editTagType = TagType.SELECT, keyValueType = KeyValueType.QY) private String qyId = ""; @Transient @FieldMeta(description = "所属区域", index = 3, editTagType = TagType.NONE,isImport = false) private String qyName = ""; @NotBlank(message ="必填项" ) @FieldMeta(description = "规划年份", index = 4) private String ghnf = ""; @NotBlank(message ="必填项" ) @FieldMeta(description = "供区类型", index = 5,queryField = true, editTagType = TagType.SELECT,keyValueType = KeyValueType.SUPPLY_ZONE_TYPE) private String gqlx = ""; @NotBlank(message ="必填项" ) @FieldMeta(description = "电压等级", index = 6, queryField = true, editTagType = TagType.SELECT, keyValueType = KeyValueType.VOLTAGE) private String voltage = ""; @NotBlank(message ="必填项" ) @FieldMeta(description = "城农网", index = 7, editTagType = TagType.SELECT, keyValueType = KeyValueType.CNW) private String cnw = ""; @FieldMeta(description = "资产属性", index = 8) private String zcsx= ""; @FieldMeta(description = "总投资(万元)", index = 9) private float xmtz; @FieldMeta(description = "农网建设性质1", index = 10) private String nwjsxz1= ""; @FieldMeta(description = "农网建设性质2", index = 11) private String nwjsxz2= ""; @FieldMeta(description = "农网建设性质3", index = 12) private String nwjsxz3= ""; @FieldMeta(description = "工程性质", index = 13) private String gcxz = ""; @FieldMeta(description = "改造总台数(台)", index = 14) private int gzzts; @FieldMeta(description = "改造前总容量(KVar)", index = 15) private float gzqzrl; @FieldMeta(description = "改造后总容量(KVar)", index = 16) private float gzhzrl; @FieldMeta(description = "其中:改造高损台数(台)", index = 17) private int gzgsts; @FieldMeta(description = "其中:改造高损容量(KVar)", index = 18) private float gzgsrl; @FieldMeta(description = "配变投资(万元)", index = 19) private float pbtz; @FieldMeta(description = "其中:更换非晶台数(台)", index = 20) private int fjts; @FieldMeta(description = "其中:更换非晶容量(KVar)", index = 21) private float fjrl; @FieldMeta(description = "无功补偿-组数(组)", index = 22) private int wgzs; @FieldMeta(description = "无功补偿-总容量(KVar)", index = 23) private float wgzrl; @FieldMeta(description = "无功补偿-投资(万元)", index = 24) private float wgtz; @FieldMeta(description = "断路器(台)", index = 25) private int dlq; @FieldMeta(description = "负荷开关(台)", index = 26) private int fhkg; @FieldMeta(description = "环网柜(座)", index = 27) private int hwg; @FieldMeta(description = "电缆分支箱(座)", index = 28) private int dlfzx; @FieldMeta(description = "开关投资(万元)", index = 29) private float kgtz; @FieldMeta(description = "架空线路条数(条)", index = 30) private int jkxlts; @FieldMeta(description = "架空线路长度(km)", index = 31) private float jkxlcd; @FieldMeta(description = "绝缘导线长度(km)", index = 32) private float jydxcd; @FieldMeta(description = "架空线路投资(万元)", index = 33) private float jkxltz; @FieldMeta(description = "电缆条数(条)", index = 34) private int dlts; @FieldMeta(description = "电缆线路长度(km)", index = 35) private float dlxlcd; @FieldMeta(description = "沟道长度(km)", index = 36) private float gdcd; @FieldMeta(description = "电缆投资(万元)", index = 37) private float dlxltz; @FieldMeta(description = "户表(户)", index = 38) private int hb; @FieldMeta(description = "接户线(km)", index = 39) private float jhx; @FieldMeta(description = "户表投资(万元)", index = 40) private float hbtz; @FieldMeta(description = "中央计划(%)", index = 41) private float zyjh; @FieldMeta(description = "公司自筹(%)", index = 42) private float gszc; @FieldMeta(description = "县级供电企业自筹(%)", index = 43) private float xjgdqyzc; @FieldMeta(description = "用户投资(%)", index = 44) private float yhtz; @FieldMeta(description = "小区配套费(%)", index = 45) private float xqptf; @FieldMeta(description = "政府垫资(%)", index = 46) private float zfdz; @FieldMeta(description = "其他投资(%)", index = 47) private float qttz; @FieldMeta(description = "類型",show =false,index = 48,isExport = false, isImport = false) private int type; public int getType() { return type; } public void setType(int type) { this.type = type; } public String getXmmc() { return xmmc; } public void setXmmc(String xmmc) { this.xmmc = xmmc; } public String getYwdwId() { return ywdwId; } public void setYwdwId(String ywdwId) { this.ywdwId = ywdwId; } public String getYwdwName() { return ywdwName; } public void setYwdwName(String ywdwName) { this.ywdwName = ywdwName; } public String getQyId() { return qyId; } public void setQyId(String qyId) { this.qyId = qyId; } public String getQyName() { return qyName; } public void setQyName(String qyName) { this.qyName = qyName; } public String getGhnf() { return ghnf; } public void setGhnf(String ghnf) { this.ghnf = ghnf; } public String getGqlx() { return gqlx; } public void setGqlx(String gqlx) { this.gqlx = gqlx; } public String getVoltage() { return voltage; } public void setVoltage(String voltage) { this.voltage = voltage; } public String getCnw() { return cnw; } public void setCnw(String cnw) { this.cnw = cnw; } public String getZcsx() { return zcsx; } public void setZcsx(String zcsx) { this.zcsx = zcsx; } public float getXmtz() { return xmtz; } public void setXmtz(float xmtz) { this.xmtz = xmtz; } public String getNwjsxz1() { return nwjsxz1; } public void setNwjsxz1(String nwjsxz1) { this.nwjsxz1 = nwjsxz1; } public String getNwjsxz2() { return nwjsxz2; } public void setNwjsxz2(String nwjsxz2) { this.nwjsxz2 = nwjsxz2; } public String getNwjsxz3() { return nwjsxz3; } public void setNwjsxz3(String nwjsxz3) { this.nwjsxz3 = nwjsxz3; } public String getGcxz() { return gcxz; } public void setGcxz(String gcxz) { this.gcxz = gcxz; } public int getGzzts() { return gzzts; } public void setGzzts(int gzzts) { this.gzzts = gzzts; } public float getGzqzrl() { return gzqzrl; } public void setGzqzrl(float gzqzrl) { this.gzqzrl = gzqzrl; } public float getGzhzrl() { return gzhzrl; } public void setGzhzrl(float gzhzrl) { this.gzhzrl = gzhzrl; } public int getGzgsts() { return gzgsts; } public void setGzgsts(int gzgsts) { this.gzgsts = gzgsts; } public float getGzgsrl() { return gzgsrl; } public void setGzgsrl(float gzgsrl) { this.gzgsrl = gzgsrl; } public float getPbtz() { return pbtz; } public void setPbtz(float pbtz) { this.pbtz = pbtz; } public int getFjts() { return fjts; } public void setFjts(int fjts) { this.fjts = fjts; } public float getFjrl() { return fjrl; } public void setFjrl(float fjrl) { this.fjrl = fjrl; } public int getWgzs() { return wgzs; } public void setWgzs(int wgzs) { this.wgzs = wgzs; } public float getWgzrl() { return wgzrl; } public void setWgzrl(float wgzrl) { this.wgzrl = wgzrl; } public float getWgtz() { return wgtz; } public void setWgtz(float wgtz) { this.wgtz = wgtz; } public int getDlq() { return dlq; } public void setDlq(int dlq) { this.dlq = dlq; } public int getFhkg() { return fhkg; } public void setFhkg(int fhkg) { this.fhkg = fhkg; } public int getHwg() { return hwg; } public void setHwg(int hwg) { this.hwg = hwg; } public int getDlfzx() { return dlfzx; } public void setDlfzx(int dlfzx) { this.dlfzx = dlfzx; } public float getKgtz() { return kgtz; } public void setKgtz(float kgtz) { this.kgtz = kgtz; } public int getJkxlts() { return jkxlts; } public void setJkxlts(int jkxlts) { this.jkxlts = jkxlts; } public float getJkxlcd() { return jkxlcd; } public void setJkxlcd(float jkxlcd) { this.jkxlcd = jkxlcd; } public float getJydxcd() { return jydxcd; } public void setJydxcd(float jydxcd) { this.jydxcd = jydxcd; } public float getJkxltz() { return jkxltz; } public void setJkxltz(float jkxltz) { this.jkxltz = jkxltz; } public int getDlts() { return dlts; } public void setDlts(int dlts) { this.dlts = dlts; } public float getDlxlcd() { return dlxlcd; } public void setDlxlcd(float dlxlcd) { this.dlxlcd = dlxlcd; } public float getGdcd() { return gdcd; } public void setGdcd(float gdcd) { this.gdcd = gdcd; } public float getDlxltz() { return dlxltz; } public void setDlxltz(float dlxltz) { this.dlxltz = dlxltz; } public int getHb() { return hb; } public void setHb(int hb) { this.hb = hb; } public float getJhx() { return jhx; } public void setJhx(float jhx) { this.jhx = jhx; } public float getHbtz() { return hbtz; } public void setHbtz(float hbtz) { this.hbtz = hbtz; } public float getZyjh() { return zyjh; } public void setZyjh(float zyjh) { this.zyjh = zyjh; } public float getGszc() { return gszc; } public void setGszc(float gszc) { this.gszc = gszc; } public float getXjgdqyzc() { return xjgdqyzc; } public void setXjgdqyzc(float xjgdqyzc) { this.xjgdqyzc = xjgdqyzc; } public float getYhtz() { return yhtz; } public void setYhtz(float yhtz) { this.yhtz = yhtz; } public float getXqptf() { return xqptf; } public void setXqptf(float xqptf) { this.xqptf = xqptf; } public float getZfdz() { return zfdz; } public void setZfdz(float zfdz) { this.zfdz = zfdz; } public float getQttz() { return qttz; } public void setQttz(float qttz) { this.qttz = qttz; } }
18.418502
142
0.573627
478c053b9357f2205b26a51a4d09c3c542dba057
802
package com.example.nanchen.aiyaschoolpush.ui.activity; import android.os.Bundle; import com.example.nanchen.aiyaschoolpush.R; import com.example.nanchen.aiyaschoolpush.ui.view.TitleView; import me.wangyuwei.particleview.ParticleView; public class AboutActivity extends ActivityBase { private TitleView mTitleBar; private ParticleView mParticleView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); mTitleBar = (TitleView) findViewById(R.id.about_titleBar); mTitleBar.setTitle("关于我们"); mTitleBar.setLeftButtonAsFinish(this); // mParticleView = (ParticleView) findViewById(R.id.about_particle); // mParticleView.startAnim(); } }
27.655172
75
0.744389
8abc7302e7ac86505e23d86efa817ed279ae8c4a
317
import java.util.*; public class conheo { //public class Main { public static int sum(int a, int b) { return a + b; } public static void main(String[] args) { int sum = sum(2,5); System.out.println(sum); } }
21.133333
49
0.44164
250a68407fa5542f136fbc455c6d89118f5a217d
4,920
// Copyright 2012,2013 Vaughn Vernon // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.saasovation.agilepm.domain.model.team; import java.util.Collections; import java.util.HashSet; import java.util.Set; import com.saasovation.agilepm.domain.model.Entity; import com.saasovation.agilepm.domain.model.tenant.TenantId; public class Team extends Entity { private String name; private ProductOwner productOwner; private Set<TeamMember> teamMembers; private TenantId tenantId; public Team(TenantId aTenantId, String aName, ProductOwner aProductOwner) { this(); this.setName(aName); this.setProductOwner(aProductOwner); this.setTenantId(aTenantId); } public Team(TenantId aTenantId, String aName) { this(); this.setName(aName); this.setTenantId(aTenantId); } public Set<TeamMember> allTeamMembers() { return Collections.unmodifiableSet(this.teamMembers()); } public void assignProductOwner(ProductOwner aProductOwner) { this.assertArgumentEquals(this.tenantId(), aProductOwner.tenantId(), "Product owner must be of the same tenant."); this.setProductOwner(aProductOwner); } public void assignTeamMember(TeamMember aTeamMember) { this.assertArgumentEquals(this.tenantId(), aTeamMember.tenantId(), "Team member must be of the same tenant."); this.teamMembers().add(aTeamMember); } public String name() { return this.name; } public boolean isTeamMember(TeamMember aTeamMember) { this.assertArgumentEquals(this.tenantId(), aTeamMember.tenantId(), "Team member must be of the same tenant."); boolean isTeamMember = false; String usernameToMatch = aTeamMember.username(); for (TeamMember member : this.teamMembers()) { if (member.username().equals(usernameToMatch)) { isTeamMember = true; break; } } return isTeamMember; } public ProductOwner productOwner() { return this.productOwner; } public void removeTeamMember(TeamMember aTeamMember) { this.assertArgumentEquals(this.tenantId(), aTeamMember.tenantId(), "Team member must be of the same tenant."); TeamMember memberToRemove = null; String usernameToMatch = aTeamMember.username(); for (TeamMember member : this.teamMembers()) { if (member.username().equals(usernameToMatch)) { memberToRemove = member; break; } } this.teamMembers().remove(memberToRemove); } public TenantId tenantId() { return this.tenantId; } @Override public boolean equals(Object anObject) { boolean equalObjects = false; if (anObject != null && this.getClass() == anObject.getClass()) { Team typedObject = (Team) anObject; equalObjects = this.tenantId().equals(typedObject.tenantId()) && this.name().equals(typedObject.name()); } return equalObjects; } @Override public int hashCode() { int hashCodeValue = + (63815 * 59) + this.tenantId().hashCode() + this.name().hashCode(); return hashCodeValue; } private Team() { super(); this.setTeamMembers(new HashSet<TeamMember>(0)); } private void setName(String aName) { this.assertArgumentNotEmpty(aName, "The name must be provided."); this.assertArgumentLength(aName, 100, "The name must be 100 characters or less."); this.name = aName; } private void setProductOwner(ProductOwner aProductOwner) { this.assertArgumentNotNull(aProductOwner, "The productOwner must be provided."); this.assertArgumentEquals(this.tenantId(), aProductOwner.tenantId(), "The productOwner must be of the same tenant."); this.productOwner = aProductOwner; } private Set<TeamMember> teamMembers() { return this.teamMembers; } private void setTeamMembers(Set<TeamMember> aTeamMembers) { this.teamMembers = aTeamMembers; } private void setTenantId(TenantId aTenantId) { this.assertArgumentNotNull(aTenantId, "The tenantId must be provided."); this.tenantId = aTenantId; } }
30
125
0.652236
72f115e134f1bc8a532d7e4af1b4fe66c0a43b8a
30,538
package com.rabbit.gui.component.code.parser; // Generated from Python3.g4 by ANTLR 4.5.3 import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link Python3Listener}, which * can be extended to create a listener which only needs to handle a subset of * the available methods. */ public class Python3BaseListener implements Python3Listener { /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterAnd_expr(Python3Parser.And_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterAnd_test(Python3Parser.And_testContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterArglist(Python3Parser.ArglistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterArgument(Python3Parser.ArgumentContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterArith_expr(Python3Parser.Arith_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterAssert_stmt(Python3Parser.Assert_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterAtom(Python3Parser.AtomContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterAugassign(Python3Parser.AugassignContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterBreak_stmt(Python3Parser.Break_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterClassdef(Python3Parser.ClassdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterComp_for(Python3Parser.Comp_forContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterComp_if(Python3Parser.Comp_ifContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterComp_iter(Python3Parser.Comp_iterContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterComp_op(Python3Parser.Comp_opContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterComparison(Python3Parser.ComparisonContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterCompound_stmt(Python3Parser.Compound_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterContinue_stmt(Python3Parser.Continue_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDecorated(Python3Parser.DecoratedContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDecorator(Python3Parser.DecoratorContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDecorators(Python3Parser.DecoratorsContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDel_stmt(Python3Parser.Del_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDictorsetmaker(Python3Parser.DictorsetmakerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDotted_as_name(Python3Parser.Dotted_as_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDotted_as_names(Python3Parser.Dotted_as_namesContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterDotted_name(Python3Parser.Dotted_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterEval_input(Python3Parser.Eval_inputContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterExcept_clause(Python3Parser.Except_clauseContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterExpr(Python3Parser.ExprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterExpr_stmt(Python3Parser.Expr_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterExprlist(Python3Parser.ExprlistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterFactor(Python3Parser.FactorContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterFile_input(Python3Parser.File_inputContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterFlow_stmt(Python3Parser.Flow_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterFor_stmt(Python3Parser.For_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterFuncdef(Python3Parser.FuncdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterGlobal_stmt(Python3Parser.Global_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterIf_stmt(Python3Parser.If_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterImport_as_name(Python3Parser.Import_as_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterImport_as_names(Python3Parser.Import_as_namesContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterImport_from(Python3Parser.Import_fromContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterImport_name(Python3Parser.Import_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterImport_stmt(Python3Parser.Import_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterInteger(Python3Parser.IntegerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterLambdef(Python3Parser.LambdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterLambdef_nocond(Python3Parser.Lambdef_nocondContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterNonlocal_stmt(Python3Parser.Nonlocal_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterNot_test(Python3Parser.Not_testContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterNumber(Python3Parser.NumberContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterOr_test(Python3Parser.Or_testContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterParameters(Python3Parser.ParametersContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterPass_stmt(Python3Parser.Pass_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterPower(Python3Parser.PowerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterRaise_stmt(Python3Parser.Raise_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterReturn_stmt(Python3Parser.Return_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterShift_expr(Python3Parser.Shift_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterSimple_stmt(Python3Parser.Simple_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterSingle_input(Python3Parser.Single_inputContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterSliceop(Python3Parser.SliceopContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterSmall_stmt(Python3Parser.Small_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterStar_expr(Python3Parser.Star_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterStmt(Python3Parser.StmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterString(Python3Parser.StringContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterSubscript(Python3Parser.SubscriptContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterSubscriptlist(Python3Parser.SubscriptlistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterSuite(Python3Parser.SuiteContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTerm(Python3Parser.TermContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTest(Python3Parser.TestContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTest_nocond(Python3Parser.Test_nocondContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTestlist(Python3Parser.TestlistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTestlist_comp(Python3Parser.Testlist_compContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTestlist_star_expr(Python3Parser.Testlist_star_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTfpdef(Python3Parser.TfpdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTrailer(Python3Parser.TrailerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTry_stmt(Python3Parser.Try_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterTypedargslist(Python3Parser.TypedargslistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterVarargslist(Python3Parser.VarargslistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterVfpdef(Python3Parser.VfpdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterWhile_stmt(Python3Parser.While_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterWith_item(Python3Parser.With_itemContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterWith_stmt(Python3Parser.With_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterXor_expr(Python3Parser.Xor_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterYield_arg(Python3Parser.Yield_argContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterYield_expr(Python3Parser.Yield_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void enterYield_stmt(Python3Parser.Yield_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitAnd_expr(Python3Parser.And_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitAnd_test(Python3Parser.And_testContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitArglist(Python3Parser.ArglistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitArgument(Python3Parser.ArgumentContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitArith_expr(Python3Parser.Arith_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitAssert_stmt(Python3Parser.Assert_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitAtom(Python3Parser.AtomContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitAugassign(Python3Parser.AugassignContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitBreak_stmt(Python3Parser.Break_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitClassdef(Python3Parser.ClassdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitComp_for(Python3Parser.Comp_forContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitComp_if(Python3Parser.Comp_ifContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitComp_iter(Python3Parser.Comp_iterContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitComp_op(Python3Parser.Comp_opContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitComparison(Python3Parser.ComparisonContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitCompound_stmt(Python3Parser.Compound_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitContinue_stmt(Python3Parser.Continue_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDecorated(Python3Parser.DecoratedContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDecorator(Python3Parser.DecoratorContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDecorators(Python3Parser.DecoratorsContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDel_stmt(Python3Parser.Del_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDictorsetmaker(Python3Parser.DictorsetmakerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDotted_as_name(Python3Parser.Dotted_as_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDotted_as_names(Python3Parser.Dotted_as_namesContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitDotted_name(Python3Parser.Dotted_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitEval_input(Python3Parser.Eval_inputContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitExcept_clause(Python3Parser.Except_clauseContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitExpr(Python3Parser.ExprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitExpr_stmt(Python3Parser.Expr_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitExprlist(Python3Parser.ExprlistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitFactor(Python3Parser.FactorContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitFile_input(Python3Parser.File_inputContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitFlow_stmt(Python3Parser.Flow_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitFor_stmt(Python3Parser.For_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitFuncdef(Python3Parser.FuncdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitGlobal_stmt(Python3Parser.Global_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitIf_stmt(Python3Parser.If_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitImport_as_name(Python3Parser.Import_as_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitImport_as_names(Python3Parser.Import_as_namesContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitImport_from(Python3Parser.Import_fromContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitImport_name(Python3Parser.Import_nameContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitImport_stmt(Python3Parser.Import_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitInteger(Python3Parser.IntegerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitLambdef(Python3Parser.LambdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitLambdef_nocond(Python3Parser.Lambdef_nocondContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitNonlocal_stmt(Python3Parser.Nonlocal_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitNot_test(Python3Parser.Not_testContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitNumber(Python3Parser.NumberContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitOr_test(Python3Parser.Or_testContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitParameters(Python3Parser.ParametersContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitPass_stmt(Python3Parser.Pass_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitPower(Python3Parser.PowerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitRaise_stmt(Python3Parser.Raise_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitReturn_stmt(Python3Parser.Return_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitShift_expr(Python3Parser.Shift_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitSimple_stmt(Python3Parser.Simple_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitSingle_input(Python3Parser.Single_inputContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitSliceop(Python3Parser.SliceopContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitSmall_stmt(Python3Parser.Small_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitStar_expr(Python3Parser.Star_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitStmt(Python3Parser.StmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitString(Python3Parser.StringContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitSubscript(Python3Parser.SubscriptContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitSubscriptlist(Python3Parser.SubscriptlistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitSuite(Python3Parser.SuiteContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTerm(Python3Parser.TermContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTest(Python3Parser.TestContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTest_nocond(Python3Parser.Test_nocondContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTestlist(Python3Parser.TestlistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTestlist_comp(Python3Parser.Testlist_compContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTestlist_star_expr(Python3Parser.Testlist_star_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTfpdef(Python3Parser.TfpdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTrailer(Python3Parser.TrailerContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTry_stmt(Python3Parser.Try_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitTypedargslist(Python3Parser.TypedargslistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitVarargslist(Python3Parser.VarargslistContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitVfpdef(Python3Parser.VfpdefContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitWhile_stmt(Python3Parser.While_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitWith_item(Python3Parser.With_itemContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitWith_stmt(Python3Parser.With_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitXor_expr(Python3Parser.Xor_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitYield_arg(Python3Parser.Yield_argContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitYield_expr(Python3Parser.Yield_exprContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void exitYield_stmt(Python3Parser.Yield_stmtContext ctx) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void visitErrorNode(ErrorNode node) { } /** * {@inheritDoc} * * <p> * The default implementation does nothing. * </p> */ @Override public void visitTerminal(TerminalNode node) { } }
16.022036
83
0.636289
80a48c4c1b643578eb4f09e32edf532675666fce
4,110
/* Copyright (C) 2002-2004 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. There are special exceptions to the terms and conditions of the GPL as it is applied to this software. View the full text of the exception in file EXCEPTIONS-CONNECTOR-J in the directory of this software distribution. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.mysql.jdbc.log; /** * Unified interface to logging facilities on different platforms * * @author Mark Matthews * * @version $Id: Log.java 3726 2005-05-19 15:52:24Z mmatthews $ */ public interface Log { /** * Is the 'debug' log level enabled? * * @return true if so. */ boolean isDebugEnabled(); /** * Is the 'error' log level enabled? * * @return true if so. */ boolean isErrorEnabled(); /** * Is the 'fatal' log level enabled? * * @return true if so. */ boolean isFatalEnabled(); /** * Is the 'info' log level enabled? * * @return true if so. */ boolean isInfoEnabled(); /** * Is the 'trace' log level enabled? * * @return true if so. */ boolean isTraceEnabled(); /** * Is the 'warn' log level enabled? * * @return true if so. */ boolean isWarnEnabled(); /** * Logs the given message instance using the 'debug' level * * @param msg * the message to log */ void logDebug(Object msg); /** * Logs the given message and Throwable at the 'debug' level. * * @param msg * the message to log * @param thrown * the throwable to log (may be null) */ void logDebug(Object msg, Throwable thrown); /** * Logs the given message instance using the 'error' level * * @param msg * the message to log */ void logError(Object msg); /** * Logs the given message and Throwable at the 'error' level. * * @param msg * the message to log * @param thrown * the throwable to log (may be null) */ void logError(Object msg, Throwable thrown); /** * Logs the given message instance using the 'fatal' level * * @param msg * the message to log */ void logFatal(Object msg); /** * Logs the given message and Throwable at the 'fatal' level. * * @param msg * the message to log * @param thrown * the throwable to log (may be null) */ void logFatal(Object msg, Throwable thrown); /** * Logs the given message instance using the 'info' level * * @param msg * the message to log */ void logInfo(Object msg); /** * Logs the given message and Throwable at the 'info' level. * * @param msg * the message to log * @param thrown * the throwable to log (may be null) */ void logInfo(Object msg, Throwable thrown); /** * Logs the given message instance using the 'trace' level * * @param msg * the message to log */ void logTrace(Object msg); /** * Logs the given message and Throwable at the 'trace' level. * * @param msg * the message to log * @param thrown * the throwable to log (may be null) */ void logTrace(Object msg, Throwable thrown); /** * Logs the given message instance using the 'warn' level * * @param msg * the message to log */ void logWarn(Object msg); /** * Logs the given message and Throwable at the 'warn' level. * * @param msg * the message to log * @param thrown * the throwable to log (may be null) */ void logWarn(Object msg, Throwable thrown); }
22.336957
74
0.62944
37b5e76cc5ac2cb52a2aafd7929cd1631e998e08
131
/** * Contains an extensible framework for writing an HttpClient uses within Morpheus. */ package com.zavtech.morpheus.util.http;
32.75
83
0.778626
23394f8fef0d35612cf7caacd1a7846c6b0033f8
3,126
package com.company.Tries; import com.company.Heap.HeapGeneric; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HuffmanEncoder { HashMap<Character, String> Encoder; HashMap<String, Character> Decoder; public HuffmanEncoder(String feeder) { // 1. create frequency map HashMap<Character, Integer> fmap = new HashMap<>(); for (int i = 0; i < feeder.length(); i++) { char cc = feeder.charAt(i); if (fmap.containsKey(cc)) { int ov = fmap.get(cc); ov = ov + 1; fmap.put(cc, ov); } else { fmap.put(cc, 1); } } // 2. create a min heap HeapGeneric<Node> minHeap=new HeapGeneric<>(true); Set<Map.Entry<Character,Integer>> entryset=fmap.entrySet(); for(Map.Entry<Character,Integer> entry: entryset){ Node node =new Node(entry.getKey(),entry.getValue()); minHeap.add(node); } // 3. combine nodes until one node is left while(minHeap.size()!=1){ Node minone=minHeap.remove(); Node mintwo=minHeap.remove(); Node combined=new Node(minone,mintwo); combined.data='\0'; combined.cost=minone.cost+mintwo.cost; minHeap.add(combined); } Node ft=minHeap.remove(); this.Decoder=new HashMap<>(); this.Encoder=new HashMap<>(); this.initEncoderDecoder(ft,""); } private void initEncoderDecoder(Node node,String osf){ if(node==null){ return; } if(node.left==null && node.right==null){ this.Encoder.put(node.data,osf); this.Decoder.put(osf,node.data); } this.initEncoderDecoder(node.left,osf+"0"); this.initEncoderDecoder(node.right,osf+"1"); } public String encode(String source ){ String rv=""; for(int i=0;i<source.length();i++){ String code=this.Encoder.get(source.charAt(i)); rv=rv+code; } return rv; } public String decode(String codedstring ){ String rv=""; String key=""; for(int i=0;i<codedstring.length();i++) { key = key + codedstring.charAt(i); if (this.Decoder.containsKey(key)) { rv = rv + this.Decoder.get(key); key = ""; } } return rv; } private class Node implements Comparable<Node> { Character data; int cost; Node left; Node right; Node(char data, int cost) { this.data = data; this.cost = cost; this.left = null; this.right = null; } Node(Node left,Node right){ this.left=left; this.right=right; } @Override public int compareTo(Node o) { return this.cost - o.cost; } } }
29.214953
68
0.504159
ec0d11e1c1cd8ae77a3118b615fc81afd4271a4f
2,893
// CSD 2013, Pablo Galdámez import java.rmi.*; import java.rmi.server.*; import java.util.*; // // Simple ChatChannel implementation // public class ChatChannel extends UnicastRemoteObject implements IChatChannel { public static final String LEAVE = "LEAVE"; public static final String JOIN = "JOIN"; private String name; private Hashtable <String, IChatUser> users = new Hashtable<String, IChatUser> (); public ChatChannel (String name) throws RemoteException { super (ChatConfiguration.the().getMyPort()); this.name = name; } // // ISA IChatChannel // public String getName () throws RemoteException { return name; } // // ISA IChatChannel // public boolean join (IChatUser usr) throws RemoteException { String nick = usr.getNick(); String keyNick = nick.trim().toLowerCase(); if (users.get (keyNick) != null) return false; // User already in channel users.put (keyNick, usr); notifyUsers (JOIN, nick); return true; } // // ISA IChatChannel // public boolean leave (IChatUser usr) throws RemoteException { String nick = usr.getNick(); String keyNick = nick.trim().toLowerCase(); if (users.get (keyNick) == null) return false; // User not found users.remove (keyNick); // Channel sends a control message to all users at the channel---> one user left notifyUsers (LEAVE, nick); return true; } // // ISA IChatChannel // public void sendMessage (IChatMessage msg) throws RemoteException { purge (); for (IChatUser usr: users.values()) { usr.sendMessage (msg); } } // // ISA IChatChannel // public IChatUser [] listUsers () throws RemoteException { purge (); return users.values().toArray(new IChatUser[users.size()]); } // // private function to purge stale users // private void purge (){ String [] keys = users.keySet().toArray(new String [users.size()]); for (int i=0; i<keys.length; i++) { try { users.get (keys[i]).getNick(); // Remote invo to check if stale or alive } catch (Exception e){ users.remove (keys[i]); // Remove stale users notifyUsers (LEAVE, keys[i]); // this notification sends lowercase nicks (keys) } } } // // When users leave or join this channel, we send a message to the remaning users, so that // they can update their fancy UI's :) // private void notifyUsers (String code, String nick) { IChatMessage msg = null; try { msg = new ChatMessage (null, this, code + " " + nick); } catch (Exception e) {return;} for (IChatUser usr: users.values()) { try { usr.sendMessage (msg); } catch (Exception e) {} // Ignore errors when sending channel notifications } } }
25.830357
93
0.614587
984f1d0f35c96e451765ade74bece67755002ca9
3,433
/* * Copyright © 2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.common.zookeeper.coordination; import com.google.common.collect.Multimap; import com.google.common.collect.TreeMultimap; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import org.apache.twill.discovery.Discoverable; import java.lang.reflect.Type; import java.util.Map; /** * The Gson codec for {@link ResourceAssignment}. */ class ResourceAssignmentTypeAdapter implements JsonSerializer<ResourceAssignment>, JsonDeserializer<ResourceAssignment> { @Override public JsonElement serialize(ResourceAssignment src, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); json.addProperty("name", src.getName()); src.getAssignments().entries(); JsonArray assignments = new JsonArray(); for (Map.Entry<Discoverable, PartitionReplica> entry : src.getAssignments().entries()) { JsonArray entryJson = new JsonArray(); entryJson.add(context.serialize(entry.getKey(), Discoverable.class)); entryJson.add(context.serialize(entry.getValue())); assignments.add(entryJson); } json.add("assignments", assignments); return json; } @Override public ResourceAssignment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("Expect a json object, got " + json); } JsonObject jsonObj = json.getAsJsonObject(); String name = jsonObj.get("name").getAsString(); Multimap<Discoverable, PartitionReplica> assignments = TreeMultimap.create(DiscoverableComparator.COMPARATOR, PartitionReplica.COMPARATOR); JsonArray assignmentsJson = context.deserialize(jsonObj.get("assignments"), JsonArray.class); for (JsonElement element : assignmentsJson) { if (!element.isJsonArray()) { throw new JsonParseException("Expect a json array, got " + element); } JsonArray entryJson = element.getAsJsonArray(); if (entryJson.size() != 2) { throw new JsonParseException("Expect json array of size = 2, got " + entryJson.size()); } Discoverable key = context.deserialize(entryJson.get(0), Discoverable.class); PartitionReplica value = context.deserialize(entryJson.get(1), PartitionReplica.class); assignments.put(key, value); } return new ResourceAssignment(name, assignments); } }
38.573034
113
0.707836
bb4b28068a47578a2e09f9957db295262ce83d88
2,249
/* * 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 Model; import javax.swing.JOptionPane; /** * * @author EDUARDO */ public class Matricula { private int id; private int diaMatricula; private String mesMatricula; public int anoMatricula; public Double nota; public void matricularAluno(){ String id = JOptionPane.showInputDialog(null, "ID"); this.setId(Integer.parseInt(id)); String diaDaMatricula = JOptionPane.showInputDialog(null, "Dia da matricula"); this.setDiaMatricula(Integer.parseInt(diaDaMatricula)); this.setMesMatricula(JOptionPane.showInputDialog(null, "Mes da matricula")); String anoMatriculaa = JOptionPane.showInputDialog(null, "Ano da matricula"); this.setAnoMatricula(Integer.parseInt(anoMatriculaa)); String Nota = JOptionPane.showInputDialog(null, "Nota"); this.setNota(Double.parseDouble(Nota)); } public void exibirMatricula(){ System.out.println("ID "+this.id); System.out.println("Dia da matricula "+this.diaMatricula); System.out.println("Mes da matricula "+this.mesMatricula); System.out.println("Ano da matricua "+this.anoMatricula); System.out.println("Nota "+this.nota); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getDiaMatricula() { return diaMatricula; } public void setDiaMatricula(int diaMatricula) { this.diaMatricula = diaMatricula; } public String getMesMatricula() { return mesMatricula; } public void setMesMatricula(String mesMatricula) { this.mesMatricula = mesMatricula; } public int getAnoMatricula() { return anoMatricula; } public void setAnoMatricula(int anoMatricula) { this.anoMatricula = anoMatricula; } public Double getNota() { return nota; } public void setNota(Double nota) { this.nota = nota; } }
24.445652
86
0.633615
af94974766223b91ee275c9febfcc965cf0651d6
1,072
/** * */ package br.javamagazine.learning.lambda.pojo; import java.math.BigDecimal; /** * Represents a gamer through a gameplay * * @author dinhego * */ public class Gamer { private final String name; private final BigDecimal healthPercentage; /** * Creates a single user of the videogame * * @param name */ public Gamer(final String name) { this.name = name; this.healthPercentage = new BigDecimal(100L); } // getters public String getName() { return this.name; } public BigDecimal getHealthPercentage() { return this.healthPercentage; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Gamer {"); if (this.name != null) { builder.append("name:\""); builder.append(this.name); builder.append("\", "); } if (this.healthPercentage != null) { builder.append("healthPercentage:"); builder.append(this.healthPercentage); } builder.append("}"); return builder.toString(); } }
17.015873
52
0.662313
68c6a1127b65069d5be6fc65408c216b460e3dfc
713
package cloud.javacoder.bbcnewsgems.dictionary; import lombok.Data; import java.util.Objects; /* * Represents word data */ @Data public class DictionaryEntry { private int rank; private String word; private String partOfSpeech; private int frequency; private float dispersion; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DictionaryEntry that = (DictionaryEntry) o; return word.equals(that.word) && partOfSpeech.equals(that.partOfSpeech); } @Override public int hashCode() { return Objects.hash(word, partOfSpeech); } }
21.606061
66
0.646564
1460bf0a5f5cdaa7442b44253ce38f71575b070a
7,836
/* * $Id: JSONValue.java,v 1.1 2006/04/15 14:37:04 platform Exp $ * Created on 2006-4-15 */ package org.json.alt.simple; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; // import java.util.List; import java.util.Map; import org.json.alt.simple.parser.JSONParser; import org.json.alt.simple.parser.ParseException; /** * @author FangYidong<[email protected]> */ public class JSONValue { /** * Parse JSON text into java object from the input source. Please use * parseWithException() if you don't want to ignore the exception. * * @see org.json.alt.simple.parser.JSONParser#parse(Reader) * @see #parseWithException(Reader) * * @param in * @return Instance of the following: org.json.simple.JSONObject, * org.json.simple.JSONArray, java.lang.String, java.lang.Number, * java.lang.Boolean, null * * @deprecated this method may throw an {@code Error} instead of returning * {@code null}; please use * {@link JSONValue#parseWithException(Reader)} instead */ public static Object parse(Reader in) { try { JSONParser parser = new JSONParser(); return parser.parse(in); } catch (Exception e) { return null; } } /** * Parse JSON text into java object from the given string. Please use * parseWithException() if you don't want to ignore the exception. * * @see org.json.alt.simple.parser.JSONParser#parse(Reader) * @see #parseWithException(Reader) * * @param s * @return Instance of the following: org.json.simple.JSONObject, * org.json.simple.JSONArray, java.lang.String, java.lang.Number, * java.lang.Boolean, null * * @deprecated this method may throw an {@code Error} instead of returning * {@code null}; please use * {@link JSONValue#parseWithException(String)} instead */ public static Object parse(String s) { StringReader in = new StringReader(s); return parse(in); } /** * Parse JSON text into java object from the input source. * * @see org.json.alt.simple.parser.JSONParser * * @param in * @return Instance of the following: org.json.simple.JSONObject, * org.json.simple.JSONArray, java.lang.String, java.lang.Number, * java.lang.Boolean, null * * @throws IOException * @throws ParseException */ public static Object parseWithException(Reader in) throws IOException, ParseException { JSONParser parser = new JSONParser(); return parser.parse(in); } public static Object parseWithException(String s) throws ParseException { JSONParser parser = new JSONParser(); return parser.parse(s); } /** * Encode an object into JSON text and write it to out. * <p> * If this object is a Map or a List, and it's also a JSONStreamAware or a * JSONAware, JSONStreamAware or JSONAware will be considered firstly. * <p> * DO NOT call this method from writeJSONString(Writer) of a class that * implements both JSONStreamAware and (Map or List) with "this" as the first * parameter, use JSONObject.writeJSONString(Map, Writer) or * JSONArray.writeJSONString(List, Writer) instead. * * @see org.json.alt.simple.JSONObject#writeJSONString(Map, Writer) * @see org.json.alt.simple.JSONArray#writeJSONString(List, Writer) * * @param value * @param writer */ public static void writeJSONString(Object value, Writer out) throws IOException { if (value == null) { out.write("null"); return; } if (value instanceof String) { out.write('\"'); out.write(escape((String) value)); out.write('\"'); return; } if (value instanceof Double) { if (((Double) value).isInfinite() || ((Double) value).isNaN()) out.write("null"); else out.write(value.toString()); return; } if (value instanceof Float) { if (((Float) value).isInfinite() || ((Float) value).isNaN()) out.write("null"); else out.write(value.toString()); return; } if (value instanceof Number) { out.write(value.toString()); return; } if (value instanceof Boolean) { out.write(value.toString()); return; } if ((value instanceof JSONStreamAware)) { ((JSONStreamAware) value).writeJSONString(out); return; } if ((value instanceof JSONAware)) { out.write(((JSONAware) value).toJSONString()); return; } if (value instanceof Map) { JSONObject.writeJSONString((Map) value, out); return; } if (value instanceof Collection) { JSONArray.writeJSONString((Collection) value, out); return; } if (value instanceof byte[]) { JSONArray.writeJSONString((byte[]) value, out); return; } if (value instanceof short[]) { JSONArray.writeJSONString((short[]) value, out); return; } if (value instanceof int[]) { JSONArray.writeJSONString((int[]) value, out); return; } if (value instanceof long[]) { JSONArray.writeJSONString((long[]) value, out); return; } if (value instanceof float[]) { JSONArray.writeJSONString((float[]) value, out); return; } if (value instanceof double[]) { JSONArray.writeJSONString((double[]) value, out); return; } if (value instanceof boolean[]) { JSONArray.writeJSONString((boolean[]) value, out); return; } if (value instanceof char[]) { JSONArray.writeJSONString((char[]) value, out); return; } if (value instanceof Object[]) { JSONArray.writeJSONString((Object[]) value, out); return; } out.write(value.toString()); } /** * Convert an object to JSON text. * <p> * If this object is a Map or a List, and it's also a JSONAware, JSONAware will * be considered firstly. * <p> * DO NOT call this method from toJSONString() of a class that implements both * JSONAware and Map or List with "this" as the parameter, use * JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead. * * @see org.json.alt.simple.JSONObject#toJSONString(Map) * @see org.json.alt.simple.JSONArray#toJSONString(List) * * @param value * @return JSON text, or "null" if value is null or it's an NaN or an INF * number. */ public static String toJSONString(Object value) { final StringWriter writer = new StringWriter(); try { writeJSONString(value, writer); return writer.toString(); } catch (IOException e) { // This should never happen for a StringWriter throw new RuntimeException(e); } } /** * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 * through U+001F). * * @param s * @return */ public static String escape(String s) { if (s == null) return null; StringBuffer sb = new StringBuffer(); escape(s, sb); return sb.toString(); } /** * @param s - Must not be null. * @param sb */ static void escape(String s, StringBuffer sb) { final int len = s.length(); for (int i = 0; i < len; i++) { char ch = s.charAt(i); switch (ch) { case '"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '/': sb.append("\\/"); break; default: // Reference: http://www.unicode.org/versions/Unicode5.1.0/ if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) { String ss = Integer.toHexString(ch); sb.append("\\u"); for (int k = 0; k < 4 - ss.length(); k++) { sb.append('0'); } sb.append(ss.toUpperCase()); } else { sb.append(ch); } } } // for } }
25.196141
88
0.637315
6e279764ca9ff2495d4bb04dd14f7b9354eb1afe
2,304
package br.com.economize.bean; /** * @author Mateus Henrique Tofanello * */ import java.io.IOException; import java.io.Serializable; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import org.omnifaces.util.Faces; import org.omnifaces.util.Messages; import br.com.economize.controller.ControladorAcessoUsuario; import br.com.economize.dao.UsuarioDAO; import br.com.economize.domain.Usuario; @SuppressWarnings("serial") @ManagedBean @SessionScoped public class AutenticacaoBean implements Serializable { public static final String USUARIO_SESSAO = "usuario"; HttpSession sessao; private Usuario usuario; private Usuario usuarioLogado; private ControladorAcessoUsuario controladorAcesso; public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Usuario getUsuarioLogado() { return usuarioLogado; } public void setUsuarioLogado(Usuario usuarioLogado) { this.usuarioLogado = usuarioLogado; } public ControladorAcessoUsuario getControladorAcesso() { return controladorAcesso; } @PostConstruct public void iniciar() { usuario = new Usuario(); controladorAcesso = new ControladorAcessoUsuario(); } public void autenticar() { try { UsuarioDAO usuarioDAO = new UsuarioDAO(); Usuario usuarioLogado = usuarioDAO.autenticar(usuario.getEmail(), usuario.getSenha(), usuario.getAtivo()); if (usuarioLogado == null) { Messages.addGlobalError("Usuário Inválido ou Incorreto"); return; } sessao = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); sessao.setAttribute("USUARIO_SESSAO", usuarioLogado); controladorAcesso.configurarAcesso(); Faces.redirect("./paginas/inicio.xhtml"); } catch (IOException erro) { erro.printStackTrace(); Messages.addGlobalError(erro.getMessage()); } } public void logout() throws IOException { ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); ec.invalidateSession(); ec.redirect(ec.getRequestContextPath() + "/paginas/autenticacao.xhtml?faces-redirect=true"); } }
25.6
109
0.771701
de4d328ca36abef87232a3618a451b2e931eb051
5,222
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.api.kafka.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.strimzi.crdgenerator.annotations.Description; import io.sundr.builder.annotations.Buildable; import lombok.EqualsAndHashCode; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import static java.util.Collections.emptyMap; @Buildable( editableEnabled = false, builderPackage = Constants.FABRIC8_KUBERNETES_API ) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"sourceCluster", "targetCluster", "sourceConnector", "heartbeatConnector", "checkpointConnector", "topicsPattern", "topicsBlacklistPattern", "groupsPattern", "groupsBlacklistPattern"}) @EqualsAndHashCode public class KafkaMirrorMaker2MirrorSpec implements Serializable, UnknownPropertyPreserving { private static final long serialVersionUID = 1L; private String sourceCluster; private String targetCluster; private KafkaMirrorMaker2ConnectorSpec sourceConnector; private KafkaMirrorMaker2ConnectorSpec checkpointConnector; private KafkaMirrorMaker2ConnectorSpec heartbeatConnector; private String topicsPattern; private String topicsBlacklistPattern; private String groupsPattern; private String groupsBlacklistPattern; private Map<String, Object> additionalProperties; @Description("A regular expression matching the topics to be mirrored, for example, \"topic1|topic2|topic3\". Comma-separated lists are also supported.") public String getTopicsPattern() { return topicsPattern; } public void setTopicsPattern(String topicsPattern) { this.topicsPattern = topicsPattern; } @Description("A regular expression matching the topics to exclude from mirroring. Comma-separated lists are also supported.") public String getTopicsBlacklistPattern() { return topicsBlacklistPattern; } public void setTopicsBlacklistPattern(String topicsBlacklistPattern) { this.topicsBlacklistPattern = topicsBlacklistPattern; } @Description("A regular expression matching the consumer groups to be mirrored. Comma-separated lists are also supported.") public String getGroupsPattern() { return groupsPattern; } public void setGroupsPattern(String groupsPattern) { this.groupsPattern = groupsPattern; } @Description("A regular expression matching the consumer groups to exclude from mirroring. Comma-separated lists are also supported.") public String getGroupsBlacklistPattern() { return groupsBlacklistPattern; } public void setGroupsBlacklistPattern(String groupsBlacklistPattern) { this.groupsBlacklistPattern = groupsBlacklistPattern; } @Description("The alias of the source cluster used by the Kafka MirrorMaker 2.0 connectors. The alias must match a cluster in the list at `spec.clusters`.") @JsonProperty(required = true) public String getSourceCluster() { return sourceCluster; } public void setSourceCluster(String sourceCluster) { this.sourceCluster = sourceCluster; } @Description("The alias of the target cluster used by the Kafka MirrorMaker 2.0 connectors. The alias must match a cluster in the list at `spec.clusters`.") @JsonProperty(required = true) public String getTargetCluster() { return targetCluster; } public void setTargetCluster(String targetCluster) { this.targetCluster = targetCluster; } @Description("The specification of the Kafka MirrorMaker 2.0 source connector.") public KafkaMirrorMaker2ConnectorSpec getSourceConnector() { return sourceConnector; } public void setSourceConnector(KafkaMirrorMaker2ConnectorSpec sourceConnector) { this.sourceConnector = sourceConnector; } @Description("The specification of the Kafka MirrorMaker 2.0 checkpoint connector.") public KafkaMirrorMaker2ConnectorSpec getCheckpointConnector() { return checkpointConnector; } public void setCheckpointConnector(KafkaMirrorMaker2ConnectorSpec checkpointConnector) { this.checkpointConnector = checkpointConnector; } @Description("The specification of the Kafka MirrorMaker 2.0 heartbeat connector.") public KafkaMirrorMaker2ConnectorSpec getHeartbeatConnector() { return heartbeatConnector; } public void setHeartbeatConnector(KafkaMirrorMaker2ConnectorSpec heartbeatConnector) { this.heartbeatConnector = heartbeatConnector; } @Override public Map<String, Object> getAdditionalProperties() { return this.additionalProperties != null ? this.additionalProperties : emptyMap(); } @Override public void setAdditionalProperty(String name, Object value) { if (this.additionalProperties == null) { this.additionalProperties = new HashMap<>(1); } this.additionalProperties.put(name, value); } }
37.568345
204
0.751628
1c3e38c1dd33a450f5764c6529babcd0add26088
482
package greencity.security.service; import greencity.security.dto.SuccessSignInDto; /** * Provides the google social logic. * * @author Nazar Stasyuk && Yurii Koval * @version 1.0 */ public interface GoogleSecurityService { /** * Method that allow you authenticate with google idToken. * * @param idToken {@link String} - google id token. * @return {@link SuccessSignInDto} if token valid */ SuccessSignInDto authenticate(String idToken); }
22.952381
62
0.695021
f133ed6704acffc8c8447f1c6a2c790e7da55d03
16,199
/******************************************************************************* * * Copyright FUJITSU LIMITED 2016 * * Author: pock * * Creation Date: 18.06.2010 * *******************************************************************************/ package org.oscm.triggerservice.bean; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.security.RolesAllowed; import javax.ejb.EJB; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.interceptor.Interceptors; import javax.persistence.Query; import org.oscm.converter.ParameterizedTypes; import org.oscm.dataservice.local.DataService; import org.oscm.domobjects.Organization; import org.oscm.domobjects.TriggerDefinition; import org.oscm.domobjects.TriggerProcess; import org.oscm.interceptor.ExceptionMapper; import org.oscm.interceptor.InvocationDateContainer; import org.oscm.internal.intf.TriggerDefinitionService; import org.oscm.internal.types.enumtypes.OrganizationRoleType; import org.oscm.internal.types.enumtypes.TriggerType; import org.oscm.internal.types.exception.ConcurrentModificationException; import org.oscm.internal.types.exception.DeletionConstraintException; import org.oscm.internal.types.exception.DomainObjectException.ClassEnum; import org.oscm.internal.types.exception.NonUniqueBusinessKeyException; import org.oscm.internal.types.exception.ObjectNotFoundException; import org.oscm.internal.types.exception.OperationNotPermittedException; import org.oscm.internal.types.exception.SaaSSystemException; import org.oscm.internal.types.exception.TriggerDefinitionDataException; import org.oscm.internal.types.exception.ValidationException; import org.oscm.internal.types.exception.ValidationException.ReasonEnum; import org.oscm.internal.vo.VOTriggerDefinition; import org.oscm.logging.Log4jLogger; import org.oscm.logging.LoggerFactory; import org.oscm.triggerservice.assembler.TriggerDefinitionAssembler; import org.oscm.triggerservice.local.TriggerDefinitionServiceLocal; import org.oscm.types.enumtypes.LogMessageIdentifier; import org.oscm.validation.ArgumentValidator; /** * Session Bean implementation class of TriggerDefinitionService * * * */ @Stateless @Remote(TriggerDefinitionService.class) @Local(TriggerDefinitionServiceLocal.class) @Interceptors({ InvocationDateContainer.class, ExceptionMapper.class }) public class TriggerDefinitionServiceBean implements TriggerDefinitionService { private final static Log4jLogger logger = LoggerFactory .getLogger(TriggerDefinitionServiceBean.class); @EJB(beanInterface = DataService.class) protected DataService dm; private static TriggerType[] allowedTriggersForSupplier = { TriggerType.ACTIVATE_SERVICE, TriggerType.DEACTIVATE_SERVICE, TriggerType.REGISTER_CUSTOMER_FOR_SUPPLIER, TriggerType.SAVE_PAYMENT_CONFIGURATION, TriggerType.START_BILLING_RUN, TriggerType.SUBSCRIPTION_CREATION, TriggerType.SUBSCRIPTION_MODIFICATION, TriggerType.SUBSCRIPTION_TERMINATION, TriggerType.REGISTER_OWN_USER }; private static TriggerType[] allowedTriggersForCustomer = { TriggerType.ADD_REVOKE_USER, TriggerType.MODIFY_SUBSCRIPTION, TriggerType.SUBSCRIBE_TO_SERVICE, TriggerType.UNSUBSCRIBE_FROM_SERVICE, TriggerType.UPGRADE_SUBSCRIPTION, TriggerType.START_BILLING_RUN, TriggerType.REGISTER_OWN_USER }; @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) @TransactionAttribute(TransactionAttributeType.MANDATORY) public void deleteTriggerDefinitionInt(long triggerDefinitionKey) throws ObjectNotFoundException, DeletionConstraintException, OperationNotPermittedException { TriggerDefinition triggerDefinition = dm.getReference( TriggerDefinition.class, triggerDefinitionKey); checkOrgAuthority(triggerDefinition); // check if there are trigger processes exist for current trigger // definition. // excepts the triggerDefinition can not be deleted Query query = dm .createNamedQuery("TriggerProcess.getAllForTriggerDefinition"); query.setParameter("triggerDefinitionKey", Long.valueOf(triggerDefinitionKey)); List<TriggerProcess> triggerProcessList = ParameterizedTypes.list( query.getResultList(), TriggerProcess.class); if (triggerProcessList.size() > 0) { DeletionConstraintException sdce = new DeletionConstraintException( ClassEnum.TRIGGER_DEFINITION, String.valueOf(triggerDefinitionKey), ClassEnum.TRIGGER_PROCESS); logger.logWarn(Log4jLogger.SYSTEM_LOG, sdce, LogMessageIdentifier.WARN_TRIGGER_DELETION_FAILED); throw sdce; } dm.remove(triggerDefinition); } private void checkOrgAuthority(TriggerDefinition triggerDefinition) throws OperationNotPermittedException { if (getOwnOrganization().getKey() != triggerDefinition .getOrganization().getKey()) { OperationNotPermittedException ex = new OperationNotPermittedException( "The client has no authority for the operation."); logger.logInfo(Log4jLogger.SYSTEM_LOG, LogMessageIdentifier.ERROR_NO_AUTHORITY_TO_APPROVE, ex.getMessage()); throw ex; } } @Override @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) public Long createTriggerDefinition(VOTriggerDefinition trigger) throws TriggerDefinitionDataException, ValidationException { ArgumentValidator.notNull("trigger", trigger); VOTriggerDefinition vo = trigger; Organization organization = getOwnOrganization(); // check if trigger type is allowed for that organization if (!isAllowedTriggertype(vo.getType())) { throw new ValidationException(ReasonEnum.TRIGGER_TYPE_NOT_ALLOWED, vo.getType().name(), null); } if (vo.isSuspendProcess() && organization.getSuspendingTriggerDefinition(vo.getType()) != null) { TriggerDefinitionDataException e = new TriggerDefinitionDataException( "A suspending trigger definition does already exists for the type '" + vo.getType() + "'"); logger.logError( Log4jLogger.SYSTEM_LOG, e, LogMessageIdentifier.ERROR_SUSPENDING_TRIGGER_ALREADY_EXISTS_FOR_TYPE, String.valueOf(vo.getType())); throw e; } try { // default name if (vo.getName() == null) { vo.setName(vo.getType().name()); } TriggerDefinition triggerDefinition = TriggerDefinitionAssembler .toTriggerDefinition(vo); triggerDefinition.setOrganization(organization); dm.persist(triggerDefinition); dm.flush(); return new Long(triggerDefinition.getKey()); } catch (NonUniqueBusinessKeyException e) { // should not happen as the saved object doesn't have a business // key SaaSSystemException se = new SaaSSystemException( "TriggerDefinition has no business key.", e); logger.logError( Log4jLogger.SYSTEM_LOG, se, LogMessageIdentifier.ERROR_TRIGGER_DEFINITION_HAS_NO_BUSINESS_KEY); throw se; } } @Override @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) public void deleteTriggerDefinition(long triggerKey) throws ObjectNotFoundException, DeletionConstraintException, OperationNotPermittedException { this.deleteTriggerDefinitionInt(triggerKey); } @Override @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) public void deleteTriggerDefinition(VOTriggerDefinition vo) throws ObjectNotFoundException, DeletionConstraintException, OperationNotPermittedException, ConcurrentModificationException { ArgumentValidator.notNull("trigger", vo); TriggerDefinition triggerDefinition = dm.getReference( TriggerDefinition.class, vo.getKey()); TriggerDefinitionAssembler.verifyVersionAndKey(triggerDefinition, vo); this.deleteTriggerDefinitionInt(triggerDefinition.getKey()); } @Override @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) public void updateTriggerDefinition(VOTriggerDefinition vo) throws ObjectNotFoundException, ValidationException, ConcurrentModificationException, TriggerDefinitionDataException, OperationNotPermittedException { ArgumentValidator.notNull("trigger", vo); TriggerDefinition triggerDefinition = dm.getReference( TriggerDefinition.class, vo.getKey()); checkOrgAuthority(triggerDefinition); // check if triggertype is allowed for that organization if (!isAllowedTriggertype(vo.getType())) { throw new ValidationException(); } if (vo.isSuspendProcess()) { Organization organization = triggerDefinition.getOrganization(); TriggerDefinition existingTriggerDefinition = organization .getSuspendingTriggerDefinition(vo.getType()); if (existingTriggerDefinition != null && vo.getKey() != existingTriggerDefinition.getKey()) { TriggerDefinitionDataException e = new TriggerDefinitionDataException( "A suspending trigger definition does already exists for the type '" + vo.getType() + "'"); logger.logError( Log4jLogger.SYSTEM_LOG, e, LogMessageIdentifier.ERROR_SUSPENDING_TRIGGER_ALREADY_EXISTS_FOR_TYPE, String.valueOf(vo.getType())); throw e; } } checkTriggerDefinitionChangeAllowed(vo, triggerDefinition); TriggerDefinitionAssembler.updateTriggerDefinition(triggerDefinition, vo); } @Override @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) public List<VOTriggerDefinition> getTriggerDefinitions() { return getTriggerDefinitionsForOrganizationInt(getOwnOrganization() .getOrganizationId()); } @Override @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) public VOTriggerDefinition getTriggerDefinition(Long id) throws ObjectNotFoundException, OperationNotPermittedException { if (id == null) { throw new ObjectNotFoundException("no key with value null"); } TriggerDefinition definition = dm.getReference(TriggerDefinition.class, id.longValue()); checkOrgAuthority(definition); return TriggerDefinitionAssembler.toVOTriggerDefinition(definition); } private Organization getOwnOrganization() { Organization orgOfCurrentUser = dm.getCurrentUser().getOrganization(); return orgOfCurrentUser; } // check if triggertype is in allowed types of triggertypes for // organization private boolean isAllowedTriggertype(TriggerType triggerType) { Organization org = dm.getCurrentUser().getOrganization(); Set<OrganizationRoleType> roles = org.getGrantedRoleTypes(); for (OrganizationRoleType role : roles) { Set<TriggerType> allowedRoles = getTriggerTypesForRole(role); if (allowedRoles.contains(triggerType)) { return true; } } return false; } private List<VOTriggerDefinition> getTriggerDefinitionsForOrganizationInt( String organizationId) { Organization organization; try { organization = getOrganizationInt(organizationId); } catch (ObjectNotFoundException e) { SaaSSystemException saasEx = new SaaSSystemException( "An organization must exist"); throw saasEx; } List<VOTriggerDefinition> result = new ArrayList<VOTriggerDefinition>(); for (TriggerDefinition triggerDefinition : organization .getTriggerDefinitions()) { result.add(TriggerDefinitionAssembler.toVOTriggerDefinition( triggerDefinition, hasTriggerProcess(triggerDefinition.getKey()))); } return result; } private boolean hasTriggerProcess(long triggerDefinitionKey) { Query query = dm .createNamedQuery("TriggerProcess.getAllForTriggerDefinition"); query.setParameter("triggerDefinitionKey", Long.valueOf(triggerDefinitionKey)); List<TriggerProcess> triggerProcesses = ParameterizedTypes.list( query.getResultList(), TriggerProcess.class); return !triggerProcesses.isEmpty(); } private Organization getOrganizationInt(String organizationId) throws ObjectNotFoundException { Organization organization = new Organization(); organization.setOrganizationId(organizationId); organization = (Organization) dm .getReferenceByBusinessKey(organization); return organization; } @Override @RolesAllowed({ "ORGANIZATION_ADMIN", "PLATFORM_OPERATOR" }) public List<TriggerType> getTriggerTypes() { Organization org = this.getOwnOrganization(); Set<OrganizationRoleType> orgRoles = org.getGrantedRoleTypes(); Set<TriggerType> triggerTypesSet = new HashSet<TriggerType>(); if (orgRoles != null) { for (OrganizationRoleType orgRole : orgRoles) { triggerTypesSet.addAll(getTriggerTypesForRole(orgRole)); } } List<TriggerType> triggerTypesList = new ArrayList<TriggerType>(); triggerTypesList.addAll(triggerTypesSet); return triggerTypesList; } private Set<TriggerType> getTriggerTypesForRole(OrganizationRoleType role) { Set<TriggerType> triggerTypes = new HashSet<TriggerType>(); switch (role) { case SUPPLIER: triggerTypes.addAll(Arrays.asList(allowedTriggersForSupplier)); break; case CUSTOMER: triggerTypes.addAll(Arrays.asList(allowedTriggersForCustomer)); break; default: triggerTypes = Collections.emptySet(); } return triggerTypes; } private void checkTriggerDefinitionChangeAllowed(VOTriggerDefinition vo, TriggerDefinition triggerDefinition) throws OperationNotPermittedException { if (!TriggerDefinitionAssembler .isOnlyNameChanged(vo, triggerDefinition) && hasTriggerProcess(triggerDefinition.getKey())) { OperationNotPermittedException ex = new OperationNotPermittedException( "There are already trigger processes based on this trigger definition."); logger.logError(Log4jLogger.SYSTEM_LOG, ex, LogMessageIdentifier.WARN_TRIGGER_MODIFICATION_FAILED); throw ex; } } }
41.429668
94
0.657757
59fa2935243e871baa358fd0ee616f4c23cab22f
1,631
package unl.cse.lists; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class EqualsDemo { public static void main(String args[]) { ArrayList<UserClassA> listA = new ArrayList<UserClassA>(); ArrayList<UserClassB> listB = new ArrayList<UserClassB>(); UserClassA a = new UserClassA(10, 20.0); UserClassA b = new UserClassA(30, 50.0); UserClassA c = new UserClassA(10, 20.0); listA.add(a); listA.add(b); System.out.println("listA = "+listA); System.out.println("listA.contains(c) ? "+listA.contains(c)); UserClassB d = new UserClassB(10, 20.0); UserClassB e = new UserClassB(30, 50.0); UserClassB f = new UserClassB(10, 20.0); listB.add(d); listB.add(e); System.out.println("listB = "+listB); System.out.println("listB.contains(f) ? "+listB.contains(f)); //Demonstration that mutable objects should be handled //with care when used in the Collections framework... /* * A set usually only has *UNIQUE* elements (unique with respect to the * equals and hashcode methods)... */ Set<UserClassB> theSet = new HashSet<UserClassB>(); theSet.add(d); theSet.add(e); //adding d, e is fine System.out.println(theSet); //adding f has no effect since it is equal to d, but... theSet.add(f); System.out.println(theSet); //adding f mutated does have an effect: f.setInteger(15); theSet.add(f); System.out.println(theSet); //but now we can change it back forcing the Set to have //duplicate elements: f.setInteger(10); System.out.println(theSet); } }
27.183333
74
0.656652
e4e07dcb16b9fa42c74d3b09367a1738164b46d2
391
package com.app.phedev.popmovie.sync; import android.app.IntentService; import android.content.Intent; /** * Created by phedev in 2017. */ public class MovieIntentService extends IntentService { public MovieIntentService(){ super("MovieIntentService"); } @Override protected void onHandleIntent(Intent intent) { MovieSyncTask.syncMovie(this); } }
17.772727
55
0.705882
97fdd5e7f156a6f3926ded483b266f4d207b74ce
722
package net.osomahe.pulsarsourceapp.zip.boundary; import net.osomahe.pulsarsourceapp.message.boundary.MessageService; import net.osomahe.pulsarsourceapp.zip.control.ZipService; import net.osomahe.pulsarsourceapp.zip.entity.ZipInfo; import javax.inject.Inject; import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path(("/zip-messages")) public class ZipResource { @Inject ZipService service; @POST @Consumes(MediaType.APPLICATION_JSON) public Response writeZipData(@Valid ZipInfo info) { service.writeZipData(info); return Response.ok().build(); } }
25.785714
67
0.760388
5ee378cfa4b29e2f84c3a60ae1c6d9ff660aa2cc
1,037
package org.wyw.lanplay.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import io.swagger.annotations.ApiModel; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; /** * <p> * 邀请码 * </p> * * @author wuYd * @since 2020-03-24 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("invitation_code") @ApiModel(value="邀请码", description="") public class InvitationCodeEntity extends Model<InvitationCodeEntity> { private static final long serialVersionUID=1L; @TableId(value = "id", type = IdType.AUTO) private Long id; @TableField("code") private String code; @Override protected Serializable pkVal() { return this.id; } }
23.044444
71
0.75217
661c72f3f7bdd54c5e3a613aaf96a47a4a0571f1
1,974
package com.eilikce.osm.shop.controller; import java.util.List; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.eilikce.osm.core.bo.common.Cart; import com.eilikce.osm.core.bo.common.CommodityGroupItem; import com.eilikce.osm.core.bo.common.Consumer; import com.eilikce.osm.shop.service.IndexService; @Controller @RequestMapping("/index") public class IndexController { private static final Logger LOG = LoggerFactory.getLogger(IndexController.class); @Autowired private IndexService service; @RequestMapping("/welcome.do") public ModelAndView welcome(){ ModelAndView modelAndView = new ModelAndView("consumer/welcome"); return modelAndView; } /** * 进入超市按钮 * 要求设置用户session信息 */ @RequestMapping(value = "/enterOsm.do", params = { "addr", "name", "phone" }) @ResponseBody public void enterOsm(@RequestParam("addr") String addr, @RequestParam("name") String name, @RequestParam("phone") String phone, HttpSession session) { //用户信息放入session Consumer consumer = new Consumer(addr, name, phone); Cart cart = new Cart(consumer); session.setAttribute("consumer", consumer); session.setAttribute("cart", cart); LOG.info("新建用户:"+consumer.getInfo().getName()+",联系电话:"+consumer.getInfo().getPhone()); } @RequestMapping(value = "/group.do") public ModelAndView group() { List<CommodityGroupItem> groupItemList = service.getAllCommodityGroupAndItem(); ModelAndView modelAndView = new ModelAndView("consumer/group"); modelAndView.addObject("groupItemList",groupItemList); return modelAndView; } }
29.029412
91
0.765957
838bd182b0ade93c20c08be189051b5e9d902c18
2,679
package org.bouncycastle.gpg.keybox; import java.security.Security; import java.util.Arrays; import junit.framework.TestCase; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.test.SimpleTest; public class KeyBoxByteBufferTest extends SimpleTest { public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new KeyBoxByteBufferTest()); } public void testReadPastEnd() throws Exception { byte[] expected = new byte[]{1, 2, 3}; KeyBoxByteBuffer buf = KeyBoxByteBuffer.wrap(expected); try { buf.bN(4); fail("Would be past end."); } catch (IllegalArgumentException ilex) { } try { buf.bN(-1); TestCase.fail("Would be past end."); } catch (IllegalArgumentException ilex) { } isEquals(0, buf.bN(0).length); byte[] b = buf.bN(3); isEquals("Length", b.length, 3); isTrue("Wrong values", Arrays.equals(b, expected)); } public void testRangeReadPastEnd() throws Exception { byte[] expected = new byte[]{1, 2, 3, 4, 5}; KeyBoxByteBuffer buf = KeyBoxByteBuffer.wrap(expected); try { buf.rangeOf(3, 6); fail("Would be past end."); } catch (IllegalArgumentException ilex) { } try { buf.rangeOf(1, -3); fail("End is negative"); } catch (IllegalArgumentException ilex) { } try { buf.rangeOf(4, 3); fail("End is less than start"); } catch (IllegalArgumentException ilex) { } isEquals(0, buf.rangeOf(1, 1).length); byte[] b = buf.rangeOf(1, 3); isEquals("wrong length", 2, b.length); isTrue("Wrong values", Arrays.equals(b, new byte[]{2, 3})); } public void testConsumeReadPastEnd() throws Exception { KeyBoxByteBuffer buf = KeyBoxByteBuffer.wrap(new byte[4]); buf.consume(3); try { buf.consume(2); TestCase.fail("consume past end of buffer"); } catch (IllegalArgumentException ilex) { } } @Override public String getName() { return "KeyBoxBuffer"; } @Override public void performTest() throws Exception { testConsumeReadPastEnd(); testRangeReadPastEnd(); testReadPastEnd(); } }
21.094488
67
0.535274
cce346379ea760e6b670bb04381b2ce41d748bce
1,145
/* * Copyright 2010 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package de.hdawg.wci.portlets.bookmarks.client.ui; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.Image; /** * Extends standard GWT-hyperlink for using images as link text * * @author Hauke Wesselmann */ public class Hyperlink extends com.google.gwt.user.client.ui.Hyperlink { public Hyperlink() { } public void setResource(ImageResource imageResource) { Image img = new Image(imageResource); DOM.appendChild(DOM.getFirstChild(getElement()), img.getElement()); } }
30.131579
80
0.750218
263c5d9ce949410206c400982d2b0f55aefbcc6e
2,134
package G45502.Pentago.view; /** * Cette classe permet l'écriture d'un texte coloré 4/11/2104 - Ajout d'un main * - MCD */ public class Color { /** * Méthode de couleur default du BASH. * * @return La couleur default. */ private static String toDefault() { return "\033[0m"; } /** * Colorie une chaine en noir. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toBlack(String a) { return "\033[30m" + a + toDefault(); } /** * Colorie une chaine en rouge. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toRed(String a) { return "\033[31m" + a + toDefault(); } /** * Colorie une chaine en vert. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toGreen(String a) { return "\033[32m" + a + toDefault(); } /** * Colorie une chaine en jaune. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toYellow(String a) { return "\033[33m" + a + toDefault(); } /** * Colorie une chaine en bleu. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toBlue(String a) { return "\033[34m" + a + toDefault(); } /** * Colorie une chaine en mauve. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toPurple(String a) { return "\033[35m" + a + toDefault(); } /** * Colorie une chaine en cyan. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toCyan(String a) { return "\033[36m" + a + toDefault(); } /** * Colorie une chaine en blanc. * * @param a La chaine à colorer. * @return La chaine colorée. */ public static String toWhite(String a) { return "\033[37m" + a + toDefault(); } }
21.77551
79
0.53702
4ce7a5b16ec099c79240679748e99b9b7c0b6bd4
709
package io.github.rbxapi.javablox.api.accountsettings.tradesettings; /** * https://accountsettings.roblox.com/docs#/TradeSettings */ public interface TradeValue { /** * Get a user's trade quality filter setting * https://accountsettings.roblox.com/docs#!/TradeSettings/get_v1_trade_value * * @return { * "tradeValue": "string" * } */ String getTradeValue(); /** * Updates a user's trade quality filter setting * https://accountsettings.roblox.com/docs#!/TradeSettings/post_v1_trade_value * * @param model { * "tradeValue": "None" * } * @return {} */ String setTradeValue(String model); }
25.321429
82
0.610719
b95ef679bc5ddad719a72e09ac565807b3254377
486
package com.cldt.provider; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class CldtUacApplicationTests { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @Test public void contextLoads() { } }
24.3
75
0.777778
10735d88fa981d5501c8c9c414fa54449218b63f
220
package com.github.gpor0.jooreo; import org.jooq.DSLContext; import org.jooq.TableRecord; /** * Author: gpor0 */ public interface JooreoInsertFilter { <T extends TableRecord> int filter(DSLContext dsl, T r); }
15.714286
60
0.731818
b50c995509af97c65180c43b5dad8212e81e8702
3,547
package com.analytics.google.pjcyber.googleanalyticsmanyevents; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static String TAG = MainActivity.class.getSimpleName(); private Button btnSecondScreen, btnSendEvent, btnException, btnAppCrash; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSecondScreen = (Button) findViewById(R.id.btnSecondScreen); btnSendEvent = (Button) findViewById(R.id.btnSendEvent); btnException = (Button) findViewById(R.id.btnException); btnAppCrash = (Button) findViewById(R.id.btnAppCrash); /** * Launching another activity to track the other screen */ btnSecondScreen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); /** * Event tracking * Event(Category, Action, Label) */ btnSendEvent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Tracking Event MyApplication.getInstance().trackEvent("Cellphones", "buy", "Send event example"); Toast.makeText(getApplicationContext(), "Event \'Book\' \'buy\' \'Event example\' is sent. Check it on Google Analytics Dashboard!", Toast.LENGTH_LONG).show(); } }); /** * Tracking Exception Manually * All known exceptions can be tracking this way * using Try & Catch */ btnException.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { String name = null; if (name.equals("Homer Simpson")) { /* Never comes here as it throws null pointer exception */ } } catch (Exception e) { // Tracking exception MyApplication.getInstance().trackException(e); Toast.makeText(getApplicationContext(), getString(R.string.toast_track_exception), Toast.LENGTH_LONG).show(); Log.e(TAG, "Exception: " + e.getMessage()); } } }); /** * Tracking App Crashes * Manually generation app crash by dividing with zero */ btnAppCrash.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), getString(R.string.toast_app_crash), Toast.LENGTH_LONG).show(); Runnable r = new Runnable() { @Override public void run() { int answer = 12 / 0; } }; Handler h = new Handler(); h.postDelayed(r, 1500); } }); } }
33.462264
175
0.563575
3393e0dc909c06bc3e3f8929efbf7fe45df72104
2,484
package be.sel2.api.controller_tests; import be.sel2.api.AbstractTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class FileTests extends AbstractTest { @Override @BeforeEach protected void setUp() { super.setUp(); } @Test void emptyFileUpload() throws Exception { MockMultipartFile file = new MockMultipartFile("file", "hello.txt", "text/plain",new byte[]{}); String uri = "/files"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.multipart(uri).file(file)).andReturn(); assertEquals(400, mvcResult.getResponse().getStatus()); assertTrue(mvcResult.getResponse().getContentAsString().contains("Upload was empty")); } @Test void failUpload() throws Exception { MockMultipartFile file = new MockMultipartFile("file", "hello.txt", "text/plain", "test".getBytes()); String uri = "/files"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.multipart(uri).file(file)).andReturn(); assertEquals(400, mvcResult.getResponse().getStatus()); assertTrue(mvcResult.getResponse().getContentAsString().contains("Was unable to save file")); } @Test void getFile() throws Exception { String uri = "/files/1"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); assertEquals(200, mvcResult.getResponse().getStatus()); String response = mvcResult.getResponse().getContentAsString(); assertTrue(response.contains("/uploads/permissionFile")); } @Test void failGetFile() throws Exception { String uri = "/files/99999"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); assertEquals(404, mvcResult.getResponse().getStatus()); String response = mvcResult.getResponse().getContentAsString(); assertTrue(response.contains("Could not find file with ID 99999"), "Recieved: " + response); } }
36.529412
109
0.702093
5e6b17248b2c339be7a0f823b03d9ff4520f4ddd
2,742
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.impl.document; import java.util.Map; import org.eclipse.birt.data.engine.api.DataEngineContext; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.impl.document.stream.StreamManager; import org.eclipse.birt.data.engine.odi.IResultIterator; /** * Used to save the query which is running based on a report document and the * result is based on the result set of report document instead of data set. For * the latter case, RDSave class will be used. */ class RDSave2 implements IRDSave { private DataEngineContext context; private StreamManager streamManager; private RDSaveUtil saveUtilHelper; /** * @param context * @param queryDefn * @param queryResultID * @param rowCount * @param subQueryName * @param subQueryIndex * @throws DataException */ RDSave2( DataEngineContext context, IBaseQueryDefinition queryDefn, QueryResultInfo queryResultInfo ) throws DataException { this.context = context; this.streamManager = new StreamManager( context, queryResultInfo ); this.saveUtilHelper = new RDSaveUtil( this.context, queryDefn, this.streamManager ); } /* * @see org.eclipse.birt.data.engine.impl.document.RDSave#saveExprValue(int, * java.util.Map) */ public void saveExprValue( int currIndex, Map valueMap ) throws DataException { // do nothing } /* * @see org.eclipse.birt.data.engine.impl.document.RDSave#saveFinish(int) */ public void saveFinish( int currIndex ) throws DataException { this.saveUtilHelper.saveChildQueryID( ); } /* * @see org.eclipse.birt.data.engine.impl.document.IRDSave#saveResultIterator(org.eclipse.birt.data.engine.odi.IResultIterator, * int, int[]) */ public void saveResultIterator( IResultIterator odiResult, int groupLevel, int[] subQueryInfo ) throws DataException { saveUtilHelper.saveResultIterator( odiResult, groupLevel, subQueryInfo ); } /* * (non-Javadoc) * @see org.eclipse.birt.data.engine.impl.document.IRDSave#saveStart() */ public void saveStart( ) throws DataException { this.saveUtilHelper.saveQueryDefn( ); } }
30.131868
128
0.706783
cb62a6ea8247894fac49a3c519cd4dbb2a31c857
2,915
package com.company.crm.service; import com.company.crm.CrmService; import com.company.crm.model.Customer; import com.company.crm.model.CustomerDTO; import com.company.crm.service.impl.CustomerServiceImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.modelmapper.ModelMapper; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; @RunWith(MockitoJUnitRunner.class) public class CustomerServiceImplTest { @InjectMocks private CustomerServiceImpl customerService; @Mock private CrmService crmService; @Mock private ModelMapper modelMapper; @Test public void testUpdateCustomer() { doNothing().when(crmService).updateCustomer(any(Customer.class)); customerService.updateCustomer(new CustomerDTO()); verify(crmService, times(1)).updateCustomer(any(Customer.class)); } @Test public void testDeleteCustomer() { doNothing().when(crmService).deleteCustomerById(anyLong()); customerService.deleteCustomerById(1L); verify(crmService, times(1)).deleteCustomerById(anyLong()); } @Test public void testGetCustomer() { when(crmService.getCustomerById(anyLong())).thenReturn(getCustomer()); when(modelMapper.map(any(), any())).thenReturn(getCustomerDTOFromCustomerEntity()); CustomerDTO customerDTO = customerService.getCustomerById(1L); assertNotNull(customerDTO); assertEquals(Long.parseLong("1"), Long.parseLong(customerDTO.getId().toString())); } @Test public void testAllGetCustomers() { when(crmService.getAllCustomers()).thenReturn(Arrays.asList(getCustomer())); when(modelMapper.map(any(), any())).thenReturn(getCustomerDTOFromCustomerEntity()); List<CustomerDTO> customerDTOS = customerService.getAllCustomers(); assertNotNull(customerDTOS); assertEquals(1, customerDTOS.size()); } private Customer getCustomer() { Customer customer = new Customer(); customer.setId(1L); customer.setFirstName("first"); customer.setLastName("last"); customer.setDateOfBirth(new Date()); return customer; } private CustomerDTO getCustomerDTOFromCustomerEntity() { ModelMapper modelMapper = new ModelMapper(); CustomerDTO customerDTO = modelMapper.map(getCustomer(), CustomerDTO.class); return customerDTO; } }
32.388889
91
0.729674
c1f68709754f2543f0d5645e25c2b2b8fc3a0818
1,423
package com.interview.codechef.ccdsap_2.leetcode.design; import java.util.Stack; public class QueueUsingStacks { //https://leetcode.com/problems/implement-queue-using-stacks/ Stack<Integer> stack; public QueueUsingStacks() { stack = new Stack<>(); } //Below solution works fine, one more option using two stacks: //https://leetcode.com/problems/implement-queue-using-stacks/discuss/64206/Short-O(1)-amortized-C%2B%2B-Java-Ruby public static void main( String[] args ) { QueueUsingStacks queueUsingStacks = new QueueUsingStacks(); queueUsingStacks.push(1); queueUsingStacks.push(2); queueUsingStacks.push(3); System.out.println(queueUsingStacks.pop()); } /** * Push element x to the back of queue. */ public void push( int x ) { stack.push(x); } /** * Removes the element from in front of queue and returns that element. */ public int pop() { if (!stack.isEmpty()) { int num = stack.get(0); stack.remove(0); return num; } return -1; } /** * Get the front element. */ public int peek() { if (!stack.isEmpty()) return stack.get(0); return -1; } /** * Returns whether the queue is empty. */ public boolean empty() { return stack.isEmpty(); } }
23.327869
117
0.581167
038340425577c5695ac52a9c3654267106526bea
2,346
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.common.tracer.core.constants; /** * Component Name Constants * @author: guolei.sgl ([email protected]) 2019/4/8 9:16 PM * @since: **/ public class ComponentNameConstants { public static final String DATA_SOURCE = "dataSource"; public static final String DUBBO_CLIENT = "dubbo-client"; public static final String DUBBO_SERVER = "dubbo-server"; public static final String HTTP_CLIENT = "httpclient"; public static final String OK_HTTP = "okhttp"; public static final String REST_TEMPLATE = "resttemplate"; public static final String SPRING_MVC = "springmvc"; public static final String FLEXIBLE = "flexible-biz"; public static final String FEIGN_CLIENT = "open-feign"; public static final String MSG_PUB = "message-pub"; public static final String MSG_SUB = "message-sub"; public static final String KAFKAMQ_CONSUMER = "kafkamq-consume"; public static final String KAFKAMQ_SEND = "kafkamq-send"; public static final String ROCKETMQ_CONSUMER = "rocketmq-consume"; public static final String ROCKETMQ_SEND = "rocketmq-send"; public static final String RABBITMQ_CONSUMER = "rabbitmq-consume"; public static final String RABBITMQ_SEND = "rabbitmq-send"; public static final String MONGO_CLIENT = "mongo-client"; public static final String REDIS = "redis"; public static final String TAIR = "tair"; }
35.014925
75
0.698636
94a2acb6695f85653e5b686c786ad3cb0d773447
16,321
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|com.google.common.base package|package name|com operator|. name|google operator|. name|common operator|. name|base package|; end_package begin_import import|import static name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit operator|. name|MICROSECONDS import|; end_import begin_import import|import static name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit operator|. name|MILLISECONDS import|; end_import begin_import import|import static name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit operator|. name|NANOSECONDS import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|annotations operator|. name|GwtCompatible import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|testing operator|. name|FakeTicker import|; end_import begin_import import|import name|junit operator|. name|framework operator|. name|TestCase import|; end_import begin_comment comment|/** * Unit test for {@link Stopwatch}. * * @author Kevin Bourrillion */ end_comment begin_class annotation|@ name|GwtCompatible DECL|class|StopwatchTest specifier|public class|class name|StopwatchTest extends|extends name|TestCase block|{ DECL|field|ticker specifier|private specifier|final name|FakeTicker name|ticker init|= operator|new name|FakeTicker argument_list|() decl_stmt|; DECL|field|stopwatch specifier|private specifier|final name|Stopwatch name|stopwatch init|= operator|new name|Stopwatch argument_list|( name|ticker argument_list|) decl_stmt|; DECL|method|testCreateStarted () specifier|public name|void name|testCreateStarted parameter_list|() block|{ name|Stopwatch name|startedStopwatch init|= name|Stopwatch operator|. name|createStarted argument_list|() decl_stmt|; name|assertTrue argument_list|( name|startedStopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testCreateUnstarted () specifier|public name|void name|testCreateUnstarted parameter_list|() block|{ name|Stopwatch name|unstartedStopwatch init|= name|Stopwatch operator|. name|createUnstarted argument_list|() decl_stmt|; name|assertFalse argument_list|( name|unstartedStopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|unstartedStopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testInitialState () specifier|public name|void name|testInitialState parameter_list|() block|{ name|assertFalse argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testStart () specifier|public name|void name|testStart parameter_list|() block|{ name|assertSame argument_list|( name|stopwatch argument_list|, name|stopwatch operator|. name|start argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testStart_whileRunning () specifier|public name|void name|testStart_whileRunning parameter_list|() block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; try|try block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|fail argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IllegalStateException name|expected parameter_list|) block|{ } name|assertTrue argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testStop () specifier|public name|void name|testStop parameter_list|() block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|assertSame argument_list|( name|stopwatch argument_list|, name|stopwatch operator|. name|stop argument_list|() argument_list|) expr_stmt|; name|assertFalse argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testStop_new () specifier|public name|void name|testStop_new parameter_list|() block|{ try|try block|{ name|stopwatch operator|. name|stop argument_list|() expr_stmt|; name|fail argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IllegalStateException name|expected parameter_list|) block|{ } name|assertFalse argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testStop_alreadyStopped () specifier|public name|void name|testStop_alreadyStopped parameter_list|() block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|stopwatch operator|. name|stop argument_list|() expr_stmt|; try|try block|{ name|stopwatch operator|. name|stop argument_list|() expr_stmt|; name|fail argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IllegalStateException name|expected parameter_list|) block|{ } name|assertFalse argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testReset_new () specifier|public name|void name|testReset_new parameter_list|() block|{ name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|stopwatch operator|. name|reset argument_list|() expr_stmt|; name|assertFalse argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|2 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|3 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|3 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testReset_whileRunning () specifier|public name|void name|testReset_whileRunning parameter_list|() block|{ name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|2 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|2 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; name|stopwatch operator|. name|reset argument_list|() expr_stmt|; name|assertFalse argument_list|( name|stopwatch operator|. name|isRunning argument_list|() argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|3 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testElapsed_whileRunning () specifier|public name|void name|testElapsed_whileRunning parameter_list|() block|{ name|ticker operator|. name|advance argument_list|( literal|78 argument_list|) expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|345 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|345 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testElapsed_notRunning () specifier|public name|void name|testElapsed_notRunning parameter_list|() block|{ name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|4 argument_list|) expr_stmt|; name|stopwatch operator|. name|stop argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|9 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|4 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testElapsed_multipleSegments () specifier|public name|void name|testElapsed_multipleSegments parameter_list|() block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|9 argument_list|) expr_stmt|; name|stopwatch operator|. name|stop argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|16 argument_list|) expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|assertEquals argument_list|( literal|9 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|25 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|34 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; name|stopwatch operator|. name|stop argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|36 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|34 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|NANOSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testElapsed_micros () specifier|public name|void name|testElapsed_micros parameter_list|() block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|999 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|MICROSECONDS argument_list|) argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|MICROSECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testElapsed_millis () specifier|public name|void name|testElapsed_millis parameter_list|() block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|999999 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|MILLISECONDS argument_list|) argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|stopwatch operator|. name|elapsed argument_list|( name|MILLISECONDS argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testToString () specifier|public name|void name|testToString parameter_list|() block|{ name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|assertEquals argument_list|( literal|"0.000 ns" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"1.000 ns" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|998 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"999.0 ns" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"1.000 \u03bcs" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|1 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"1.001 \u03bcs" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|8998 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"9.999 \u03bcs" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|stopwatch operator|. name|reset argument_list|() expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|1234567 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"1.235 ms" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|stopwatch operator|. name|reset argument_list|() expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( literal|5000000000L argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"5.000 s" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|stopwatch operator|. name|reset argument_list|() expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( call|( name|long call|) argument_list|( literal|1.5 operator|* literal|60 operator|* literal|1000000000L argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"1.500 min" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|stopwatch operator|. name|reset argument_list|() expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( call|( name|long call|) argument_list|( literal|2.5 operator|* literal|60 operator|* literal|60 operator|* literal|1000000000L argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"2.500 h" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|stopwatch operator|. name|reset argument_list|() expr_stmt|; name|stopwatch operator|. name|start argument_list|() expr_stmt|; name|ticker operator|. name|advance argument_list|( call|( name|long call|) argument_list|( literal|7.25 operator|* literal|24 operator|* literal|60 operator|* literal|60 operator|* literal|1000000000L argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"7.250 d" argument_list|, name|stopwatch operator|. name|toString argument_list|() argument_list|) expr_stmt|; block|} block|} end_class end_unit
14.716862
608
0.804424
c8b6b5648653d61585aeed002d54de030a061062
139
/** * A mini application/framework to dynamically generate/update files based on a list of endpoints */ package net.dean.jraw.endpoints;
27.8
97
0.769784
bd1ffec0c215c7a272d90c0f1b1c837a2df4d211
493
package cn.com.bugmanager.develop.model; /** * Created by threegrand2 on 15-6-18. */ public class RolePermission { private String roleName; private String permToken; public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getPermToken() { return permToken; } public void setPermToken(String permToken) { this.permToken = permToken; } }
18.961538
48
0.647059
696058ddc5224bc17231ae0a6ef52e84258f8443
2,884
/** * 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.pulsar.tests; import java.util.Arrays; import java.util.Collections; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.util.RetryAnalyzerCount; public class RetryAnalyzer extends RetryAnalyzerCount { // Only try again once static final int MAX_RETRIES = Integer.parseInt(System.getProperty("testRetryCount", "1")); // Don't retry test classes that are changed in the current changeset in CI private static final Pattern TEST_FILE_PATTERN = Pattern.compile("^.*src/test/java/(.*)\\.java$"); private static final Set<String> CHANGED_TEST_CLASSES = Optional.ofNullable(System.getenv("CHANGED_TESTS")) .map(changedTestsCsv -> Collections.unmodifiableSet(Arrays.stream(StringUtils.split(changedTestsCsv)) .map(path -> { Matcher matcher = TEST_FILE_PATTERN.matcher(path); if (matcher.matches()) { return matcher.group(1) .replace('/', '.'); } else { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toSet()))) .orElse(Collections.emptySet()); public RetryAnalyzer() { setCount(MAX_RETRIES); } @Override public boolean retry(ITestResult result) { if (CHANGED_TEST_CLASSES.contains((result.getTestClass().getName()))) { return false; } return super.retry(result); } @Override public boolean retryMethod(ITestResult result) { return !(result.getThrowable() instanceof SkipException); } }
39.506849
111
0.634882
b0dbb26aa12e2b283827c9a0d81a180decc95abc
4,787
/* * 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.beam.runners.dataflow.worker.util; import static com.google.common.base.Preconditions.checkArgument; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.service.AutoService; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.beam.runners.dataflow.util.CloudObject; import org.apache.beam.runners.dataflow.util.CloudObjectTranslator; import org.apache.beam.runners.dataflow.util.CloudObjects; import org.apache.beam.runners.dataflow.util.CoderCloudObjectTranslatorRegistrar; import org.apache.beam.runners.dataflow.util.PropertyNames; import org.apache.beam.runners.dataflow.util.Structs; import org.apache.beam.runners.dataflow.worker.WindmillKeyedWorkItem.FakeKeyedWorkItemCoder; import org.apache.beam.sdk.coders.Coder; /** * Empty class which exists because the back end will sometimes insert uses of {@code * com.google.cloud.dataflow.sdk.util.TimerOrElement$TimerOrElementCoder} and we'd like to be able * to rename/move that without breaking things. */ public class TimerOrElement { // TimerOrElement should never be created. private TimerOrElement() {} /** * Empty class which exists because the back end will sometimes insert uses of {@code * com.google.cloud.dataflow.dataflow.sdk.util.TimerOrElement$TimerOrElementCoder} and we'd like * to be able to rename/move that without breaking things. */ public static class TimerOrElementCoder<ElemT> extends FakeKeyedWorkItemCoder<Object, ElemT> { private TimerOrElementCoder(Coder<ElemT> elemCoder) { super(elemCoder); } public static <T> TimerOrElementCoder<T> of(Coder<T> elemCoder) { return new TimerOrElementCoder<>(elemCoder); } @JsonCreator public static TimerOrElementCoder<?> of( @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List<Coder<?>> components) { return of(components.get(0)); } } private static class TimerOrElementCloudObjectTranslator implements CloudObjectTranslator<TimerOrElementCoder> { @Override public CloudObject toCloudObject(TimerOrElementCoder target) { throw new IllegalArgumentException("Should never be called"); } @Override public TimerOrElementCoder fromCloudObject(CloudObject cloudObject) { List<Map<String, Object>> encodedComponents = Structs.getListOfMaps( cloudObject, PropertyNames.COMPONENT_ENCODINGS, Collections.emptyList()); checkArgument( encodedComponents.size() == 1, "Expected 1 component for %s, got %s", TimerOrElementCoder.class.getSimpleName(), encodedComponents.size()); CloudObject component = CloudObject.fromSpec(encodedComponents.get(0)); return TimerOrElementCoder.of(CloudObjects.coderFromCloudObject(component)); } @Override public Class<? extends TimerOrElementCoder> getSupportedClass() { return TimerOrElementCoder.class; } @Override public String cloudObjectClassName() { return "com.google.cloud.dataflow.sdk.util.TimerOrElement$TimerOrElementCoder"; } } /** The registrar for {@link TimerOrElementCoder}. */ @SuppressWarnings("unused") @AutoService(CoderCloudObjectTranslatorRegistrar.class) public static class TimerOrElementCloudObjectTranslatorRegistrar implements CoderCloudObjectTranslatorRegistrar { private static final TimerOrElementCloudObjectTranslator TRANSLATOR = new TimerOrElementCloudObjectTranslator(); @Override public Map<Class<? extends Coder>, CloudObjectTranslator<? extends Coder>> classesToTranslators() { return ImmutableMap.of(); } @Override public Map<String, CloudObjectTranslator<? extends Coder>> classNamesToTranslators() { return Collections.singletonMap(TRANSLATOR.cloudObjectClassName(), TRANSLATOR); } } }
39.237705
98
0.756215
34d78aa5105ddfec3085af5ce533b8afbbbb547d
12,282
package me.isaiah.mods.permissions.commands; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.suggestion.SuggestionProvider; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.brigadier.tree.LiteralCommandNode; import cyber.permissions.v1.CyberPermissions; import cyber.permissions.v1.Permissible; import me.isaiah.mods.permissions.Config; import me.isaiah.mods.permissions.CyberPermissionsMod; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.text.LiteralText; import net.minecraft.text.Style; import net.minecraft.util.Formatting; public class PermsCommand implements com.mojang.brigadier.Command<ServerCommandSource>, Predicate<ServerCommandSource>, SuggestionProvider<ServerCommandSource> { public LiteralCommandNode<ServerCommandSource> register(CommandDispatcher<ServerCommandSource> dispatcher, String label) { return dispatcher.register(LiteralArgumentBuilder.<ServerCommandSource>literal(label).requires(this).executes(this) .then(RequiredArgumentBuilder.<ServerCommandSource, String>argument("args", StringArgumentType.greedyString()).suggests(this).executes(this)) ); } @Override public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> context, SuggestionsBuilder builder) throws CommandSyntaxException { builder = builder.createOffset(builder.getInput().lastIndexOf(' ') + 1); List<String> results = new ArrayList<>(); String input = builder.getInput(); int spaces = input.length() - input.replaceAll(" ", "").length(); String[] cmds = input.split(" "); if (cmds.length <= 1) { results.add("creategroup"); results.add("listgroups"); results.add("user"); results.add("group"); } else { if (cmds[1].equalsIgnoreCase("user")) { if (spaces == 2) { for (String plr : context.getSource().getMinecraftServer().getPlayerManager().getPlayerNames()) results.add(plr); } else if (spaces == 3){ results.add("info"); results.add("group"); results.add("permissions"); } else if (cmds.length >= 4) { if (cmds[3].equalsIgnoreCase("group")) { if (spaces == 4) { results.add("add"); results.add("remove"); } else if (cmds.length <= 5) { for (String group : CyberPermissionsMod.groups.keySet()) results.add(group); } } else if (cmds[3].equalsIgnoreCase("permissions")) { if (spaces == 4) { results.add("set"); } else { if (spaces == 5) { results.add("PERMISSION"); } else { results.add("true"); results.add("false"); } } } } } else if (cmds[1].equalsIgnoreCase("group")) { if (spaces == 2) { for (String group : CyberPermissionsMod.groups.keySet()) results.add(group); } else if (spaces == 3){ results.add("info"); results.add("parentgroups"); results.add("permissions"); } else if (cmds.length >= 4){ if (cmds[3].equalsIgnoreCase("parentgroups")) { if (cmds.length <= 4) { results.add("add"); results.add("remove"); } else if (cmds.length <= 5) { for (String group : CyberPermissionsMod.groups.keySet()) results.add(group); } } else if (cmds[3].equalsIgnoreCase("permissions")) { if (cmds.length <= 4) { results.add("set"); } else { if (cmds.length <= 5) { results.add("PERMISSION"); } else { results.add("true"); results.add("false"); } } } } } } boolean should = true; for (String s : results) if (input.endsWith(" " + s)) should = false; if (should) for (String s : results) builder.suggest(s); return builder.buildFuture(); } @Override public boolean test(ServerCommandSource t) { return t.hasPermissionLevel(3); // Player is operator } @Override public int run(CommandContext<ServerCommandSource> context) throws CommandSyntaxException { ServerCommandSource cs = context.getSource(); try { Permissible permissible = CyberPermissions.getPermissible(cs); if (!permissible.isHighLevelOperator()) { cs.sendFeedback(new LiteralText("This command requires operator permission.").setStyle(Style.EMPTY.withColor(Formatting.RED)), false); return 0; } String[] args = context.getInput().split(" "); if (args.length <= 1) { sendMessage(cs, null, "Invalid arguments!"); return 0; } if (args[1].equalsIgnoreCase("creategroup")) { if (!CyberPermissionsMod.groups.containsKey(args[2])) { try { Config conf = new Config(args[2]); CyberPermissionsMod.groups.put(conf.name, conf); sendMessage(cs, null, "Created group: \"" + args[2] + "\"!"); } catch (IOException e) { CyberPermissionsMod.LOGGER.error("Unable to load configuration for a group!"); e.printStackTrace(); } } } if (args[1].equalsIgnoreCase("listgroups")) { for (String group : CyberPermissionsMod.groups.keySet()) sendMessage(cs, null, group); } if (args[1].equalsIgnoreCase("user")) { String[] argz0 = context.getInput().split(args[0] + " " + args[1] + " "); if (argz0.length <= 1) { sendMessage(cs, null, "Invalid arguments!"); return 0; } String[] argz = argz0[1].split(" "); Config e = CyberPermissionsMod.getUser(CyberPermissionsMod.findGameProfile(cs, argz[0])); if (argz.length <= 0) { sendMessage(cs, null, "Usage: /perms user <user> <info|permissions|group|has>"); return 0; } if (argz[1].equalsIgnoreCase("group")) { if (argz[2].equalsIgnoreCase("add")) { e.parentGroups.add(argz[3]); sendMessage(cs, null, "Group added!"); } if (argz[2].equalsIgnoreCase("remove")) { e.parentGroups.remove(argz[3]); sendMessage(cs, null, "Group removed!"); } e.save(); } if (argz[1].equalsIgnoreCase("info")) { sendMessage(cs, Formatting.GREEN, "Info for user \"" + e.name + "\":"); sendMessage(cs, Formatting.GREEN, "UUID: " + e.uuid); sendMessage(cs, Formatting.DARK_GREEN, "parentGroups:"); for (String s : e.parentGroups) sendMessage(cs, Formatting.GREEN, "- " + s); sendMessage(cs, Formatting.DARK_GREEN, "User permissions:"); for (String s : e.permissions) sendMessage(cs, Formatting.GREEN, "- " + s); for (String s : e.negPermissions) sendMessage(cs, Formatting.GREEN, "- -" + s); return 0; } if (argz[1].equalsIgnoreCase("permissions")) { if (argz[2].equalsIgnoreCase("set")) { String perm = argz[3]; String value = argz[4]; e.setPermission(perm, Boolean.valueOf(value)); sendMessage(cs, null, "Permission \"" + perm + "\" set to " + value + " for user " + argz[0]); } } } if (args[1].equalsIgnoreCase("group")) { String[] argz0 = context.getInput().split(args[0] + " " + args[1] + " "); if (argz0.length <= 1) { sendMessage(cs, null, "Invalid arguments!"); return 0; } String[] argz = argz0[1].split(" "); Config e = CyberPermissionsMod.groups.get(argz[0]); if (argz.length <= 0) { sendMessage(cs, null, "Usage: /perms group <group> <info|permissions|parentgroups>"); return 0; } if (argz[1].equalsIgnoreCase("info")) { sendMessage(cs, Formatting.GREEN, "Info for group \"" + e.name + "\":"); sendMessage(cs, Formatting.GREEN, "Name: " + e.name); sendMessage(cs, Formatting.DARK_GREEN, "parentGroups:"); for (String s : e.parentGroups) sendMessage(cs, Formatting.GREEN, "- " + s); sendMessage(cs, Formatting.DARK_GREEN, "Group permissions:"); for (String s : e.permissions) sendMessage(cs, Formatting.GREEN, "- " + s); for (String s : e.negPermissions) sendMessage(cs, Formatting.GREEN, "- -" + s); return 0; } if (argz[1].equalsIgnoreCase("permissions")) { if (argz[2].equalsIgnoreCase("set")) { String perm = argz[3]; String value = argz[4]; e.setPermission(perm, Boolean.valueOf(value)); sendMessage(cs, null, "Permission \"" + perm + "\" set to " + value + " for group " + argz[0]); } } if (argz[1].equalsIgnoreCase("parentgroups")) { if (argz[2].equalsIgnoreCase("add")) { e.parentGroups.add(argz[3]); sendMessage(cs, null, "Group added!"); } if (argz[2].equalsIgnoreCase("remove")) { e.parentGroups.remove(argz[3]); sendMessage(cs, null, "Group removed!"); } e.save(); } } } catch (Exception e) { e.printStackTrace(); } return 0; } public void sendMessage(ServerCommandSource cs, Formatting color, String message) { LiteralText txt = new LiteralText(message); cs.sendFeedback(color != null ? txt.setStyle(Style.EMPTY.withColor(color)) : txt, false); } }
45.657993
161
0.492265
5d3499f58de6ae5c95fb3335ed07eb9d96c87d76
1,804
package com.ean.client.v3.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; /** * Contains the hotel itinerary response for the service request. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonRootName(value = "HotelItineraryResponse") public class HotelItineraryResponse extends BaseResponse implements Serializable { private static final long serialVersionUID = -3751923281323499088L; @JsonProperty("@size") private int size; @JsonProperty("Itinerary") private List<Itinerary> itineraries = new ArrayList<Itinerary>(); /** * Constructor. */ public HotelItineraryResponse() { super(); } /** * Returns the size for the HotelItineraryResponse * * @return int for the size */ public int getSize() { return size; } /** * Returns the first itinerary for the HotelItineraryResponse * * @return Itinerary for the itinerary */ public Itinerary getItinerary() { return itineraries.get(0); } /** * Returns all itineraries for the HotelItineraryResponse * * @return a list containing all itineraries from this HotelItineraryResponse */ public List<Itinerary> getItineraries() { return itineraries; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("HotelItineraryResponse [customerSessionId=%s, size=%s, itineraries=%s, error=%s]", this.getCustomerSessionId(), size, itineraries, this.getEanWsError()); } }
25.771429
112
0.681818
60d9194ff63013bc6d0e82ed2bfbdf380088cd54
345
package com.gigamole.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MirrorButton extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_mirror_button ); } }
24.642857
58
0.756522
313a624a15c3e3af6ab66ea995ef7c6c9de1c6d5
1,468
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.api; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SafeServiceLoader { private static final Logger log = LoggerFactory.getLogger(SafeServiceLoader.class); /** * Delegates to {@link ServiceLoader#load(Class, ClassLoader)} and then eagerly iterates over * returned {@code Iterable}, ignoring any potential {@link UnsupportedClassVersionError}. * * <p>Those errors can happen when some classes returned by {@code ServiceLoader} were compiled * for later java version than is used by currently running JVM. During normal course of business * this should not happen. Please read CONTRIBUTING.md, section "Testing - Java versions" for a * background info why this is Ok. */ public static <T> Iterable<T> load(Class<T> serviceClass, ClassLoader classLoader) { List<T> result = new ArrayList<>(); java.util.ServiceLoader<T> services = ServiceLoader.load(serviceClass, classLoader); for (Iterator<T> iter = services.iterator(); iter.hasNext(); ) { try { result.add(iter.next()); } catch (UnsupportedClassVersionError e) { log.debug("Unable to load instrumentation class: {}", e.getMessage()); } } return result; } }
35.804878
99
0.723433
92150c46a01af5757f587f8d209ea9f02388c283
1,286
package edu.hm.cs.fs.app.presenter; import android.support.annotation.NonNull; import java.util.List; import edu.hm.cs.fs.app.database.ICallback; import edu.hm.cs.fs.app.database.FsModel; import edu.hm.cs.fs.app.database.ModelFactory; import edu.hm.cs.fs.app.view.IFsNewsView; import edu.hm.cs.fs.common.model.News; /** * @author Fabio */ public class FsNewsPresenter extends BasePresenter<IFsNewsView, FsModel> { /** * @param view */ public FsNewsPresenter(final IFsNewsView view) { super(view, ModelFactory.getFs()); } /** * Needed for testing! * * @param view * @param model */ public FsNewsPresenter(final IFsNewsView view, final FsModel model) { super(view, model); } public void loadNews(final boolean refresh) { getView().showLoading(); getModel().getNews(refresh, new ICallback<List<News>>() { @Override public void onSuccess(final List<News> data) { getView().showContent(data); getView().hideLoading(); } @Override public void onError(@NonNull final Throwable e) { getView().showError(e); getView().hideLoading(); } }); } }
25.215686
74
0.601089
1644879a08d6243bad26d8f70780fb836a73fe29
2,437
package com.tencent.smtt.export.external.interfaces; import com.knziha.polymer.browser.webkit.WebResourceResponseCompat; import com.knziha.polymer.widgets.Utils; import java.io.InputStream; import java.util.Map; public class WebResourceResponse { private String mMimeType; private String mEncoding; private int mStatusCode; private String mReasonPhrase; private Map<String, String> mResponseHeaders; private InputStream mInputStream; public WebResourceResponse() { } public WebResourceResponse(String mMimeType, String mEncoding, InputStream Data) { this.mMimeType = mMimeType; this.mEncoding = mEncoding; this.setData(Data); } public WebResourceResponse(String mMimeType, String mEncoding, int StatusCode, String ReasonPhrase, Map<String, String> ResponseHeaders, InputStream Data) { this(mMimeType, mEncoding, Data); this.setStatusCodeAndReasonPhrase(StatusCode, ReasonPhrase); this.setResponseHeaders(ResponseHeaders); } public static WebResourceResponse new_WebResourceResponse(android.webkit.WebResourceResponse ret) { return ret==null?null:new WebResourceResponse(ret); } public WebResourceResponse(android.webkit.WebResourceResponse ret) { this(ret.getMimeType(), ret.getEncoding(), ret.getData()); if(Utils.bigCake) { setResponseHeaders(ret.getResponseHeaders()); } else if(ret instanceof WebResourceResponseCompat) { setResponseHeaders(((WebResourceResponseCompat) ret).getResponseHeaders()); } } public void setMimeType(String var1) { this.mMimeType = var1; } public String getMimeType() { return this.mMimeType; } public void setEncoding(String var1) { this.mEncoding = var1; } public String getEncoding() { return this.mEncoding; } public void setStatusCodeAndReasonPhrase(int var1, String var2) { this.mStatusCode = var1; this.mReasonPhrase = var2; } public int getStatusCode() { return this.mStatusCode; } public String getReasonPhrase() { return this.mReasonPhrase; } public void setResponseHeaders(Map<String, String> var1) { this.mResponseHeaders = var1; } public Map<String, String> getResponseHeaders() { return this.mResponseHeaders; } public void setData(InputStream var1) { this.mInputStream = var1; } public InputStream getData() { return this.mInputStream; } }
27.077778
159
0.724661
d5c3ad507d4c4a757649f97abc3f33e00f04cde0
3,648
package mmm.comercial.centro.model; import java.util.List; import javax.annotation.Resource; import javax.sql.DataSource; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import mmm.comercial.centro.model.interfaces.IClienteDAO; import mmm.comercial.centro.model.mappers.ClienteMapper; import mmm.comercial.centro.pojo.Cliente; @Repository("clienteDAO") public class ClienteDAOImpl implements IClienteDAO { private JdbcTemplate jdbctemplate; @Resource(name = "myDataSource") private DataSource datasource; @Override public int create(Cliente c) { int codigo = -1; final String SQL = "INSERT INTO cliente(user,pass,nombre,apellidos,ruta_imagen,online,hora_conexion,role) VALUES (?,?,?,?,?,?,?,?)"; codigo = jdbctemplate.update(SQL, c.getUser(), c.getPass(), c.getNombre(), c.getApellidos(), c.getRuta_imagen(), c.getOnline(), c.getHora_conexion(), c.getRole()); return codigo; } @Override public Cliente getById(final int codigo) { Cliente c = null; final String SQL = "SELECT id,user,pass,nombre,apellidos,ruta_imagen,online,hora_conexion,role FROM cliente WHERE id=?"; try { c = jdbctemplate.queryForObject(SQL, new Object[] { codigo }, new ClienteMapper()); } catch (EmptyResultDataAccessException e) { c = null; } return c; } @Override public Cliente getByUser(String user) { Cliente c = null; final String SQL = "SELECT id,user,pass,nombre,apellidos,ruta_imagen,online,hora_conexion,role FROM cliente WHERE user=?"; try { c = jdbctemplate.queryForObject(SQL, new Object[] { user }, new ClienteMapper()); } catch (EmptyResultDataAccessException e) { c = null; } return c; } @Override public Cliente getByRole(String role) { Cliente c = null; final String SQL = "SELECT id,user,pass,nombre,apellidos,ruta_imagen,online,hora_conexion,role FROM cliente WHERE role=?"; try { c = jdbctemplate.queryForObject(SQL, new Object[] { role }, new ClienteMapper()); } catch (EmptyResultDataAccessException e) { c = null; } return c; } @Override public Cliente getByOnline() { Cliente c = null; int online = 1; final String SQL = "SELECT id,user,pass,nombre,apellidos,ruta_imagen,online,hora_conexion,role FROM cliente WHERE online=?"; try { c = jdbctemplate.queryForObject(SQL, new Object[] { online }, new ClienteMapper()); } catch (EmptyResultDataAccessException e) { c = null; } return c; } @Override public List<Cliente> getAll() { List<Cliente> clientes = null; final String SQL = "SELECT id,user,pass,nombre,apellidos,ruta_imagen,online,hora_conexion,role FROM cliente"; try { clientes = jdbctemplate.query(SQL, new ClienteMapper()); } catch (EmptyResultDataAccessException e) { clientes = null; } return clientes; } @Override public int update(Cliente c) { int codigo = -1; final String SQL = "UPDATE cliente SET user=?,pass=?,nombre=?,apellidos=?,ruta_imagen=?,online=?,hora_conexion=?,role=? WHERE id=?"; codigo = jdbctemplate.update(SQL, c.getUser(), c.getPass(), c.getNombre(), c.getApellidos(), c.getRuta_imagen(), c.getOnline(), c.getHora_conexion(), c.getRole(), c.getId()); return codigo; } @Override public int delete(int codigo) { int cod = -1; final String SQL = "DELETE FROM cliente WHERE id=?"; cod = jdbctemplate.update(SQL, codigo); return cod; } @Resource(name="myDataSource") @Override public void setDatasource(DataSource datasource) { this.datasource=datasource; jdbctemplate=new JdbcTemplate(datasource); } }
28.724409
134
0.717379
369a6d4de9a98da28348de1eaceedd5e7e2a5139
7,793
package knowledge.consumer; import org.hamcrest.Description; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.After; import org.junit.Before; import org.junit.Test; import jade.content.ContentManager; import jade.content.abs.AbsObject; import jade.content.abs.AbsPredicate; import jade.content.lang.Codec.CodecException; import jade.content.lang.sl.SLVocabulary; import jade.content.onto.Ontology; import jade.content.onto.OntologyException; import jade.lang.acl.ACLMessage; import knowledge.KnowledgeAgent; import knowledge.ontology.Fact; import knowledge.ontology.KnowledgeOntology; import knowledge.ontology.Question; public class FindFactBehaviourTest { private final Mockery context = new Mockery() { { this.setImposteriser(ClassImposteriser.INSTANCE); } }; ACLMessage requestMessage_mock; KnowledgeAgent knowledgeAgent_mock; FindFactBehaviour findFactBehaviour; @Before public void setUp() { requestMessage_mock = context.mock(ACLMessage.class, "request message"); knowledgeAgent_mock = context.mock(KnowledgeAgent.class); findFactBehaviour = new FindFactBehaviour(knowledgeAgent_mock, requestMessage_mock); } @After public void tearDown() { context.assertIsSatisfied(); } @Test public void handleInform_unexpected_response() throws CodecException, OntologyException { ACLMessage informMessage_mock = context.mock(ACLMessage.class, "inform message"); ContentManager contentManager_mock = context.mock(ContentManager.class); AbsPredicate absPredicate_mock = context.mock(AbsPredicate.class); Ontology ontology_mock = context.mock(Ontology.class); context.checking(new Expectations() { { oneOf(knowledgeAgent_mock).trace("knowledge processor liked my question"); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).extractAbsContent(informMessage_mock); will(returnValue(absPredicate_mock)); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).lookupOntology(KnowledgeOntology.ONTOLOGY_NAME); will(returnValue(ontology_mock)); exactly(2).of(absPredicate_mock).getTypeName(); will(returnValue("unexpected")); oneOf(knowledgeAgent_mock).trace("unexpected response"); } }); findFactBehaviour.handleInform(informMessage_mock); } @Test public void handleInform_answer() throws CodecException, OntologyException { ACLMessage informMessage_mock = context.mock(ACLMessage.class, "inform message"); ContentManager contentManager_mock = context.mock(ContentManager.class); AbsPredicate absPredicate_mock = context.mock(AbsPredicate.class); Ontology ontology_mock = context.mock(Ontology.class); Fact fact = new Fact("key", "value"); Question question = new Question(); question.setFact(fact); context.checking(new Expectations() { { oneOf(knowledgeAgent_mock).trace("knowledge processor liked my question"); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).extractAbsContent(informMessage_mock); will(returnValue(absPredicate_mock)); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).lookupOntology(KnowledgeOntology.ONTOLOGY_NAME); will(returnValue(ontology_mock)); oneOf(absPredicate_mock).getTypeName(); will(returnValue(KnowledgeOntology.QUESTION)); oneOf(ontology_mock).toObject(absPredicate_mock); will(returnValue(question)); oneOf(knowledgeAgent_mock).trace("answer question ( key [key] value [value] )"); } }); findFactBehaviour.handleInform(informMessage_mock); } @Test public void handleInform_no_answer() throws CodecException, OntologyException { ACLMessage informMessage_mock = context.mock(ACLMessage.class, "inform message"); ContentManager contentManager_mock = context.mock(ContentManager.class); AbsPredicate absPredicate_mock = context.mock(AbsPredicate.class); Ontology ontology_mock = context.mock(Ontology.class); AbsObject absObject_mock = context.mock(AbsObject.class); Fact fact = new Fact("key", "value"); Question question = new Question(); question.setFact(fact); context.checking(new Expectations() { { oneOf(knowledgeAgent_mock).trace("knowledge processor liked my question"); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).extractAbsContent(informMessage_mock); will(returnValue(absPredicate_mock)); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).lookupOntology(KnowledgeOntology.ONTOLOGY_NAME); will(returnValue(ontology_mock)); exactly(2).of(absPredicate_mock).getTypeName(); will(returnValue(SLVocabulary.NOT)); oneOf(absPredicate_mock).getAbsObject(SLVocabulary.NOT_WHAT); will(returnValue(absObject_mock)); oneOf(ontology_mock).toObject(absObject_mock); will(returnValue(question)); oneOf(knowledgeAgent_mock).trace("no answer for question ( key [key] )"); } }); findFactBehaviour.handleInform(informMessage_mock); } @Test public void handleInform_CodecException() throws CodecException, OntologyException { ACLMessage informMessage_mock = context.mock(ACLMessage.class, "inform message"); ContentManager contentManager_mock = context.mock(ContentManager.class); context.checking(new Expectations() { { oneOf(knowledgeAgent_mock).trace("knowledge processor liked my question"); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).extractAbsContent(informMessage_mock); will(new Action() { @Override public void describeTo(Description arg0) { } @Override public Object invoke(Invocation arg0) throws Throwable { throw new CodecException("Unknown language"); } }); oneOf(knowledgeAgent_mock).trace("Unknown language"); } }); findFactBehaviour.handleInform(informMessage_mock); } @Test public void handleInform_OntologyException() throws CodecException, OntologyException { ACLMessage informMessage_mock = context.mock(ACLMessage.class, "inform message"); ContentManager contentManager_mock = context.mock(ContentManager.class); context.checking(new Expectations() { { oneOf(knowledgeAgent_mock).trace("knowledge processor liked my question"); oneOf(knowledgeAgent_mock).getContentManager(); will(returnValue(contentManager_mock)); oneOf(contentManager_mock).extractAbsContent(informMessage_mock); will(new Action() { @Override public void describeTo(Description arg0) { } @Override public Object invoke(Invocation arg0) throws Throwable { throw new OntologyException("Unknown ontology"); } }); oneOf(knowledgeAgent_mock).trace("Unknown ontology"); } }); findFactBehaviour.handleInform(informMessage_mock); } @Test public void handleRefuse() { ACLMessage refuseMessage_mock = context.mock(ACLMessage.class, "refuse message"); context.checking(new Expectations() { { oneOf(knowledgeAgent_mock).trace("knowledge processor does not liked my question"); } }); findFactBehaviour.handleRefuse(refuseMessage_mock); } }
32.069959
91
0.743744
2f4fa75e15f60939d9d0c623b2a10d7cad431b61
303
package org.usfirst.frc.team3339.robot.triggers; import org.usfirst.frc.team3339.robot.OI; import edu.wpi.first.wpilibj.buttons.Trigger; /** * */ public class TriggerChangeCollectHeightModeUp extends Trigger { @Override public boolean get() { return OI.operatorController.GetPOV_Right(); } }
17.823529
63
0.765677
9b386d286ef27a34e5b8d6f84ace2a2f10ad1ae4
221
public class Main { public static void main(String[] args) { // observable GlobalVariables g1 = new GlobalVariables(1); // observer Window1 w1 = new Window1("test window 1", g1); g1.addObserver(w1); } }
18.416667
48
0.660633
2696a0806e52da45b046068d5b147d3c82525a0b
17,117
/* * Copyright (C) 2018 Seoul National University * * 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 edu.snu.mist.core.task.merging; import edu.snu.mist.common.SerializeUtils; import edu.snu.mist.common.graph.DAG; import edu.snu.mist.common.graph.GraphUtils; import edu.snu.mist.common.graph.MISTEdge; import edu.snu.mist.core.task.*; import edu.snu.mist.core.task.codeshare.ClassLoaderProvider; import javax.inject.Inject; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; /** * This starter tries to merges the submitted dag with the currently running dag. * When a query is submitted, this starter first finds mergeable execution dags. * After that, it merges them with the submitted query. */ public final class ImmediateQueryMergingStarter implements QueryStarter { /** * An algorithm for finding the sub-dag between the execution and submitted dag. */ private final CommonSubDagFinder commonSubDagFinder; /** * Map that has the source conf as a key and the physical execution dag as a value. */ private final SrcAndDagMap<Map<String, String>> srcAndDagMap; /** * The map that has the query id as a key and its configuration dag as a value. */ private final QueryIdConfigDagMap queryIdConfigDagMap; /** * Physical execution dags. */ private final ExecutionDags executionDags; /** * Class loader provider. */ private final ClassLoaderProvider classLoaderProvider; /** * Execution vertex generator. */ private final ExecutionVertexGenerator executionVertexGenerator; /** * A map that has config vertex as a key and the corresponding execution vertex as a value. */ private final ConfigExecutionVertexMap configExecutionVertexMap; /** * A map that has an execution vertex as a key and the reference count number as a value. * The reference count number represents how many queries are sharing the execution vertex. */ private final ExecutionVertexCountMap executionVertexCountMap; /** * A map that has an execution vertex as a key and the dag that contains its vertex as a value. */ private final ExecutionVertexDagMap executionVertexDagMap; /** * The list of jar file paths. */ private final List<String> groupJarFilePaths; @Inject private ImmediateQueryMergingStarter(final CommonSubDagFinder commonSubDagFinder, final SrcAndDagMap<Map<String, String>> srcAndDagMap, final QueryIdConfigDagMap queryIdConfigDagMap, final ExecutionDags executionDags, final ConfigExecutionVertexMap configExecutionVertexMap, final ExecutionVertexCountMap executionVertexCountMap, final ClassLoaderProvider classLoaderProvider, final ExecutionVertexGenerator executionVertexGenerator, final ExecutionVertexDagMap executionVertexDagMap) { this.commonSubDagFinder = commonSubDagFinder; this.srcAndDagMap = srcAndDagMap; this.queryIdConfigDagMap = queryIdConfigDagMap; this.executionDags = executionDags; this.classLoaderProvider = classLoaderProvider; this.executionVertexGenerator = executionVertexGenerator; this.configExecutionVertexMap = configExecutionVertexMap; this.executionVertexCountMap = executionVertexCountMap; this.executionVertexDagMap = executionVertexDagMap; this.groupJarFilePaths = new CopyOnWriteArrayList<>(); } @Override public synchronized void start(final String queryId, final Query query, final DAG<ConfigVertex, MISTEdge> submittedDag, final List<String> jarFilePaths) throws IOException, ClassNotFoundException { queryIdConfigDagMap.put(queryId, submittedDag); // Get a class loader final URL[] urls = SerializeUtils.getJarFileURLs(jarFilePaths); final ClassLoader classLoader = classLoaderProvider.newInstance(urls); synchronized (groupJarFilePaths) { if (jarFilePaths != null && jarFilePaths.size() != 0) { groupJarFilePaths.addAll(jarFilePaths); } } // Synchronize the execution dags to evade concurrent modifications // TODO:[MIST-590] We need to improve this code for concurrent modification synchronized (srcAndDagMap) { // Find mergeable DAGs from the execution dags final Map<Map<String, String>, ExecutionDag> mergeableDags = findMergeableDags(submittedDag); // Exit the merging process if there is no mergeable dag if (mergeableDags.size() == 0) { final ExecutionDag executionDag = generate(submittedDag, urls, classLoader); // Set up the output emitters of the submitted DAG QueryStarterUtils.setUpOutputEmitters(executionDag, query); for (final ExecutionVertex source : executionDag.getDag().getRootVertices()) { // Start the source final PhysicalSource src = (PhysicalSource) source; srcAndDagMap.put(src.getConfiguration(), executionDag); src.start(); } // Update the execution dag of the execution vertex for (final ExecutionVertex ev : executionDag.getDag().getVertices()) { executionVertexDagMap.put(ev, executionDag); } executionDags.add(executionDag); return; } // If there exist mergeable execution dags, // Select the DAG that has the largest number of vertices and merge all of the DAG to the largest DAG final ExecutionDag sharableExecutionDag = selectLargestDag(mergeableDags.values()); // Merge all dag into one execution dag // We suppose that all of the dags has no same vertices for (final ExecutionDag executionDag : mergeableDags.values()) { if (executionDag != sharableExecutionDag) { GraphUtils.copy(executionDag.getDag(), sharableExecutionDag.getDag()); // Remove the execution dag executionDags.remove(executionDag); // Update all of the sources in the execution Dag for (final ExecutionVertex source : executionDag.getDag().getRootVertices()) { srcAndDagMap.replace(((PhysicalSource) source).getConfiguration(), sharableExecutionDag); } // Update the execution dag of the execution vertex for (final ExecutionVertex ev : executionDag.getDag().getVertices()) { executionVertexDagMap.put(ev, sharableExecutionDag); } } } // After that, find the sub-dag between the sharableDAG and the submitted dag final Map<ConfigVertex, ExecutionVertex> subDagMap = commonSubDagFinder.findSubDag(sharableExecutionDag, submittedDag); // After that, we should merge the sharable dag with the submitted dag // and update the output emitters of the sharable dag final Set<ConfigVertex> visited = new HashSet<>(submittedDag.numberOfVertices()); for (final ConfigVertex source : submittedDag.getRootVertices()) { // dfs search ExecutionVertex executionVertex; if (subDagMap.get(source) == null) { executionVertex = executionVertexGenerator.generate(source, urls, classLoader); sharableExecutionDag.getDag().addVertex(executionVertex); executionVertexCountMap.put(executionVertex, 1); executionVertexDagMap.put(executionVertex, sharableExecutionDag); } else { executionVertex = subDagMap.get(source); executionVertexCountMap.put(executionVertex, executionVertexCountMap.get(executionVertex) + 1); } configExecutionVertexMap.put(source, executionVertex); for (final Map.Entry<ConfigVertex, MISTEdge> child : submittedDag.getEdges(source).entrySet()) { dfsMerge(subDagMap, visited, executionVertex, child.getValue(), child.getKey(), sharableExecutionDag, submittedDag, urls, classLoader); } } // If there are sources that are not shared, start them for (final ConfigVertex source : submittedDag.getRootVertices()) { if (!subDagMap.containsKey(source)) { srcAndDagMap.put(source.getConfiguration(), sharableExecutionDag); ((PhysicalSource)configExecutionVertexMap.get(source)).start(); } } } } /** * Create the execution dag in dfs order. */ private void dfsCreation(final ExecutionVertex parent, final MISTEdge parentEdge, final ConfigVertex currVertex, final Map<ConfigVertex, ExecutionVertex> created, final DAG<ConfigVertex, MISTEdge> configDag, final ExecutionDag executionDag, final URL[] urls, final ClassLoader classLoader) throws IOException, ClassNotFoundException { final ExecutionVertex currExecutionVertex; if (created.get(currVertex) == null) { currExecutionVertex = executionVertexGenerator.generate(currVertex, urls, classLoader); created.put(currVertex, currExecutionVertex); executionVertexCountMap.put(currExecutionVertex, 1); executionVertexDagMap.put(currExecutionVertex, executionDag); executionDag.getDag().addVertex(currExecutionVertex); // do dfs creation for (final Map.Entry<ConfigVertex, MISTEdge> edges : configDag.getEdges(currVertex).entrySet()) { final ConfigVertex childVertex = edges.getKey(); final MISTEdge edge = edges.getValue(); dfsCreation(currExecutionVertex, edge, childVertex, created, configDag, executionDag, urls, classLoader); } } else { currExecutionVertex = created.get(currVertex); } configExecutionVertexMap.put(currVertex, currExecutionVertex); executionDag.getDag().addEdge(parent, currExecutionVertex, parentEdge); } /** * This generates a new execution dag from the configuration dag. */ private ExecutionDag generate(final DAG<ConfigVertex, MISTEdge> configDag, final URL[] urls, final ClassLoader classLoader) throws IOException, ClassNotFoundException { // For execution dag final ExecutionDag executionDag = new ExecutionDag(new AdjacentListConcurrentMapDAG<>()); final Map<ConfigVertex, ExecutionVertex> created = new HashMap<>(configDag.numberOfVertices()); for (final ConfigVertex source : configDag.getRootVertices()) { final ExecutionVertex currExecutionVertex = executionVertexGenerator.generate(source, urls, classLoader); created.put(source, currExecutionVertex); configExecutionVertexMap.put(source, currExecutionVertex); executionVertexCountMap.put(currExecutionVertex, 1); executionVertexDagMap.put(currExecutionVertex, executionDag); executionDag.getDag().addVertex(currExecutionVertex); // do dfs creation for (final Map.Entry<ConfigVertex, MISTEdge> edges : configDag.getEdges(source).entrySet()) { final ConfigVertex childVertex = edges.getKey(); final MISTEdge edge = edges.getValue(); dfsCreation(currExecutionVertex, edge, childVertex, created, configDag, executionDag, urls, classLoader); } } return executionDag; } /** * This function merges the submitted dag with the execution dag by traversing the dags in DFS order. * @param subDagMap a map that contains vertices of the sub-dag * @param visited a set that holds the visited vertices * @param parent parent (execution) vertex of the current vertex * @param parentEdge parent edge of the current vertex * @param currentVertex current (config) vertex * @param executionDag execution dag that merges the submitted dag * @param submittedDag submitted dag * @param urls urls for creating execution vertices * @param classLoader classLoader for creating execution vertices */ private void dfsMerge(final Map<ConfigVertex, ExecutionVertex> subDagMap, final Set<ConfigVertex> visited, final ExecutionVertex parent, final MISTEdge parentEdge, final ConfigVertex currentVertex, final ExecutionDag executionDag, final DAG<ConfigVertex, MISTEdge> submittedDag, final URL[] urls, final ClassLoader classLoader) throws IOException, ClassNotFoundException { if (visited.contains(currentVertex)) { executionDag.getDag().addEdge(parent, configExecutionVertexMap.get(currentVertex), parentEdge); return; } // Add to the visited set visited.add(currentVertex); // Traverse in DFS order ExecutionVertex correspondingVertex = subDagMap.get(currentVertex); if (correspondingVertex == null) { // it is not shared, so we need to create it correspondingVertex = executionVertexGenerator.generate(currentVertex, urls, classLoader); executionDag.getDag().addVertex(correspondingVertex); executionVertexCountMap.put(correspondingVertex, 1); executionVertexDagMap.put(correspondingVertex, executionDag); } else { // It is shared, so increase the reference count executionVertexCountMap.put(correspondingVertex, executionVertexCountMap.get(correspondingVertex) + 1); } configExecutionVertexMap.put(currentVertex, correspondingVertex); // Traverse boolean outputEmitterUpdateNeeded = false; for (final Map.Entry<ConfigVertex, MISTEdge> neighbor : submittedDag.getEdges(currentVertex).entrySet()) { final ConfigVertex child = neighbor.getKey(); if (!subDagMap.containsKey(child)) { outputEmitterUpdateNeeded = true; } dfsMerge(subDagMap, visited, correspondingVertex, neighbor.getValue(), child, executionDag, submittedDag, urls, classLoader); } // [TODO:MIST-527] Integrate ExecutionVertex and PhysicalVertex // We need to integrate ExecutionVertex and PhysicalVertex // The output emitter of the current vertex of the execution dag needs to be updated if (outputEmitterUpdateNeeded) { if (correspondingVertex.getType() == ExecutionVertex.Type.SOURCE) { final PhysicalSource s = (PhysicalSource) correspondingVertex; final SourceOutputEmitter sourceOutputEmitter = s.getSourceOutputEmitter(); s.setOutputEmitter(new NonBlockingQueueSourceOutputEmitter<>( executionDag.getDag().getEdges(correspondingVertex), sourceOutputEmitter.getQuery())); } else if (correspondingVertex.getType() == ExecutionVertex.Type.OPERATOR) { ((PhysicalOperator)correspondingVertex).getOperator().setOutputEmitter( new OperatorOutputEmitter(executionDag.getDag().getEdges(correspondingVertex))); } } executionDag.getDag().addEdge(parent, correspondingVertex, parentEdge); } /** * TODO:[MIST-538] Select a sharable DAG that minimizes merging cost in immediate merging * Select one execution dag for merging. * @param dags mergeable dags * @return a dag where all of the dags will be merged */ private ExecutionDag selectLargestDag( final Collection<ExecutionDag> dags) { int count = 0; ExecutionDag largestExecutionDag = null; for (final ExecutionDag executionDag : dags) { if (executionDag.getDag().numberOfVertices() > count) { count = executionDag.getDag().numberOfVertices(); largestExecutionDag = executionDag; } } return largestExecutionDag; } /** * Find mergeable dag with the submitted query. * @param configDag the configuration dag of the submitted query * @return mergeable dags */ private Map<Map<String, String>, ExecutionDag> findMergeableDags( final DAG<ConfigVertex, MISTEdge> configDag) { final Set<ConfigVertex> sources = configDag.getRootVertices(); final Map<Map<String, String>, ExecutionDag> mergeableDags = new HashMap<>(sources.size()); for (final ConfigVertex source : sources) { final Map<String, String> srcConf = source.getConfiguration(); final ExecutionDag executionDag = srcAndDagMap.get(srcConf); if (executionDag != null) { // Mergeable source mergeableDags.put(srcConf, executionDag); } } return mergeableDags; } }
44.002571
113
0.693287
d162a67e48e436705365f683236d3bec582ca10b
16,939
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.github; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataSink; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.actionSystem.TypeSafeDataProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vcs.VcsDataKeys; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog; import com.intellij.openapi.vcs.ui.CommitMessage; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ThrowableConsumer; import com.intellij.util.ThrowableConvertor; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcsUtil.VcsFileUtil; import consulo.github.icon.GitHubIconGroup; import consulo.util.dataholder.Key; import git4idea.DialogManager; import git4idea.GitLocalBranch; import git4idea.GitUtil; import git4idea.actions.BasicAction; import git4idea.actions.GitInit; import git4idea.commands.*; import git4idea.i18n.GitBundle; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.util.GitFileUtils; import git4idea.util.GitUIUtil; import org.jetbrains.plugins.github.api.GithubApiUtil; import org.jetbrains.plugins.github.api.GithubRepo; import org.jetbrains.plugins.github.api.GithubUserDetailed; import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException; import org.jetbrains.plugins.github.ui.GithubShareDialog; import org.jetbrains.plugins.github.util.GithubAuthData; import org.jetbrains.plugins.github.util.GithubNotifications; import org.jetbrains.plugins.github.util.GithubUrlUtil; import org.jetbrains.plugins.github.util.GithubUtil; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import static org.jetbrains.plugins.github.util.GithubUtil.setVisibleEnabled; /** * @author oleg */ public class GithubShareAction extends DumbAwareAction { private static final Logger LOG = GithubUtil.LOG; public GithubShareAction() { super("Share project on GitHub", "Easily share project on GitHub", GitHubIconGroup.github_icon()); } public void update(AnActionEvent e) { final Project project = e.getData(PlatformDataKeys.PROJECT); if(project == null || project.isDefault()) { setVisibleEnabled(e, false, false); return; } setVisibleEnabled(e, true, true); } // get gitRepository // check for existing git repo // check available repos and privateRepo access (net) // Show dialog (window) // create GitHub repo (net) // create local git repo (if not exist) // add GitHub as a remote host // make first commit // push everything (net) @Override public void actionPerformed(final AnActionEvent e) { final Project project = e.getData(PlatformDataKeys.PROJECT); final VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE); if(project == null || project.isDisposed()) { return; } shareProjectOnGithub(project, file); } public static void shareProjectOnGithub(@Nonnull final Project project, @Nullable final VirtualFile file) { BasicAction.saveAll(); // get gitRepository final GitRepository gitRepository = GithubUtil.getGitRepository(project, file); final boolean gitDetected = gitRepository != null; final VirtualFile root = gitDetected ? gitRepository.getRoot() : project.getBaseDir(); // check for existing git repo boolean externalRemoteDetected = false; if(gitDetected) { final String githubRemote = GithubUtil.findGithubRemoteUrl(gitRepository); if(githubRemote != null) { GithubNotifications.showInfoURL(project, "Project is already on GitHub", "GitHub", githubRemote); return; } externalRemoteDetected = !gitRepository.getRemotes().isEmpty(); } // get available GitHub repos with modal progress final GithubInfo githubInfo = loadGithubInfoWithModal(project); if(githubInfo == null) { return; } // Show dialog (window) final GithubShareDialog shareDialog = new GithubShareDialog(project, githubInfo.getRepositoryNames(), githubInfo.getUser().canCreatePrivateRepo()); DialogManager.show(shareDialog); if(!shareDialog.isOK()) { return; } final boolean isPrivate = shareDialog.isPrivate(); final String name = shareDialog.getRepositoryName(); final String description = shareDialog.getDescription(); // finish the job in background final boolean finalExternalRemoteDetected = externalRemoteDetected; new Task.Backgroundable(project, "Sharing project on GitHub...") { @Override public void run(@Nonnull ProgressIndicator indicator) { // create GitHub repo (network) LOG.info("Creating GitHub repository"); indicator.setText("Creating GitHub repository..."); final String url = createGithubRepository(project, githubInfo.getAuthData(), name, description, isPrivate); if(url == null) { return; } LOG.info("Successfully created GitHub repository"); // creating empty git repo if git is not initialized LOG.info("Binding local project with GitHub"); if(!gitDetected) { LOG.info("No git detected, creating empty git repo"); indicator.setText("Creating empty git repo..."); if(!createEmptyGitRepository(project, root, indicator)) { return; } } GitRepositoryManager repositoryManager = GitUtil.getRepositoryManager(project); final GitRepository repository = repositoryManager.getRepositoryForRoot(root); LOG.assertTrue(repository != null, "GitRepository is null for root " + root); final String remoteUrl = GithubUrlUtil.getGitHost() + "/" + githubInfo.getUser().getLogin() + "/" + name + ".git"; final String remoteName = finalExternalRemoteDetected ? "github" : "origin"; //git remote add origin [email protected]:login/name.git LOG.info("Adding GitHub as a remote host"); indicator.setText("Adding GitHub as a remote host..."); if(!addGithubRemote(project, root, remoteName, remoteUrl, repository)) { return; } // create sample commit for binding project if(!performFirstCommitIfRequired(project, root, repository, indicator, name, url)) { return; } //git push origin master LOG.info("Pushing to github master"); indicator.setText("Pushing to github master..."); if(!pushCurrentBranch(project, repository, remoteName, remoteUrl, name, url)) { return; } GithubNotifications.showInfoURL(project, "Successfully shared project on GitHub", name, url); } }.queue(); } @Nullable private static GithubInfo loadGithubInfoWithModal(@Nonnull final Project project) { try { return GithubUtil.computeValueInModal(project, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, GithubInfo, IOException>() { @Override public GithubInfo convert(ProgressIndicator indicator) throws IOException { // get existing github repos (network) and validate auth data final Ref<List<GithubRepo>> availableReposRef = new Ref<List<GithubRepo>>(); final GithubAuthData auth = GithubUtil.runAndGetValidAuth(project, indicator, new ThrowableConsumer<GithubAuthData, IOException>() { @Override public void consume(GithubAuthData authData) throws IOException { availableReposRef.set(GithubApiUtil.getUserRepos(authData)); } }); final HashSet<String> names = new HashSet<String>(); for(GithubRepo info : availableReposRef.get()) { names.add(info.getName()); } // check access to private repos (network) final GithubUserDetailed userInfo = GithubApiUtil.getCurrentUserDetailed(auth); return new GithubInfo(auth, userInfo, names); } }); } catch(GithubAuthenticationCanceledException e) { return null; } catch(IOException e) { GithubNotifications.showErrorDialog(project, "Failed to connect to GitHub", e); return null; } } @Nullable private static String createGithubRepository(@Nonnull Project project, @Nonnull GithubAuthData auth, @Nonnull String name, @Nonnull String description, boolean isPrivate) { try { GithubRepo response = GithubApiUtil.createRepo(auth, name, description, !isPrivate); return response.getHtmlUrl(); } catch(IOException e) { GithubNotifications.showError(project, "Failed to create GitHub Repository", e); return null; } } private static boolean createEmptyGitRepository(@Nonnull Project project, @Nonnull VirtualFile root, @Nonnull ProgressIndicator indicator) { final GitLineHandler h = new GitLineHandler(project, root, GitCommand.INIT); GitHandlerUtil.runInCurrentThread(h, indicator, true, GitBundle.message("initializing.title")); if(!h.errors().isEmpty()) { GitUIUtil.showOperationErrors(project, h.errors(), "git init"); LOG.info("Failed to create empty git repo: " + h.errors()); return false; } GitInit.refreshAndConfigureVcsMappings(project, root, root.getPath()); return true; } private static boolean addGithubRemote(@Nonnull Project project, @Nonnull VirtualFile root, @Nonnull String remoteName, @Nonnull String remoteUrl, @Nonnull GitRepository repository) { final GitSimpleHandler addRemoteHandler = new GitSimpleHandler(project, root, GitCommand.REMOTE); addRemoteHandler.setSilent(true); addRemoteHandler.addParameters("add", remoteName, remoteUrl); try { addRemoteHandler.run(); repository.update(); if(addRemoteHandler.getExitCode() != 0) { GithubNotifications.showError(project, "Failed to add GitHub repository as remote", "Failed to add GitHub repository as remote"); return false; } } catch(VcsException e) { GithubNotifications.showError(project, "Failed to add GitHub repository as remote", e); return false; } return true; } private static boolean performFirstCommitIfRequired(@Nonnull final Project project, @Nonnull VirtualFile root, @Nonnull GitRepository repository, @Nonnull ProgressIndicator indicator, @Nonnull String name, @Nonnull String url) { // check if there is no commits if(!repository.isFresh()) { return true; } LOG.info("Trying to commit"); try { LOG.info("Adding files for commit"); indicator.setText("Adding files to git..."); // ask for files to add final List<VirtualFile> trackedFiles = ChangeListManager.getInstance(project).getAffectedFiles(); final Collection<VirtualFile> untrackedFiles = repository.getUntrackedFilesHolder() .retrieveUntrackedFiles(); final List<VirtualFile> allFiles = new ArrayList<VirtualFile>(); allFiles.addAll(trackedFiles); allFiles.addAll(untrackedFiles); final Ref<GithubUntrackedFilesDialog> dialogRef = new Ref<GithubUntrackedFilesDialog>(); ApplicationManager.getApplication().invokeAndWait(new Runnable() { @Override public void run() { GithubUntrackedFilesDialog dialog = new GithubUntrackedFilesDialog(project, allFiles); if(!trackedFiles.isEmpty()) { dialog.setSelectedFiles(trackedFiles); } DialogManager.show(dialog); dialogRef.set(dialog); } }, indicator.getModalityState()); final GithubUntrackedFilesDialog dialog = dialogRef.get(); final Collection<VirtualFile> files2commit = dialog.getSelectedFiles(); if(!dialog.isOK() || files2commit.isEmpty()) { GithubNotifications.showInfoURL(project, "Successfully created empty repository on GitHub", name, url); return false; } Collection<VirtualFile> files2add = ContainerUtil.intersection(untrackedFiles, files2commit); Collection<VirtualFile> files2rm = ContainerUtil.subtract(trackedFiles, files2commit); Collection<VirtualFile> modified = new HashSet<VirtualFile>(trackedFiles); modified.addAll(files2commit); GitFileUtils.addFiles(project, root, files2add); GitFileUtils.deleteFilesFromCache(project, root, files2rm); // commit LOG.info("Performing commit"); indicator.setText("Performing commit..."); GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); handler.addParameters("-m", dialog.getCommitMessage()); handler.endOptions(); handler.run(); VcsFileUtil.markFilesDirty(project, modified); } catch(VcsException e) { LOG.warn(e); GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'" + name + "'", " on GitHub, but initial commit failed:<br/>" + e.getMessage(), url); return false; } LOG.info("Successfully created initial commit"); return true; } private static boolean pushCurrentBranch(@Nonnull Project project, @Nonnull GitRepository repository, @Nonnull String remoteName, @Nonnull String remoteUrl, @Nonnull String name, @Nonnull String url) { Git git = ServiceManager.getService(Git.class); GitLocalBranch currentBranch = repository.getCurrentBranch(); if(currentBranch == null) { GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'" + name + "'", " on GitHub, but initial push failed: no " + "current branch", url); return false; } GitCommandResult result = git.push(repository, remoteName, remoteUrl, null, currentBranch.getName(), true); if(!result.success()) { GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'" + name + "'", " on GitHub, but initial push failed:<br/>" + result.getErrorOutputAsHtmlString(), url); return false; } return true; } public static class GithubUntrackedFilesDialog extends SelectFilesDialog implements TypeSafeDataProvider { @Nonnull private final Project myProject; private CommitMessage myCommitMessagePanel; public GithubUntrackedFilesDialog(@Nonnull Project project, @Nonnull List<VirtualFile> untrackedFiles) { super(project, untrackedFiles, null, null, true, false, false); myProject = project; setTitle("Add Files For Initial Commit"); init(); } @Override protected JComponent createNorthPanel() { return null; } @Override protected JComponent createCenterPanel() { final JComponent tree = super.createCenterPanel(); myCommitMessagePanel = new CommitMessage(myProject); myCommitMessagePanel.setCommitMessage("Initial commit"); Splitter splitter = new Splitter(true); splitter.setHonorComponentsMinimumSize(true); splitter.setFirstComponent(tree); splitter.setSecondComponent(myCommitMessagePanel); splitter.setProportion(0.7f); return splitter; } @Nonnull public String getCommitMessage() { return myCommitMessagePanel.getComment(); } @Override public void calcData(Key<?> key, DataSink sink) { if(key == VcsDataKeys.COMMIT_MESSAGE_CONTROL) { sink.put(VcsDataKeys.COMMIT_MESSAGE_CONTROL, myCommitMessagePanel); } } @Override protected String getDimensionServiceKey() { return "Github.UntrackedFilesDialog"; } } private static class GithubInfo { @Nonnull private final GithubUserDetailed myUser; @Nonnull private final GithubAuthData myAuthData; @Nonnull private final HashSet<String> myRepositoryNames; GithubInfo(@Nonnull GithubAuthData auth, @Nonnull GithubUserDetailed user, @Nonnull HashSet<String> repositoryNames) { myUser = user; myAuthData = auth; myRepositoryNames = repositoryNames; } @Nonnull public GithubUserDetailed getUser() { return myUser; } @Nonnull public GithubAuthData getAuthData() { return myAuthData; } @Nonnull public HashSet<String> getRepositoryNames() { return myRepositoryNames; } } }
31.310536
109
0.741366
fc09ae7adcb95438c2a38f0e6a10b25709067f5c
896
package com.virtual.lab.mapper; import com.virtual.lab.pojo.RoleFunctionExample; import com.virtual.lab.pojo.RoleFunctionKey; import java.util.List; import org.apache.ibatis.annotations.Param; public interface RoleFunctionMapper { int countByExample(RoleFunctionExample example); int deleteByExample(RoleFunctionExample example); int deleteByPrimaryKey(RoleFunctionKey key); int insert(RoleFunctionKey record); int insertSelective(RoleFunctionKey record); List<RoleFunctionKey> selectByExample(RoleFunctionExample example); int updateByExampleSelective(@Param("record") RoleFunctionKey record, @Param("example") RoleFunctionExample example); int updateByExample(@Param("record") RoleFunctionKey record, @Param("example") RoleFunctionExample example); //根据权限的id删除role_function表里的权限信息 void deleteByFunctionId(String id); }
33.185185
122
0.773438
22d62c2dc98c1d97bf712cd4544da21565dd1ab8
11,457
package org.sagacity.sqltoy.configure; import static java.lang.System.err; import java.util.ArrayList; import java.util.List; import org.sagacity.sqltoy.SqlToyContext; import org.sagacity.sqltoy.config.model.ElasticEndpoint; import org.sagacity.sqltoy.dao.SqlToyLazyDao; import org.sagacity.sqltoy.dao.impl.SqlToyLazyDaoImpl; import org.sagacity.sqltoy.plugins.IUnifyFieldsHandler; import org.sagacity.sqltoy.plugins.TypeHandler; import org.sagacity.sqltoy.plugins.datasource.ConnectionFactory; import org.sagacity.sqltoy.plugins.datasource.DataSourceSelector; import org.sagacity.sqltoy.plugins.secure.DesensitizeProvider; import org.sagacity.sqltoy.plugins.secure.FieldsSecureProvider; import org.sagacity.sqltoy.service.SqlToyCRUDService; import org.sagacity.sqltoy.service.impl.SqlToyCRUDServiceImpl; import org.sagacity.sqltoy.translate.cache.TranslateCacheManager; import org.sagacity.sqltoy.utils.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @description sqltoy 自动配置类 * @author wolf * @version v1.0,Date:2018年12月26日 * @modify {Date:2020-2-20,完善配置支持es等,实现完整功能} */ @Configuration @EnableConfigurationProperties(SqlToyContextProperties.class) public class SqltoyAutoConfiguration { @Autowired private ApplicationContext applicationContext; @Autowired private SqlToyContextProperties properties; // 增加一个辅助校验,避免不少新用户将spring.sqltoy开头写成sqltoy.开头 @Value("${sqltoy.sqlResourcesDir:}") private String sqlResourcesDir; // 构建sqltoy上下文,并指定初始化方法和销毁方法 @Bean(name = "sqlToyContext", initMethod = "initialize", destroyMethod = "destroy") @ConditionalOnMissingBean SqlToyContext sqlToyContext() throws Exception { // 用辅助配置来校验是否配置错误 if (StringUtil.isBlank(properties.getSqlResourcesDir()) && StringUtil.isNotBlank(sqlResourcesDir)) { throw new IllegalArgumentException( "请检查sqltoy配置,是spring.sqltoy作为前缀,而不是sqltoy!\n正确范例: spring.sqltoy.sqlResourcesDir=classpath:com/sagframe/modules"); } SqlToyContext sqlToyContext = new SqlToyContext(); // 当发现有重复sqlId时是否抛出异常,终止程序执行 sqlToyContext.setBreakWhenSqlRepeat(properties.isBreakWhenSqlRepeat()); // sql 文件资源路径 sqlToyContext.setSqlResourcesDir(properties.getSqlResourcesDir()); if (properties.getSqlResources() != null && properties.getSqlResources().length > 0) { List<String> resList = new ArrayList<String>(); for (String prop : properties.getSqlResources()) { resList.add(prop); } sqlToyContext.setSqlResources(resList); } // sql文件解析的编码格式,默认utf-8 if (properties.getEncoding() != null) { sqlToyContext.setEncoding(properties.getEncoding()); } // sqltoy 已经无需指定扫描pojo类,已经改为用的时候动态加载 // pojo 扫描路径,意义不存在 if (properties.getPackagesToScan() != null) { sqlToyContext.setPackagesToScan(properties.getPackagesToScan()); } // 特定pojo类加载,意义已经不存在 if (properties.getAnnotatedClasses() != null) { sqlToyContext.setAnnotatedClasses(properties.getAnnotatedClasses()); } // 批量操作时(saveAll、updateAll),每批次数量,默认200 if (properties.getBatchSize() != null) { sqlToyContext.setBatchSize(properties.getBatchSize()); } // 默认数据库fetchSize if (properties.getFetchSize() > 0) { sqlToyContext.setFetchSize(properties.getFetchSize()); } // 分页查询单页最大记录数量(默认50000) if (properties.getPageFetchSizeLimit() != null) { sqlToyContext.setPageFetchSizeLimit(properties.getPageFetchSizeLimit()); } // sql 检测间隔时长(单位秒) if (properties.getScriptCheckIntervalSeconds() != null) { sqlToyContext.setScriptCheckIntervalSeconds(properties.getScriptCheckIntervalSeconds()); } // 缓存、sql文件在初始化后延时多少秒开始检测 if (properties.getDelayCheckSeconds() != null) { sqlToyContext.setDelayCheckSeconds(properties.getDelayCheckSeconds()); } // 是否debug模式 if (properties.getDebug() != null) { sqlToyContext.setDebug(properties.getDebug()); } // sql执行超过多长时间则打印提醒(默认30秒) if (properties.getPrintSqlTimeoutMillis() != null) { sqlToyContext.setPrintSqlTimeoutMillis(properties.getPrintSqlTimeoutMillis()); } // sql函数转换器 if (properties.getFunctionConverts() != null) { sqlToyContext.setFunctionConverts(properties.getFunctionConverts()); } // 缓存翻译配置 if (properties.getTranslateConfig() != null) { sqlToyContext.setTranslateConfig(properties.getTranslateConfig()); } // 数据库保留字 if (properties.getReservedWords() != null) { sqlToyContext.setReservedWords(properties.getReservedWords()); } // 分页页号超出总页时转第一页,否则返回空集合 sqlToyContext.setPageOverToFirst(properties.isPageOverToFirst()); // 数据库方言 sqlToyContext.setDialect(properties.getDialect()); // sqltoy内置参数默认值修改 sqlToyContext.setDialectConfig(properties.getDialectConfig()); // update 2021-01-18 设置缓存类别,默认ehcache sqlToyContext.setCacheType(properties.getCacheType()); sqlToyContext.setSecurePrivateKey(properties.getSecurePrivateKey()); sqlToyContext.setSecurePublicKey(properties.getSecurePublicKey()); // 设置公共统一属性的处理器 String unfiyHandler = properties.getUnifyFieldsHandler(); if (StringUtil.isNotBlank(unfiyHandler)) { try { IUnifyFieldsHandler handler = null; // 类 if (unfiyHandler.contains(".")) { handler = (IUnifyFieldsHandler) Class.forName(unfiyHandler).getDeclaredConstructor().newInstance(); } // spring bean名称 else if (applicationContext.containsBean(unfiyHandler)) { handler = (IUnifyFieldsHandler) applicationContext.getBean(unfiyHandler); if (handler == null) { throw new ClassNotFoundException("项目中未定义unifyFieldsHandler=" + unfiyHandler + " 对应的bean!"); } } if (handler != null) { sqlToyContext.setUnifyFieldsHandler(handler); } } catch (ClassNotFoundException cne) { err.println("------------------- 错误提示 ------------------------------------------- "); err.println("spring.sqltoy.unifyFieldsHandler=" + unfiyHandler + " 对应类不存在,错误原因:"); err.println("--1.您可能直接copy了参照项目的配置文件,但没有将具体的类也同步copy过来!"); err.println("--2.如您并不需要此功能,请将配置文件中注释掉spring.sqltoy.unifyFieldsHandler"); err.println("------------------------------------------------"); cne.printStackTrace(); throw cne; } } // 设置elastic连接 Elastic es = properties.getElastic(); if (es != null && es.getEndpoints() != null && !es.getEndpoints().isEmpty()) { sqlToyContext.setDefaultElastic(es.getDefaultId()); List<ElasticEndpoint> endpoints = new ArrayList<ElasticEndpoint>(); for (ElasticConfig esconfig : es.getEndpoints()) { ElasticEndpoint ep = new ElasticEndpoint(esconfig.getUrl(), esconfig.getSqlPath()); ep.setId(esconfig.getId()); if (esconfig.getCharset() != null) { ep.setCharset(esconfig.getCharset()); } if (esconfig.getRequestTimeout() != null) { ep.setRequestTimeout(esconfig.getRequestTimeout()); } if (esconfig.getConnectTimeout() != null) { ep.setConnectTimeout(esconfig.getConnectTimeout()); } if (esconfig.getSocketTimeout() != null) { ep.setSocketTimeout(esconfig.getSocketTimeout()); } ep.setAuthCaching(esconfig.isAuthCaching()); ep.setUsername(esconfig.getUsername()); ep.setPassword(esconfig.getPassword()); ep.setKeyStore(esconfig.getKeyStore()); ep.setKeyStorePass(esconfig.getKeyStorePass()); ep.setKeyStoreSelfSign(esconfig.isKeyStoreSelfSign()); ep.setKeyStoreType(esconfig.getKeyStoreType()); endpoints.add(ep); } // 这里已经完成了当没有设置默认节点时将第一个节点作为默认节点 sqlToyContext.setElasticEndpoints(endpoints); } // 设置默认数据库 if (properties.getDefaultDataSource() != null) { sqlToyContext.setDefaultDataSourceName(properties.getDefaultDataSource()); } // 自定义缓存实现管理器 String translateCacheManager = properties.getTranslateCacheManager(); if (StringUtil.isNotBlank(translateCacheManager)) { // 缓存管理器的bean名称 if (applicationContext.containsBean(translateCacheManager)) { sqlToyContext.setTranslateCacheManager( (TranslateCacheManager) applicationContext.getBean(translateCacheManager)); } // 包名和类名称 else if (translateCacheManager.contains(".")) { sqlToyContext.setTranslateCacheManager((TranslateCacheManager) Class.forName(translateCacheManager) .getDeclaredConstructor().newInstance()); } } // 自定义typeHandler String typeHandler = properties.getTypeHandler(); if (StringUtil.isNotBlank(typeHandler)) { if (applicationContext.containsBean(typeHandler)) { sqlToyContext.setTypeHandler((TypeHandler) applicationContext.getBean(typeHandler)); } // 包名和类名称 else if (typeHandler.contains(".")) { sqlToyContext.setTypeHandler( (TypeHandler) Class.forName(typeHandler).getDeclaredConstructor().newInstance()); } } // 自定义数据源选择器 String dataSourceSelector = properties.getDataSourceSelector(); if (StringUtil.isNotBlank(dataSourceSelector)) { if (applicationContext.containsBean(dataSourceSelector)) { sqlToyContext .setDataSourceSelector((DataSourceSelector) applicationContext.getBean(dataSourceSelector)); } // 包名和类名称 else if (dataSourceSelector.contains(".")) { sqlToyContext.setDataSourceSelector( (DataSourceSelector) Class.forName(dataSourceSelector).getDeclaredConstructor().newInstance()); } } // 自定义数据库连接获取和释放的接口实现 String connectionFactory = properties.getConnectionFactory(); if (StringUtil.isNotBlank(connectionFactory)) { if (applicationContext.containsBean(connectionFactory)) { sqlToyContext.setConnectionFactory((ConnectionFactory) applicationContext.getBean(connectionFactory)); } // 包名和类名称 else if (connectionFactory.contains(".")) { sqlToyContext.setConnectionFactory( (ConnectionFactory) Class.forName(connectionFactory).getDeclaredConstructor().newInstance()); } } // 自定义字段安全实现器 String fieldsSecureProvider = properties.getFieldsSecureProvider(); if (StringUtil.isNotBlank(fieldsSecureProvider)) { if (applicationContext.containsBean(fieldsSecureProvider)) { sqlToyContext.setFieldsSecureProvider( (FieldsSecureProvider) applicationContext.getBean(fieldsSecureProvider)); } // 包名和类名称 else if (fieldsSecureProvider.contains(".")) { sqlToyContext.setFieldsSecureProvider((FieldsSecureProvider) Class.forName(fieldsSecureProvider) .getDeclaredConstructor().newInstance()); } } // 自定义字段脱敏处理器 String desensitizeProvider = properties.getDesensitizeProvider(); if (StringUtil.isNotBlank(desensitizeProvider)) { if (applicationContext.containsBean(desensitizeProvider)) { sqlToyContext .setDesensitizeProvider((DesensitizeProvider) applicationContext.getBean(desensitizeProvider)); } // 包名和类名称 else if (desensitizeProvider.contains(".")) { sqlToyContext.setDesensitizeProvider((DesensitizeProvider) Class.forName(desensitizeProvider) .getDeclaredConstructor().newInstance()); } } return sqlToyContext; } /** * * @return 返回预定义的通用Dao实例 */ @Bean(name = "sqlToyLazyDao") @ConditionalOnMissingBean SqlToyLazyDao sqlToyLazyDao() { return new SqlToyLazyDaoImpl(); } /** * * @return 返回预定义的通用CRUD service实例 */ @Bean(name = "sqlToyCRUDService") @ConditionalOnMissingBean SqlToyCRUDService sqlToyCRUDService() { return new SqlToyCRUDServiceImpl(); } }
36.839228
118
0.751942
cb43645b09f1b6efaa975acb816572e5f5dddcf5
1,794
package robson.games.tictactoe.game.ai.rules; import org.junit.Assert; import org.junit.Test; import robson.games.tictactoe.model.Field; import robson.games.tictactoe.model.Path; import robson.games.tictactoe.model.Player; import java.util.ArrayList; import java.util.List; public class DestroySomeoneElseVictoryTest { private final DestroySomeoneElseVictory destroySomeoneElseVictory = new DestroySomeoneElseVictory(); @Test public void shouldChangeIfPathIsReadyToTheVictory() { List<Path> paths = new ArrayList<>(); Field field = new Field(0, 0); field.assign(new Player('T')); Path pathA = new Path(); pathA.add(new Field(0, 0)); pathA.add(field); pathA.add(field); paths.add(pathA); destroySomeoneElseVictory.executeSelection(new Player('X'), paths); Assert.assertTrue(pathA.isFull()); } @Test public void shouldntChangeIfPathIsntReadyToTheVictory() { List<Path> paths = new ArrayList<>(); Field field = new Field(0, 0); field.assign(new Player('T')); Path pathA = new Path(); pathA.add(new Field(0, 0)); pathA.add(new Field(0, 0)); pathA.add(field); paths.add(pathA); destroySomeoneElseVictory.executeSelection(new Player('X'), paths); Assert.assertTrue(pathA.countFreeFields() == 2); } @Test public void shouldntChangeAnEmptyPath() { List<Path> paths = new ArrayList<>(); Path pathA = new Path(); pathA.add(new Field(0, 0)); pathA.add(new Field(0, 0)); pathA.add(new Field(0, 0)); paths.add(pathA); destroySomeoneElseVictory.executeSelection(new Player('X'), paths); Assert.assertTrue(pathA.isEmpty()); } }
27.181818
104
0.641583
9680dc8b979ddee748affea96035e504240350a1
169
package com.minimal.mapper.back; import com.minimal.entity.model.Menu; import tk.mybatis.mapper.common.Mapper; public interface BackMenuMapper extends Mapper<Menu> { }
24.142857
54
0.810651
7d2f6964ff649d414ee1e2533a553c68702bfc76
7,997
/* * Copyright 2009-2020 Exactpro (Exactpro Systems Limited) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exactpro.sf.services.mina; import java.util.Objects; import java.util.stream.Collectors; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.filterchain.IoFilter; import org.apache.mina.core.future.WriteFuture; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.exactpro.sf.common.messages.IMessage; import com.exactpro.sf.common.messages.IMetadata; import com.exactpro.sf.common.messages.MetadataExtensions; import com.exactpro.sf.common.services.ServiceName; import com.exactpro.sf.common.util.EPSCommonException; import com.exactpro.sf.common.util.SendMessageFailedException; import com.exactpro.sf.configuration.ILoggingConfigurator; import com.exactpro.sf.messages.service.ErrorMessage; import com.exactpro.sf.services.ISession; import com.exactpro.sf.services.ServiceException; public class MINASession implements ISession { protected final Logger logger = LoggerFactory.getLogger(ILoggingConfigurator.getLoggerName(this)); protected final IoSession session; protected final ServiceName serviceName; protected final long sendMessageTimeout; protected volatile boolean loggedOn; public MINASession(ServiceName serviceName, IoSession session, long sendMessageTimeout) { this.serviceName = Objects.requireNonNull(serviceName, "serviceName cannot be null"); this.session = Objects.requireNonNull(session, "session cannot be null"); this.sendMessageTimeout = sendMessageTimeout; } @Override public String getName() { return serviceName.toString(); } @Override public IMessage send(Object message) throws InterruptedException { return send(message, sendMessageTimeout); } protected Object prepareMessage(Object message) { return message; } public IMessage send(Object message, long timeout) throws InterruptedException { if(!isConnected()) { throw new SendMessageFailedException("Session isn't connected: " + this); } if (timeout < 1) { throw new EPSCommonException("Illegal timeout value: " + timeout); } WriteFuture future = session.write(prepareMessage(message)); if(future.await(timeout)) { if(!future.isDone()) { throw new SendMessageFailedException("Send operation isn't done. Session: " + this, future.getException()); } if(!future.isWritten()) { throw new SendMessageFailedException("Write operation isn't done. Session: " + this, future.getException()); } } else { throw new SendMessageFailedException("Send operation isn't completed. Session: " + this, future.getException()); } if(future.getException() != null) { throw new SendMessageFailedException("Message send failed. Session: " + this, future.getException()); } return message instanceof IMessage ? (IMessage)message : null; } @Override public IMessage sendDirty(Object message) throws InterruptedException { throw new UnsupportedOperationException("Dirty send is not supported"); } @Override public void sendRaw(byte[] rawData, IMetadata extraMetadata) throws InterruptedException { IoFilter codecFilter = session.getFilterChain().get(AbstractMINAService.CODEC_FILTER_NAME); if (codecFilter == null) { throw new IllegalStateException("Cannot get filter '" + AbstractMINAService.CODEC_FILTER_NAME + "' from session " + session); } try { MessageNextFilter nextFilter = new MessageNextFilter(); codecFilter.messageReceived(nextFilter, session, IoBuffer.wrap(rawData)); if (!nextFilter.getExceptions().isEmpty()) { SendMessageFailedException exception = new SendMessageFailedException("Exception accurate during decoding"); nextFilter.getExceptions().forEach(exception::addSuppressed); throw exception; } boolean sent = false; for (IMessage result : nextFilter.getResults()) { if (filterResultFromSendRaw(result)) { continue; } if (ErrorMessage.MESSAGE_NAME.equals(result.getName())) { ErrorMessage errorMessage = new ErrorMessage(result); logger.error("Got error message when decoding the raw message: {}", errorMessage.getCause()); throw new SendMessageFailedException("Got error when decoding the raw message: " + errorMessage.getCause()); } removeSessionFields(result); MetadataExtensions.merge(result.getMetaData(), extraMetadata); send(result); sent = true; } if (!sent) { throw new SendMessageFailedException("No messages were sent to the system. Result size: " + nextFilter.getResults().size() + ". Messages in the result: " + nextFilter.getResults().stream() .map(IMessage::getName) .collect(Collectors.joining(", ")) ); } } catch (ProtocolDecoderException e) { throw new SendMessageFailedException("Cannot decode raw bytes to messages", e); } catch (Exception e) { if (e instanceof InterruptedException) { throw (InterruptedException)e; } throw new SendMessageFailedException("Cannot send message", e); } } protected boolean filterResultFromSendRaw(IMessage result) { // all messages by default are allowed for sending return false; } protected void removeSessionFields(IMessage result) { // do nothing by default } @Override public void close() { logger.debug("Closing session: {}", this); session.close(true).addListener(future -> { logger.debug("Session closed: {}", this); }); } @Override public boolean isClosed() { return !isConnected(); } @Override public boolean isLoggedOn() { return loggedOn; } public void setLoggedOn(boolean loggedOn) { if(!isConnected()) { throw new ServiceException("Session is not connected: " + this); } this.loggedOn = loggedOn; } public boolean isConnected() { return session.isConnected(); } public boolean waitClose(long timeout) throws InterruptedException { long waitUntil = System.currentTimeMillis() + timeout; while(isConnected() && waitUntil > System.currentTimeMillis()) { Thread.sleep(1); } return isClosed(); } @Override public String toString() { ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE); builder.append("serviceName", serviceName); builder.append("session", session); builder.append("loggedOn", loggedOn); return builder.toString(); } }
37.544601
137
0.659622
74f99fa5e0ec1800bf44ba172aa3e874e84c2fc4
1,228
/* * Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. This * code is released under a tri EPL/GPL/LGPL license. You can use it, * redistribute it and/or modify it under the terms of the: * * Eclipse Public License version 1.0 * GNU General Public License version 2 * GNU Lesser General Public License version 2.1 */ package org.jruby.truffle.nodes.instrument; import com.oracle.truffle.api.instrument.ASTProber; import com.oracle.truffle.api.instrument.StandardSyntaxTag; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.NodeVisitor; import org.jruby.truffle.nodes.RubyNode; public class RubyDefaultASTProber implements NodeVisitor, ASTProber { @Override public boolean visit(Node node) { if (node.isInstrumentable() && node instanceof RubyNode) { final RubyNode rubyNode = (RubyNode) node; if (rubyNode.isAtNewline()) { // Identify statements using "newline" nodes created by the JRuby parser. rubyNode.probe().tagAs(StandardSyntaxTag.STATEMENT, null); } } return true; } @Override public void probeAST(Node node) { node.accept(this); } }
31.487179
89
0.693811
711da4e4b5f9edf9706b17ac261d18588d65965b
3,544
/* * MoonPhasesPreference.java * * TKWeek (c) Thomas Künneth 2016 - 2021 * Alle Rechte beim Autoren. All rights reserved. */ package com.thomaskuenneth.tkweek.preference; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.DialogPreference; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import com.thomaskuenneth.tkweek.R; public class MoonPhasesPreference extends DialogPreference { public static final String HIDE_MOONPHASES = "hide_moon_phases"; public static final String SHOW_NEW_MOON = "show_new_moon"; public static final String SHOW_FULL_MOON = "show_full_moon"; public static final String SHOW_FIRST_QUARTER = "show_first_quarter"; public static final String SHOW_LAST_QUARTER = "show_last_quarter"; private SharedPreferences prefs; private LinearLayout checkboxes; private CheckBox showMoonPhases; private CheckBox newMoon; private CheckBox fullMoon; private CheckBox firstQuarter; private CheckBox lastQuarter; public MoonPhasesPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected View onCreateDialogView() { Context context = getContext(); LinearLayout layout = new LinearLayout(context); layout.setOrientation(LinearLayout.VERTICAL); prefs = PreferenceManager .getDefaultSharedPreferences(context); checkboxes = new LinearLayout(context); checkboxes.setOrientation(LinearLayout.VERTICAL); showMoonPhases = new CheckBox(context); showMoonPhases.setText(context.getString(R.string.show_moon_phases)); showMoonPhases.setOnCheckedChangeListener((buttonView, isChecked) -> setVisibility(isChecked)); showMoonPhases.setChecked(!prefs.getBoolean(HIDE_MOONPHASES, false)); layout.addView(showMoonPhases); newMoon = createAndAddMoonPhaseCheckbox(R.string.new_moon, SHOW_NEW_MOON); firstQuarter = createAndAddMoonPhaseCheckbox(R.string.first_quarter, SHOW_FIRST_QUARTER); fullMoon = createAndAddMoonPhaseCheckbox(R.string.full_moon, SHOW_FULL_MOON); lastQuarter = createAndAddMoonPhaseCheckbox(R.string.last_quarter, SHOW_LAST_QUARTER); layout.addView(checkboxes); setVisibility(showMoonPhases.isChecked()); return layout; } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { Editor editor = prefs.edit(); editor.putBoolean(HIDE_MOONPHASES, !showMoonPhases.isChecked()); editor.putBoolean(SHOW_NEW_MOON, newMoon.isChecked()); editor.putBoolean(SHOW_FIRST_QUARTER, firstQuarter.isChecked()); editor.putBoolean(SHOW_FULL_MOON, fullMoon.isChecked()); editor.putBoolean(SHOW_LAST_QUARTER, lastQuarter.isChecked()); editor.apply(); } } private CheckBox createAndAddMoonPhaseCheckbox(int resId, String key) { Context context = getContext(); CheckBox cb = new CheckBox(context); cb.setText(context.getString(resId)); cb.setChecked(prefs.getBoolean(key, true)); checkboxes.addView(cb); return cb; } private void setVisibility(boolean visible) { checkboxes.setVisibility(visible ? View.VISIBLE : View.GONE); } }
39.377778
103
0.727144
f89c9cf510adbe4a343f519ffc02505a75839524
10,495
package org.bouncycastle.pqc.crypto.rainbow; import javax.security.SecureRandom; import org.bouncycastle.pqc.crypto.rainbow.util.GF2Field; import org.bouncycastle.pqc.crypto.rainbow.util.RainbowUtil; import org.bouncycastle.util.Arrays; /** * This class represents a layer of the Rainbow Oil- and Vinegar Map. Each Layer * consists of oi polynomials with their coefficients, generated at random. * <p> * To sign a document, we solve a LES (linear equation system) for each layer in * order to find the oil variables of that layer and to be able to use the * variables to compute the signature. This functionality is implemented in the * RainbowSignature-class, by the aid of the private key. * <p> * Each layer is a part of the private key. * <p> * More information about the layer can be found in the paper of Jintai Ding, * Dieter Schmidt: Rainbow, a New Multivariable Polynomial Signature Scheme. * ACNS 2005: 164-175 (http://dx.doi.org/10.1007/11496137_12) */ public class Layer { private int vi; // number of vinegars in this layer private int viNext; // number of vinegars in next layer private int oi; // number of oils in this layer /* * k : index of polynomial * * i,j : indices of oil and vinegar variables */ private short[/* k */][/* i */][/* j */] coeff_alpha; private short[/* k */][/* i */][/* j */] coeff_beta; private short[/* k */][/* i */] coeff_gamma; private short[/* k */] coeff_eta; /** * Constructor * * @param vi number of vinegar variables of this layer * @param viNext number of vinegar variables of next layer. It's the same as * (num of oils) + (num of vinegars) of this layer. * @param coeffAlpha alpha-coefficients in the polynomials of this layer * @param coeffBeta beta-coefficients in the polynomials of this layer * @param coeffGamma gamma-coefficients in the polynomials of this layer * @param coeffEta eta-coefficients in the polynomials of this layer */ public Layer(byte vi, byte viNext, short[][][] coeffAlpha, short[][][] coeffBeta, short[][] coeffGamma, short[] coeffEta) { this.vi = vi & 0xff; this.viNext = viNext & 0xff; this.oi = this.viNext - this.vi; // the secret coefficients of all polynomials in this layer this.coeff_alpha = coeffAlpha; this.coeff_beta = coeffBeta; this.coeff_gamma = coeffGamma; this.coeff_eta = coeffEta; } /** * This function generates the coefficients of all polynomials in this layer * at random using random generator. * * @param sr the random generator which is to be used */ public Layer(int vi, int viNext, SecureRandom sr) { this.vi = vi; this.viNext = viNext; this.oi = viNext - vi; // the coefficients of all polynomials in this layer this.coeff_alpha = new short[this.oi][this.oi][this.vi]; this.coeff_beta = new short[this.oi][this.vi][this.vi]; this.coeff_gamma = new short[this.oi][this.viNext]; this.coeff_eta = new short[this.oi]; int numOfPoly = this.oi; // number of polynomials per layer // Alpha coeffs for (int k = 0; k < numOfPoly; k++) { for (int i = 0; i < this.oi; i++) { for (int j = 0; j < this.vi; j++) { coeff_alpha[k][i][j] = (short)(sr.nextInt() & GF2Field.MASK); } } } // Beta coeffs for (int k = 0; k < numOfPoly; k++) { for (int i = 0; i < this.vi; i++) { for (int j = 0; j < this.vi; j++) { coeff_beta[k][i][j] = (short)(sr.nextInt() & GF2Field.MASK); } } } // Gamma coeffs for (int k = 0; k < numOfPoly; k++) { for (int i = 0; i < this.viNext; i++) { coeff_gamma[k][i] = (short)(sr.nextInt() & GF2Field.MASK); } } // Eta for (int k = 0; k < numOfPoly; k++) { coeff_eta[k] = (short)(sr.nextInt() & GF2Field.MASK); } } /** * This method plugs in the vinegar variables into the polynomials of this * layer and computes the coefficients of the Oil-variables as well as the * free coefficient in each polynomial. * <p> * It is needed for computing the Oil variables while signing. * * @param x vinegar variables of this layer that should be plugged into * the polynomials. * @return coeff the coefficients of Oil variables and the free coeff in the * polynomials of this layer. */ public short[][] plugInVinegars(short[] x) { // temporary variable needed for the multiplication short tmpMult = 0; // coeff: 1st index = which polynomial, 2nd index=which variable short[][] coeff = new short[oi][oi + 1]; // gets returned // free coefficient per polynomial short[] sum = new short[oi]; /* * evaluate the beta-part of the polynomials (it contains no oil * variables) */ for (int k = 0; k < oi; k++) { for (int i = 0; i < vi; i++) { for (int j = 0; j < vi; j++) { // tmp = beta * xi (plug in) tmpMult = GF2Field.multElem(coeff_beta[k][i][j], x[i]); // tmp = tmp * xj tmpMult = GF2Field.multElem(tmpMult, x[j]); // accumulate into the array for the free coefficients. sum[k] = GF2Field.addElem(sum[k], tmpMult); } } } /* evaluate the alpha-part (it contains oils) */ for (int k = 0; k < oi; k++) { for (int i = 0; i < oi; i++) { for (int j = 0; j < vi; j++) { // alpha * xj (plug in) tmpMult = GF2Field.multElem(coeff_alpha[k][i][j], x[j]); // accumulate coeff[k][i] = GF2Field.addElem(coeff[k][i], tmpMult); } } } /* evaluate the gama-part of the polynomial (containing no oils) */ for (int k = 0; k < oi; k++) { for (int i = 0; i < vi; i++) { // gamma * xi (plug in) tmpMult = GF2Field.multElem(coeff_gamma[k][i], x[i]); // accumulate in the array for the free coefficients (per // polynomial). sum[k] = GF2Field.addElem(sum[k], tmpMult); } } /* evaluate the gama-part of the polynomial (but containing oils) */ for (int k = 0; k < oi; k++) { for (int i = vi; i < viNext; i++) { // oils // accumulate the coefficients of the oil variables (per // polynomial). coeff[k][i - vi] = GF2Field.addElem(coeff_gamma[k][i], coeff[k][i - vi]); } } /* evaluate the eta-part of the polynomial */ for (int k = 0; k < oi; k++) { // accumulate in the array for the free coefficients per polynomial. sum[k] = GF2Field.addElem(sum[k], coeff_eta[k]); } /* put the free coefficients (sum) into the coeff-array as last column */ for (int k = 0; k < oi; k++) { coeff[k][oi] = sum[k]; } return coeff; } /** * Getter for the number of vinegar variables of this layer. * * @return the number of vinegar variables of this layer. */ public int getVi() { return vi; } /** * Getter for the number of vinegar variables of the next layer. * * @return the number of vinegar variables of the next layer. */ public int getViNext() { return viNext; } /** * Getter for the number of Oil variables of this layer. * * @return the number of oil variables of this layer. */ public int getOi() { return oi; } /** * Getter for the alpha-coefficients of the polynomials in this layer. * * @return the coefficients of alpha-terms of this layer. */ public short[][][] getCoeffAlpha() { return coeff_alpha; } /** * Getter for the beta-coefficients of the polynomials in this layer. * * @return the coefficients of beta-terms of this layer. */ public short[][][] getCoeffBeta() { return coeff_beta; } /** * Getter for the gamma-coefficients of the polynomials in this layer. * * @return the coefficients of gamma-terms of this layer */ public short[][] getCoeffGamma() { return coeff_gamma; } /** * Getter for the eta-coefficients of the polynomials in this layer. * * @return the coefficients eta of this layer */ public short[] getCoeffEta() { return coeff_eta; } /** * This function compares this Layer with another object. * * @param other the other object * @return the result of the comparison */ public boolean equals(Object other) { if (other == null || !(other instanceof Layer)) { return false; } Layer otherLayer = (Layer)other; return vi == otherLayer.getVi() && viNext == otherLayer.getViNext() && oi == otherLayer.getOi() && RainbowUtil.equals(coeff_alpha, otherLayer.getCoeffAlpha()) && RainbowUtil.equals(coeff_beta, otherLayer.getCoeffBeta()) && RainbowUtil.equals(coeff_gamma, otherLayer.getCoeffGamma()) && RainbowUtil.equals(coeff_eta, otherLayer.getCoeffEta()); } public int hashCode() { int hash = vi; hash = hash * 37 + viNext; hash = hash * 37 + oi; hash = hash * 37 + Arrays.hashCode(coeff_alpha); hash = hash * 37 + Arrays.hashCode(coeff_beta); hash = hash * 37 + Arrays.hashCode(coeff_gamma); hash = hash * 37 + Arrays.hashCode(coeff_eta); return hash; } }
32.49226
84
0.537589
725bd2bb9339062cde63287c9b33534dcf6f2e53
8,388
package org.corfudb.integration; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Arrays; import java.util.Collections; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; /** * This suite of tests verifies the behavior of log replication in the event of * Checkpoint and Trim both in the sender (source/active cluster) and receiver (sink/standby cluster) */ @Slf4j public class CorfuReplicationTrimIT extends LogReplicationAbstractIT { /** * Sets the plugin path before starting any test * @throws Exception */ @Before public void setupPluginPath() { if(runProcess) { File f = new File(nettyConfig); this.pluginConfigFilePath = f.getAbsolutePath(); } else { this.pluginConfigFilePath = nettyConfig; } } /** * Test the case where the log is trimmed on the standby in between two snapshot syncs. * We should guarantee that shadow streams do not throw trim exceptions and data is applied successfully. * * This test does the following: * (1) Do a Snapshot (full) and Log Entry (delta) Sync * (2) Stop the active cluster LR (we stop so we can write some more data and checkpoint it, such that we enforce * s subsequent snapshot sync, otherwise this written data would be transferred in log entry--delta--sync) * (3) Checkpoint and Trim on Standby Cluster (enforce shadow streams to be trimmed) * (4) Write additional data on Active Cluster (while LR is down) * (4.1) Verify Data written is present on active * (4.2) Verify this new Data is not yet present on standby * (5) Checkpoint and Trim on Active Cluster (to guarantee when we bring up the server, delta's are not available * so Snapshot Sync is enforced) * (6) Start Active LR * (7) Verify Data reaches standby cluster * * */ @Test public void testTrimBetweenSnapshotSync() throws Exception { try { testEndToEndSnapshotAndLogEntrySync(); // Stop Log Replication on Active, so we can write some data into active Corfu // and checkpoint so we enforce a subsequent Snapshot Sync log.debug("Stop Active Log Replicator ..."); stopActiveLogReplicator(); // Checkpoint & Trim on the Standby (so shadow stream get trimmed) checkpointAndTrim(false, Collections.singletonList(mapAStandby)); // Write Entry's to Active Cluster (while replicator is down) log.debug("Write additional entries to active CorfuDB ..."); writeToActive((numWrites + (numWrites/2)), numWrites/2); // Confirm data does exist on Active Cluster assertThat(mapA.size()).isEqualTo(numWrites*2); // Confirm new data does not exist on Standby Cluster assertThat(mapAStandby.size()).isEqualTo((numWrites + (numWrites/2))); // Checkpoint & Trim on the Active so we force a snapshot sync on restart checkpointAndTrim(true, Collections.singletonList(mapA)); log.debug("Start active Log Replicator again ..."); startActiveLogReplicator(); log.debug("Verify Data on Standby ..."); verifyDataOnStandby((numWrites*2)); log.debug("Entries :: " + mapAStandby.keySet()); } finally { executorService.shutdownNow(); if (activeCorfu != null) { activeCorfu.destroy(); } if (standbyCorfu != null) { standbyCorfu.destroy(); } if (activeReplicationServer != null) { activeReplicationServer.destroy(); } if (standbyReplicationServer != null) { standbyReplicationServer.destroy(); } } } /** * Test the case where the log is trimmed in between two cycles of log entry sync. * In this test we stop the active log replicator before trimming so we * can enforce re-negotiation after the trim. */ @Test public void testTrimmedExceptionsBetweenLogEntrySync() throws Exception { testLogTrimBetweenLogEntrySync(true); } /** * Test the case where the log is trimmed in between two cycles of log entry sync. * In this test we don't stop the active log replicator, so log entry sync is resumed. */ @Test public void testTrimmedExceptionsBetweenLogEntrySyncContinuous() throws Exception { testLogTrimBetweenLogEntrySync(false); } /** * Test trimming the log on the standby site, in the middle of log entry sync. * * @param stop true, stop the active server right before trimming (to enforce re-negotiation) * false, trim without stopping the server. */ private void testLogTrimBetweenLogEntrySync(boolean stop) throws Exception { try { testEndToEndSnapshotAndLogEntrySync(); if (stop) { // Stop Log Replication on Active, so we can test re-negotiation in the event of trims log.debug("Stop Active Log Replicator ..."); stopActiveLogReplicator(); } // Checkpoint & Trim on the Standby, so we trim the shadow stream checkpointAndTrim(false, Collections.singletonList(mapAStandby)); // Write Entry's to Active Cluster (while replicator is down) log.debug("Write additional entries to active CorfuDB ..."); writeToActive((numWrites + (numWrites/2)), numWrites/2); // Confirm data does exist on Active Cluster assertThat(mapA.size()).isEqualTo(numWrites*2); if (stop) { // Confirm new data does not exist on Standby Cluster assertThat(mapAStandby.size()).isEqualTo((numWrites + (numWrites / 2))); log.debug("Start active Log Replicator again ..."); startActiveLogReplicator(); } // Since we did not checkpoint data should be transferred in delta's log.debug("Verify Data on Standby ..."); verifyDataOnStandby((numWrites*2)); log.debug("Entries :: " + mapAStandby.keySet()); } finally { executorService.shutdownNow(); if (activeCorfu != null) { activeCorfu.destroy(); } if (standbyCorfu != null) { standbyCorfu.destroy(); } if (activeReplicationServer != null) { activeReplicationServer.destroy(); } if (standbyReplicationServer != null) { standbyReplicationServer.destroy(); } } } @Test public void testSnapshotSyncEndToEndWithCheckpointedStreams() throws Exception { try { log.debug("\nSetup active and standby Corfu's"); setupActiveAndStandbyCorfu(); log.debug("Open map on active and standby"); openMap(); log.debug("Write data to active CorfuDB before LR is started ..."); // Add Data for Snapshot Sync writeToActive(0, numWrites); // Confirm data does exist on Active Cluster assertThat(mapA.size()).isEqualTo(numWrites); // Confirm data does not exist on Standby Cluster assertThat(mapAStandby.size()).isZero(); // Checkpoint and Trim Before Starting checkpointAndTrim(true, Arrays.asList(mapA)); startLogReplicatorServers(); log.debug("Wait ... Snapshot log replication in progress ..."); verifyDataOnStandby(numWrites); } finally { executorService.shutdownNow(); if (activeCorfu != null) { activeCorfu.destroy(); } if (standbyCorfu != null) { standbyCorfu.destroy(); } if (activeReplicationServer != null) { activeReplicationServer.destroy(); } if (standbyReplicationServer != null) { standbyReplicationServer.destroy(); } } } }
35.542373
122
0.599905
10032a29d1b48e60bdc3a134f025b2334a4fac23
5,646
/* * 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.beam.sdk.metrics; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import java.util.Map; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.annotations.Experimental.Kind; import org.apache.beam.sdk.metrics.MetricUpdates.MetricUpdate; /** * Holds the metrics for a single step and unit-of-commit (bundle). * * <p>This class is thread-safe. It is intended to be used with 1 (or more) threads are updating * metrics and at-most 1 thread is extracting updates by calling {@link #getUpdates} and * {@link #commitUpdates}. Outside of this it is still safe. Although races in the update extraction * may cause updates that don't actually have any changes, it will never lose an update. * * <p>For consistency, all threads that update metrics should finish before getting the final * cumulative values/updates. */ @Experimental(Kind.METRICS) public class MetricsContainer { private final String stepName; private MetricsMap<MetricName, CounterCell> counters = new MetricsMap<>(new MetricsMap.Factory<MetricName, CounterCell>() { @Override public CounterCell createInstance(MetricName unusedKey) { return new CounterCell(); } }); private MetricsMap<MetricName, DistributionCell> distributions = new MetricsMap<>(new MetricsMap.Factory<MetricName, DistributionCell>() { @Override public DistributionCell createInstance(MetricName unusedKey) { return new DistributionCell(); } }); /** * Create a new {@link MetricsContainer} associated with the given {@code stepName}. */ public MetricsContainer(String stepName) { this.stepName = stepName; } /** * Return the {@link CounterCell} that should be used for implementing the given * {@code metricName} in this container. */ public CounterCell getCounter(MetricName metricName) { return counters.get(metricName); } public DistributionCell getDistribution(MetricName metricName) { return distributions.get(metricName); } private <UpdateT, CellT extends MetricCell<?, UpdateT>> ImmutableList<MetricUpdate<UpdateT>> extractUpdates( MetricsMap<MetricName, CellT> cells) { ImmutableList.Builder<MetricUpdate<UpdateT>> updates = ImmutableList.builder(); for (Map.Entry<MetricName, CellT> cell : cells.entries()) { if (cell.getValue().getDirty().beforeCommit()) { updates.add(MetricUpdate.create(MetricKey.create(stepName, cell.getKey()), cell.getValue().getCumulative())); } } return updates.build(); } /** * Return the cumulative values for any metrics that have changed since the last time updates were * committed. */ public MetricUpdates getUpdates() { return MetricUpdates.create( extractUpdates(counters), extractUpdates(distributions)); } private void commitUpdates(MetricsMap<MetricName, ? extends MetricCell<?, ?>> cells) { for (MetricCell<?, ?> cell : cells.values()) { cell.getDirty().afterCommit(); } } /** * Mark all of the updates that were retrieved with the latest call to {@link #getUpdates()} as * committed. */ public void commitUpdates() { commitUpdates(counters); commitUpdates(distributions); } private <UpdateT, CellT extends MetricCell<?, UpdateT>> ImmutableList<MetricUpdate<UpdateT>> extractCumulatives( MetricsMap<MetricName, CellT> cells) { ImmutableList.Builder<MetricUpdate<UpdateT>> updates = ImmutableList.builder(); for (Map.Entry<MetricName, CellT> cell : cells.entries()) { UpdateT update = checkNotNull(cell.getValue().getCumulative()); updates.add(MetricUpdate.create(MetricKey.create(stepName, cell.getKey()), update)); } return updates.build(); } /** * Return the {@link MetricUpdates} representing the cumulative values of all metrics in this * container. */ public MetricUpdates getCumulative() { ImmutableList.Builder<MetricUpdate<Long>> counterUpdates = ImmutableList.builder(); for (Map.Entry<MetricName, CounterCell> counter : counters.entries()) { counterUpdates.add(MetricUpdate.create( MetricKey.create(stepName, counter.getKey()), counter.getValue().getCumulative())); } ImmutableList.Builder<MetricUpdate<DistributionData>> distributionUpdates = ImmutableList.builder(); for (Map.Entry<MetricName, DistributionCell> distribution : distributions.entries()) { distributionUpdates.add(MetricUpdate.create( MetricKey.create(stepName, distribution.getKey()), distribution.getValue().getCumulative())); } return MetricUpdates.create( extractCumulatives(counters), extractCumulatives(distributions)); } }
37.390728
100
0.716259
9467424c1ac18533ee8ef93a89bf01ccf698e765
2,301
/** * netcell-gui - A Swing GUI for netcell ESB * Copyright (C) 2009 Adrian Cristian Ionescu - https://github.com/acionescu * * 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.segoia.netcell.toolkit.actions; import java.awt.Component; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import net.segoia.java.forms.Form; import net.segoia.java.forms.model.ObjectFormModel; import net.segoia.netcell.gui.NetcellGuiController; import net.segoia.netcell.vo.definitions.ConfigurableComponentDefinition; import net.segoia.netcell.vo.definitions.EntityDefinition; public class UpdateCustomComponentAction extends NetcellAbstractAction{ public UpdateCustomComponentAction(NetcellGuiController controller) { super(controller); } /** * */ private static final long serialVersionUID = 3142931681304460109L; @Override protected void actionPerformedDelegate(ActionEvent e) throws Exception { ConfigurableComponentDefinition ccd = (ConfigurableComponentDefinition)e.getSource(); Form form = controller.getFormForObject(ccd, "update"); form.initialize(); JOptionPane pane = new JOptionPane(new JScrollPane((Component)form.getUi().getHolder())); JDialog dialog = pane.createDialog("Configure custom component"); form.getModel().addPropertyChangeListener(new PropertyChangeMonitor()); dialog.setVisible(true); } class PropertyChangeMonitor implements PropertyChangeListener{ public void propertyChange(PropertyChangeEvent evt) { ObjectFormModel fm = (ObjectFormModel)evt.getSource(); controller.onEntityChanged((EntityDefinition)fm.getDataObject()); } } }
36.52381
90
0.777488
ae69160be035ea8ee75fe0e620c9824b81cb725d
422
package com.github.base.widget.status.core; import android.content.Context; import android.view.View; /** * @ClassName: Transport * @Description: java类作用描述 * @Author: crazyandcoder * @email: [email protected] * @CreateDate: 2020/6/27 4:13 PM * @UpdateUser: 更新者 * @UpdateDate: 2020/6/27 4:13 PM * @UpdateRemark: 更新说明 * @Version: 1.0 */ public interface Transport { void order(Context context, View view); }
21.1
43
0.706161
4f61e94f1d60f0480e6b852bf27d064ceddd3ef8
1,495
package camelinaction; import java.util.concurrent.ExecutorService; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.ThreadPoolBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; /** * Demonstrates how to use a custom thread pool with the WireTap EIP pattern. */ public class WireTapTest extends CamelTestSupport { @Test public void testWireTap() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:tap").expectedBodiesReceived("Hello Camel"); template.sendBody("direct:start", "Hello Camel"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { // create a custom thread pool ExecutorService lowPool = new ThreadPoolBuilder(context) .poolSize(1).maxPoolSize(5).build("LowPool"); // which we want the WireTap to use from("direct:start") .log("Incoming message ${body}") .wireTap("direct:tap").executorService(lowPool) .to("mock:result"); from("direct:tap") .log("Tapped message ${body}") .to("mock:tap"); } }; } }
31.808511
77
0.610702
3da35c13201d8ccad8501e1eb795ec7c34b88b53
999
package annotationInteraction; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.util.List; public class SonnetWordPairs { private int sonnet_id; private List<WordPair> antonyms; //private List<WordPair> synonyms; private Rectangle2D sonnet_id_bounds; private TextLayout sonnet_id_layout; public SonnetWordPairs(int sonnet_id, List<WordPair> antonyms){ this.sonnet_id = sonnet_id; this.antonyms = antonyms; } public int getSonnetId(){ return sonnet_id; } public List<WordPair> getAntonymPairs(){ return antonyms; } public void setSonnetIdBounds(Rectangle2D bounds){ sonnet_id_bounds = bounds; } public Rectangle2D getSonnetIdBounds(){ return sonnet_id_bounds; } public void setSonnetIdLayout(TextLayout layout){ sonnet_id_layout = layout; } public TextLayout getSonnetIdLayout(){ return sonnet_id_layout; } }
16.377049
65
0.686687
ddb839292eebc2c0cd9f96cfaa434614367e6c60
721
package net.shiruba.tinkerforge.weatherstation.listener; import com.tinkerforge.BrickletBarometer; import net.shiruba.tinkerforge.weatherstation.data.AirPressureMeasurement; import net.shiruba.tinkerforge.weatherstation.data.AirPressureMeasurementRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class AirPressureListener implements BrickletBarometer.AirPressureListener { @Autowired private AirPressureMeasurementRepository airPressureMeasurementRepository; @Override public void airPressure(int airPressure) { airPressureMeasurementRepository.save(new AirPressureMeasurement(airPressure)); } }
36.05
87
0.84466
9dca5ecf8845a0934e07397eca53a8d878a91364
1,368
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.java.api.common.project.ui.customizer; import org.netbeans.spi.project.ui.CustomizerProvider2; /** * CustomizerProvider enhanced with ability to explicitly close a customizer * that may be currently opened. The close operation is equivalent to * pressing Cancel in customizer dialog. * * @author Petr Somol * @since 1.52 */ public interface CustomizerProvider3 extends CustomizerProvider2 { /** * Close customizer if it is currently opened as if it was cancelled */ void cancelCustomizer(); }
35.076923
76
0.746345
98ae30b5564a6e5ffea97593b221ed035d7d4906
685
package in.cubestack.lib.event.core; import in.cubestack.lib.event.handler.EventHandler; import org.springframework.stereotype.Component; @Component public class EventExtractionHelper { public Class<? extends Event> getEventsManagedBy(EventHandler eventHandler) { Class eventHandlerClass = eventHandler.getClass(); if (!eventHandlerClass.isAnnotationPresent(EventConsumer.class)) { throw new RuntimeException("Annotation @EventConsumer required on class " + eventHandler.getClass()); } EventConsumer eventConsumer = (EventConsumer) eventHandlerClass.getAnnotation(EventConsumer.class); return eventConsumer.value(); } }
34.25
113
0.750365
f6156408e3bb55ec2954334670ecd0eca92a20bc
596
package de.thb.paf.scrabblefactory.models.assets; /** * Enumeration of all supported asset file types. * * @author Dominic Schiller - Technische Hochschule Brandenburg * @version 1.0 * @since 1.0 */ public enum AssetFileType { JSON(".json"), XML(".xml"), TEXTURE_ATLAS(".atlas"), TRUE_TYPE_FONT(".ttf"); /** * Private Constructor * @param fileEnding The associated file ending */ AssetFileType(String fileEnding) { this.fileEnding = fileEnding; } /** * The associated file ending */ public final String fileEnding; }
19.866667
63
0.637584
d8c70431ffd71f9e2ccf74199ed19f324007a0f8
4,307
package mod.azure.doom.recipes; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.tuple.Pair; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipeSerializer; import net.minecraft.item.crafting.Ingredient; import net.minecraft.item.crafting.ShapedRecipe; import net.minecraft.network.PacketBuffer; import net.minecraft.util.JSONUtils; import net.minecraft.util.ResourceLocation; import net.minecraftforge.registries.ForgeRegistryEntry; public class GunRecipeSerializer extends ForgeRegistryEntry<IRecipeSerializer<?>> implements IRecipeSerializer<GunTableRecipe> { private static List<Pair<Ingredient, Integer>> getIngredients(String pattern, Map<String, Pair<Ingredient, Integer>> keys, int width) { List<Pair<Ingredient, Integer>> pairList = new ArrayList<>(); for (int i = 0; i < 5; i++) { pairList.add(Pair.of(Ingredient.EMPTY, 0)); } Set<String> set = Sets.newHashSet(keys.keySet()); set.remove(" "); for (int i = 0; i < pattern.length(); ++i) { String key = pattern.substring(i, i + 1); Ingredient ingredient = keys.get(key).getKey(); if (ingredient == null) { throw new JsonSyntaxException( "Pattern references symbol '" + key + "' but it's not defined in the key"); } set.remove(key); pairList.set(i, Pair.of(ingredient, keys.get(key).getRight())); } if (!set.isEmpty()) { throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + set); } else { return pairList; } } private static Map<String, Pair<Ingredient, Integer>> getComponents(JsonObject json) { Map<String, Pair<Ingredient, Integer>> map = Maps.newHashMap(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { String key = entry.getKey(); JsonElement jsonElement = entry.getValue(); if (key.length() != 1) { throw new JsonSyntaxException( "Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 String only)."); } if (" ".equals(key)) { throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); } map.put(key, Pair.of(Ingredient.fromJson(jsonElement), JSONUtils.getAsInt(jsonElement.getAsJsonObject(), "count", 1))); } map.put(" ", Pair.of(Ingredient.EMPTY, 0)); return map; } @SuppressWarnings("unchecked") @Override public GunTableRecipe fromJson(ResourceLocation ResourceLocation, JsonObject jsonObject) { String pattern = JSONUtils.getAsString(jsonObject, "pattern"); Map<String, Pair<Ingredient, Integer>> map = getComponents(JSONUtils.getAsJsonObject(jsonObject, "key")); List<Pair<Ingredient, Integer>> pairList = getIngredients(pattern, map, pattern.length()); if (pairList.isEmpty()) { throw new JsonParseException("No ingredients for gun table recipe"); } else if (pairList.size() > 5) { throw new JsonParseException("Too many ingredients for gun table recipe"); } else { ItemStack itemStack = ShapedRecipe.itemFromJson(JSONUtils.getAsJsonObject(jsonObject, "result")); return new GunTableRecipe(ResourceLocation, pairList.toArray(new Pair[0]), itemStack); } } @SuppressWarnings("unchecked") @Override public GunTableRecipe fromNetwork(ResourceLocation ResourceLocation, PacketBuffer PacketBuffer) { Pair<Ingredient, Integer>[] pairs = new Pair[5]; for (int j = 0; j < 5; ++j) { Ingredient ingredient = Ingredient.fromNetwork(PacketBuffer); int count = PacketBuffer.readInt(); pairs[j] = Pair.of(ingredient, count); } ItemStack output = PacketBuffer.readItem(); return new GunTableRecipe(ResourceLocation, pairs, output); } @Override public void toNetwork(PacketBuffer PacketBuffer, GunTableRecipe gunTableRecipe) { for (int i = 0; i < 5; i++) { Pair<Ingredient, Integer> pair = gunTableRecipe.ingredients[i]; Ingredient ingredient = pair.getLeft(); int count = pair.getRight(); ingredient.toNetwork(PacketBuffer); PacketBuffer.writeInt(count); } PacketBuffer.writeItem(gunTableRecipe.output); } }
34.733871
107
0.726956
7ec7ba4d9cd4f36c86c93719f7da2d86dbfac3cf
16,130
package main.java.model; import java.awt.*; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; /** * Uses the minimax algorithm with alpha-beta pruning and a heuristic to determine the best available move for the AI. * * @author tp275 */ public class AI { private final MoveGenerator moveGenerator = new MoveGenerator(); private static final int[][] positionWeightLookup = {{0, 4, 0, 4, 0, 4, 0, 4}, {4, 0, 3, 0, 3, 0, 3, 0}, {0, 3, 0, 2, 0, 2, 0, 4}, {4, 0, 2, 0, 1, 0, 3, 0}, {0, 3, 0, 1, 0, 2, 0, 4}, {4, 0, 2, 0, 2, 0, 3, 0}, {0, 3, 0, 3, 0, 3, 0, 4}, {4, 0, 4, 0, 4, 0, 4, 0}}; public static final int POSITIVE_INFINITY = 2000000000; public static final int NEGATIVE_INFINITY = -2000000000; /* /** * Runs the minimax algorithm on all moves given in the list parameter, and returns the best one * @param board the current game state * @param depth the tree depth to generate and search * @param moves A list of moves to run minimax on. Here this should be all currently available moves for the ai * @return the best move to play from the moves list, as evaluated by the minimax algorithm * public Move play(Board board, int depth, ArrayList<Move> moves) { HashMap<Double, Move> scores = new HashMap<>(); for (Move move : moves) { scores.put(minimax(board.updateLocation(move), depth, NEGATIVE_INFINITY, POSITIVE_INFINITY, 'w', move), move); } return scores.get(Collections.max(scores.keySet())); } */ public Move playTimeLimited(Board board, int timeLimitSeconds, ArrayList<Move> moves, char color) { moves = moveGenerator.updateValidMovesWithJumps(board, moves, color); LocalTime localTimeLimit = LocalTime.now().plusSeconds(timeLimitSeconds); System.out.println("Colour = " + color); HashMap<Integer, Move> scores = getScores(board, localTimeLimit, moves, color); // Move bestMove = color == 'w' ? scores.get(Collections.max(scores.keySet())) : scores.get(Collections.min(scores.keySet())); Move bestMove = scores.get(Collections.max(scores.keySet())); System.out.println("Selected move: " + bestMove); return bestMove; } private HashMap<Integer, Move> getScores(Board board, LocalTime localTimeLimit, ArrayList<Move> moves, char color) { for (Move move : moves) { System.out.print("{" + move + "} "); } System.out.println(); HashMap<Integer, Move> scores = new HashMap<>(); if (moves.size() == 0) { System.out.println("No moves to evaluate"); scores.put(0, new Move(new Point(), new Point())); return scores; } if (moves.size() == 1) { System.out.println("Only one move to take!"); scores.put(1, moves.get(0)); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } return scores; } for (int depth = 1; depth < POSITIVE_INFINITY; depth++) { HashMap<Integer, Move> currentDepthScores = new HashMap<>(); System.out.print("Depth = " + depth + ": "); for (Move move : moves) { if (LocalTime.now().isBefore(localTimeLimit)) { int result = (color == 'w') ? minimaxWhiteMaximising(board.updateLocation(move), depth, NEGATIVE_INFINITY, POSITIVE_INFINITY, 'r') : minimaxRedMaximising(board.updateLocation(move), depth, NEGATIVE_INFINITY, POSITIVE_INFINITY, 'w'); currentDepthScores.put(result, move); System.out.print(result + ", "); } else { if (!scores.isEmpty()) { System.out.println("Time up!\nBest score: " + Collections.max(scores.keySet())); } return scores; } } scores = currentDepthScores; if (!currentDepthScores.isEmpty()) { System.out.println("Best score for this depth: " + Collections.max(currentDepthScores.keySet())); } } return null; } private void checkValue(double value, String valueName) { if (value > POSITIVE_INFINITY) { System.out.println(valueName + " was above positive infinity"); } else if (value < NEGATIVE_INFINITY) { System.out.println(valueName + " was below negative infinity"); } } private void checkValues(double alpha, double beta, int checkNumber) { checkValue(alpha, "alpha"); checkValue(beta, "beta"); } private void checkValues(double alpha, double beta, double bestValue, int checkNumber) { checkValue(alpha, "alpha"); checkValue(beta, "beta"); checkValue(bestValue, "bestValue"); } private void checkValues(double alpha, double beta, double eval, double bestValue, int checkNumber) { checkValue(alpha, "alpha"); checkValue(beta, "beta"); checkValue(eval, "eval"); checkValue(bestValue, "bestValue"); } /** * The minimax algorithm, including alpha-beta pruning. * @param board the game state * @param depth the max depth to generate the tree * @param alpha alpha pruning parameter * @param beta beta pruning parameter * @param color essentially MIN/MAX player, here 'w' == MAX * @return the best score possible for the AI (given that the human plays with the same technique!) */ private int minimaxWhiteMaximising(Board board, int depth, double alpha, double beta, char color) { if (depth == 0) { // if at depth limit return weightedHeuristic(board); } int win = board.winCheck(); if (win != 0) { // if at leaf node return win; } if (color == 'w') { // if player == MAX int bestValue = NEGATIVE_INFINITY; ArrayList<Move> children = moveGenerator.findValidMoves(board, color); if (children.isEmpty()) { return NEGATIVE_INFINITY; } children = moveGenerator.updateValidMovesWithJumps(board, children, color); for (Move m : children) { // for each child of node int eval; Board childBoard = board.updateLocation(m); // (make child) // recursively call minimaxWhiteMaximising with MIN eval = minimaxWhiteMaximising(childBoard, depth-1, alpha, beta, 'r'); bestValue = Math.max(bestValue, eval); // best value is max alpha = Math.max(alpha, bestValue); // alpha is max if (alpha > beta) { // pruning break; } } return bestValue; } if (color == 'r') { // if player == MIN int bestValue = POSITIVE_INFINITY; ArrayList<Move> children = moveGenerator.findValidMoves(board, color); if (children.isEmpty()) { return POSITIVE_INFINITY; } children = moveGenerator.updateValidMovesWithJumps(board, children, color); for (Move m : children) { // for each child of node int eval; Board childBoard = board.updateLocation(m); // (make child) // recursively call minimaxWhiteMaximising with MAX eval = minimaxWhiteMaximising(childBoard, depth-1, alpha, beta, 'w'); bestValue = Math.min(bestValue, eval); // best value is min beta = Math.min(beta, bestValue); // beta is min if (alpha > beta) { // pruning break; } } return bestValue; } System.out.println("minimaxWhiteMaximising did not return correctly"); return 0; } private int minimaxRedMaximising(Board board, int depth, double alpha, double beta, char color) { if (depth == 0) { // if at depth limit return pieceAndRowHeuristicFlipped(board); } int win = board.winCheck(); if (win != 0) { // if at leaf node return -win; } if (color == 'r') { // if player == MAX int bestValue = NEGATIVE_INFINITY; ArrayList<Move> children = moveGenerator.findValidMoves(board, color); if (children.isEmpty()) { return NEGATIVE_INFINITY; } children = moveGenerator.updateValidMovesWithJumps(board, children, color); for (Move m : children) { // for each child of node int eval; Board childBoard = board.updateLocation(m); // (make child) // recursively call minimaxWhiteMaximising with MIN eval = minimaxRedMaximising(childBoard, depth-1, alpha, beta, 'w'); bestValue = Math.max(bestValue, eval); // best value is max alpha = Math.max(alpha, bestValue); // alpha is max if (alpha > beta) { // pruning break; } } return bestValue; } if (color == 'w') { // if player == MIN int bestValue = POSITIVE_INFINITY; ArrayList<Move> children = moveGenerator.findValidMoves(board, color); if (children.isEmpty()) { return POSITIVE_INFINITY; } children = moveGenerator.updateValidMovesWithJumps(board, children, color); for (Move m : children) { // for each child of node int eval; Board childBoard = board.updateLocation(m); // (make child) // recursively call minimaxWhiteMaximising with MAX eval = minimaxRedMaximising(childBoard, depth-1, alpha, beta, 'r'); bestValue = Math.min(bestValue, eval); // best value is min beta = Math.min(beta, bestValue); // beta is min if (alpha > beta) { // pruning break; } } return bestValue; } System.out.println("minimaxWhiteMaximising did not return correctly"); return 0; } /** * The heuristic: a measure of how good the given board state is for the given colour. * Currently takes into account whether the player has won and their piece advantage (counting kings as 2) * @param board the board state to evaluate * @return int, as a measure of how good the given board state is for the given colour */ private int heuristic(Board board) { // +2 for pawn, +4 for king int whiteState = (board.getWhitePieces() + board.getWhiteKings()) * 2; int redState = (board.getRedPieces() + board.getRedKings()) * 2; // Piece[][] boardArray = board.getBoard(); // for (int i = 0; i < 8; i++) { // for (int j = (i + 1) % 2; j < 8; j += 2) { // Piece piece = boardArray[i][j]; // if (piece != null && (j == 0 || j == 7)) { // if (piece.getColour() == 'w') { // +1 for piece on edge of board // whiteState += 1; // } else { // redState += 1; // } // } // } // } return whiteState - redState; } private int weightedHeuristic(Board board) { int redState = 0; int whiteState = 0; Piece[][] boardArray = board.getBoard(); for (int i = 0; i < 8; i++) { for (int j = (i + 1) % 2; j < 8; j += 2) { Piece piece = boardArray[i][j]; if (piece != null) { if (piece.getColour() == 'r') { redState += piece.isKing() ? (5 * positionWeightLookup[i][j]) : (3 * positionWeightLookup[i][j]); } else { whiteState += piece.isKing() ? (5 * positionWeightLookup[i][j]) : (3 * positionWeightLookup[i][j]); } } } } return whiteState - redState; } private int pieceAndRowHeuristic(Board board) { int redState = 0; int whiteState = 0; Piece[][] boardArray = board.getBoard(); for (int i = 0; i < 8; i++) { for (int j = (i + 1) % 2; j < 8; j += 2) { Piece piece = boardArray[i][j]; if (piece != null) { if (piece.getColour() == 'r') { redState += piece.isKing() ? 14 : (5 + (7 - i)); } else { whiteState += piece.isKing() ? 14 : (5 + i); } } } } return whiteState - redState; } private int pieceAndRowHeuristicFlipped(Board board) { int redState = 0; int whiteState = 0; Piece[][] boardArray = board.getBoard(); for (int i = 0; i < 8; i++) { for (int j = (i + 1) % 2; j < 8; j += 2) { Piece piece = boardArray[i][j]; if (piece != null) { if (piece.getColour() == 'r') { redState += piece.isKing() ? 14 : (5 + (7 - i)); } else { whiteState += piece.isKing() ? 14 : (5 + i); } } } } return redState - whiteState; } private int pieceAndRowAndWeightedHeuristic(Board board) { int redState = 0; int whiteState = 0; Piece[][] boardArray = board.getBoard(); for (int i = 0; i < 8; i++) { for (int j = (i + 1) % 2; j < 8; j += 2) { Piece piece = boardArray[i][j]; if (piece != null) { if (piece.getColour() == 'r') { redState += piece.isKing() ? (14 * positionWeightLookup[i][j]) : ((5 + (8 - i)) * positionWeightLookup[i][j]); } else { whiteState += piece.isKing() ? (14 * positionWeightLookup[i][j]) : ((5 + i) * positionWeightLookup[i][j]); } } } } return whiteState - redState; } private int complexHeuristic(Board board, char color) { double kingFactor = 1.5; double cellFactor = 0.75; int redCellWeight = 0; int whiteCellWeight = 0; int redKings = board.getRedKings(); int whiteKings = board.getWhiteKings(); int redPieces = board.getRedPieces() - board.getRedKings(); int whitePieces = board.getWhitePieces() - board.getWhiteKings(); for (int i = 0; i < 8; i++) { for (int j = (i + 1) % 2; j < 8; j += 2) { if (board.getBoard()[i][j] != null) { if (board.getBoard()[i][j].getColour() == 'r') { redCellWeight += positionWeightLookup[i][j]; } else { whiteCellWeight += positionWeightLookup[i][j]; } } } } int trade; if (board.getRedPieces() > board.getWhitePieces()) { trade = 24 - board.getPieces(); } else { trade = 24 + board.getPieces(); } return (int) ((whitePieces-redPieces) + (kingFactor * (whiteKings-redKings)) + (cellFactor * (whiteCellWeight-redCellWeight)) * 1000) + trade; } }
40.835443
150
0.512709
9dbadd248c56b885f113dc37533e8fe167945f50
2,507
package com.jmall.util; import com.jmall.common.RedisCluster; import lombok.extern.slf4j.Slf4j; import redis.clients.jedis.JedisCluster; @Slf4j public class RedisClusterUtil { public static String set(String key,String value) { JedisCluster jedisCluster = null; String result = null; try { jedisCluster = RedisCluster.getJedisCluster(); result = jedisCluster.set(key,value); } catch (Exception e) { log.error("set:key{},value:{} error",key,value,e); } return result; } public static String get(String key) { JedisCluster jedisCluster = null; String result = null; try { jedisCluster = RedisCluster.getJedisCluster(); result = jedisCluster.get(key); } catch (Exception e) { log.error("get:key{} error", key, e); } return result; } public static String setEx(String key,String value,int exTime) { JedisCluster jedisCluster = null; String result = null; try { jedisCluster = RedisCluster.getJedisCluster(); result = jedisCluster.setex(key,exTime,value); } catch (Exception e) { log.error("setEx:key{},exTime:{},value:{} error",key,exTime,value,e); } return result; } public static Long expire(String key,int exTime) { JedisCluster jedisCluster = null; Long result = null; try { jedisCluster = RedisCluster.getJedisCluster(); result = jedisCluster.expire(key,exTime); } catch (Exception e) { log.error("expire:key{},exTime:{} error",key,exTime,e); } return result; } public static Long del(String key) { JedisCluster jedisCluster = null; Long result = null; try { jedisCluster = RedisCluster.getJedisCluster(); result = jedisCluster.del(key); } catch (Exception e) { log.error("delete:key{} error",key,e); } return result; } public static void main(String[] args) { JedisCluster jedisCluster = RedisCluster.getJedisCluster(); RedisClusterUtil.set("keyTest","value"); String value = RedisClusterUtil.get("keyTest"); RedisClusterUtil.setEx("keyex","valueex",60*10); RedisClusterUtil.expire("keyTest",60*20); RedisClusterUtil.del("keyTest"); System.out.println("end"); } }
28.168539
81
0.588751
cc0725c2ae1321d1d471efa9f06d1a314fe6a20b
701
package org.accounting.system.repositories.metric; import org.accounting.system.entities.Metric; import org.accounting.system.repositories.modulators.AccessControlModulator; import org.accounting.system.repositories.modulators.AccessEntityModulator; import org.bson.types.ObjectId; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class MetricAccessEntityRepository extends AccessEntityModulator<Metric, ObjectId> { @Inject MetricAccessControlRepository metricAccessControlRepository; @Override public AccessControlModulator<Metric, ObjectId> accessControlModulator() { return metricAccessControlRepository; } }
31.863636
91
0.831669
5f0acf1191282e4901210ae6d436c93d33c79401
3,294
package com.github.ormfux.common.utils.object.testequalsbuilder; import org.junit.Test; import com.github.ormfux.common.utils.object.EqualsBuilder; public class ConstructorTest extends AbstractEqualsBuilderTest { @Test public void testInheritanceRelation() { MockType1 mock = new MockType1(); MockType2 mock2 = new MockType2(); EqualsBuilder<?> builder = new EqualsBuilder<>(mock, mock2); checkBuilderState(builder, "EQUAL"); builder = new EqualsBuilder<>(mock, mock2, true); checkBuilderState(builder, "EQUAL"); builder = new EqualsBuilder<>(mock, mock2, false); checkBuilderState(builder, "NOT_EQUAL"); builder = new EqualsBuilder<>(mock2, mock); checkBuilderState(builder, "NEVER_EQUAL"); builder = new EqualsBuilder<>(mock2, mock, true); checkBuilderState(builder, "NEVER_EQUAL"); builder = new EqualsBuilder<>(mock2, mock, false); checkBuilderState(builder, "NEVER_EQUAL"); } @Test public void testSameType() { MockType1 mock = new MockType1(); MockType1 mock2 = new MockType1(); EqualsBuilder<?> builder = new EqualsBuilder<>(mock, mock2); checkBuilderState(builder, "EQUAL"); builder = new EqualsBuilder<>(mock, mock2, true); checkBuilderState(builder, "EQUAL"); builder = new EqualsBuilder<>(mock, mock2, false); checkBuilderState(builder, "NOT_EQUAL"); } @Test public void testSameObject() { MockType1 mock = new MockType1(); EqualsBuilder<?> builder = new EqualsBuilder<>(mock, mock); checkBuilderState(builder, "ALWAYS_EQUAL"); builder = new EqualsBuilder<>(mock, mock, true); checkBuilderState(builder, "ALWAYS_EQUAL"); builder = new EqualsBuilder<>(mock, mock, false); checkBuilderState(builder, "ALWAYS_EQUAL"); } @Test public void testUnrelatedTypes() { MockType1 mock = new MockType1(); MockType3 mock3 = new MockType3(); EqualsBuilder<?> builder = new EqualsBuilder<>(mock, mock3); checkBuilderState(builder, "NEVER_EQUAL"); builder = new EqualsBuilder<>(mock, mock3, true); checkBuilderState(builder, "NEVER_EQUAL"); builder = new EqualsBuilder<>(mock, mock3, false); checkBuilderState(builder, "NEVER_EQUAL"); } @Test public void testNullComparee() { MockType1 mock = new MockType1(); EqualsBuilder<?> builder = new EqualsBuilder<>(mock, null); checkBuilderState(builder, "NEVER_EQUAL"); builder = new EqualsBuilder<>(mock, null, true); checkBuilderState(builder, "NEVER_EQUAL"); builder = new EqualsBuilder<>(mock, null, false); checkBuilderState(builder, "NEVER_EQUAL"); } @Test(expected = NullPointerException.class) public void testNullSourceValue() { new EqualsBuilder<>(null, new MockType1()); } }
32.613861
70
0.586217
0ffc0d5ca0825d3f9b2b857f164538ff00a4c70f
1,274
package com.golike.myapplication.customviews.hencoder; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; /** * Created by admin on 2018/2/6. */ public class PropetyAnimationView extends View { Paint paint, textPaint; float progress = 0.0f; public PropetyAnimationView(Context context) { super(context); } { paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.parseColor("#8B1A1A")); paint.setStrokeWidth(20.0f); textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(20.0f); textPaint.setColor(Color.parseColor("#8B1A1A")); } public float getProgress() { return progress; } public void setProgress(float progress) { this.progress = progress; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawArc(100, 100, 300, 300, 180, this.progress, false, paint); canvas.drawText(Math.round(100 * this.progress / 360) + "%", 180, 210, textPaint); } }
25.48
91
0.632653
6949622484307e1849d5641280e4dc4303bbdbcd
188
package org.snomed.authoringtemplate.domain.logical; public interface HasCardinality { void setCardinalityMin(String cardinalityMin); void setCardinalityMax(String cardinalityMax); }
20.888889
52
0.835106
f4e6d3b9a93330ecdcc06994a4c4079ca5a67a12
3,604
/* Copyright 2016 Urban Airship and Contributors */ package com.urbanairship.push.notifications; import android.content.Context; import android.graphics.BitmapFactory; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.v4.app.NotificationCompat; import com.urbanairship.Logger; import com.urbanairship.json.JsonException; import com.urbanairship.json.JsonMap; import com.urbanairship.json.JsonValue; import com.urbanairship.push.PushMessage; import com.urbanairship.util.UAStringUtil; /** * Notification builder extender to add the public notification defined by a {@link PushMessage}. */ public class PublicNotificationExtender implements NotificationCompat.Extender { static final String TITLE_KEY = "title"; static final String SUMMARY_KEY = "summary"; static final String ALERT_KEY = "alert"; private final Context context; private final PushMessage message; private int accentColor; private int smallIconId; private int largeIconId; /** * Default constructor. * * @param context The application context. * @param message The push message. */ public PublicNotificationExtender(@NonNull Context context, @NonNull PushMessage message) { this.context = context; this.message = message; this.smallIconId = context.getApplicationInfo().icon; } /** * Sets the accent color. * * @param accentColor The notification's accent color. * @return The PublicNotificationExtender to chain calls. */ public PublicNotificationExtender setAccentColor(@ColorInt int accentColor) { this.accentColor = accentColor; return this; } /** * Sets the small icon. * * @param smallIcon The small icon. * @return The PublicNotificationExtender to chain calls. */ public PublicNotificationExtender setSmallIcon(@DrawableRes int smallIcon) { this.smallIconId = smallIcon; return this; } /** * Sets the large icon. * * @param largeIcon The large icon. * @return The PublicNotificationExtender to chain calls. */ public PublicNotificationExtender setLargeIcon(@DrawableRes int largeIcon) { this.largeIconId = largeIcon; return this; } @Override public NotificationCompat.Builder extend(NotificationCompat.Builder builder) { if (UAStringUtil.isEmpty(message.getPublicNotificationPayload())) { return builder; } try { JsonMap jsonMap = JsonValue.parseString(message.getPublicNotificationPayload()).optMap(); NotificationCompat.Builder publicBuilder = new NotificationCompat.Builder(context) .setContentTitle(jsonMap.opt(TITLE_KEY).getString("")) .setContentText(jsonMap.opt(ALERT_KEY).getString("")) .setColor(accentColor) .setAutoCancel(true) .setSmallIcon(smallIconId); if (largeIconId != 0) { publicBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), largeIconId)); } if (jsonMap.containsKey(SUMMARY_KEY)) { publicBuilder.setSubText(jsonMap.opt(SUMMARY_KEY).getString("")); } builder.setPublicVersion(publicBuilder.build()); } catch (JsonException e) { Logger.error("Failed to parse public notification.", e); } return builder; } }
32.178571
110
0.675361
1b7c9580521d9c06d2114d5abf8e66ccfe9a4285
2,747
package covid.vaccine.openapi; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import org.jsoup.Jsoup; import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; /** * https://www.data.go.kr/data/15078166/openapi.do GET Vaccinated Stats by use * OpenAPI from https://nip.kdca.go.kr/irgd/cov19stats.do?list=all : XML * https://ncv.kdca.go.kr/eng/ */ public class VaccinatedStatus extends Object { /** * https://ncv.kdca.go.kr/eng/ * * @firstCnt "First Dose Administered" * @secondCnt "Fully Vaccinated" * @thirdCnt "Booster Dose Administered" */ private String OpenAPIUrl = "https://nip.kdca.go.kr/irgd/cov19stats.do"; private Response response = getDataFromOpenAPI(); java.util.Date dateTime = parseTime(); private Response getDataFromOpenAPI() { try { return Jsoup.connect(OpenAPIUrl).method(Method.GET).execute(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return response; } private java.util.Date parseTime() { try { return new SimpleDateFormat("zzz;yyyy.MM.dd HH:mm:ss") .parse("KST;" + (Jsoup.parse(response.body()).getElementsByTag("dataTime").text())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return dateTime; } public class Cnt extends Object { Cnt(String tagName) { Jsoup.parse(response.body()).getElementsByTag(tagName).forEach((a) -> { String tpcd = a.parent().getElementsByTag("tpcd").text().replaceAll("[^a-zA-Z]", ""); switch (tpcd.charAt(0)) { case 'A': this.byDays.inToday = a.text(); break; case 'B': this.byDays.total.onYesterday = a.text(); break; case 'C': this.byDays.total.onToday = a.text(); break; } }); } public class Vaccinated extends Object { public String inToday = new String(); public class Total extends Object { public String onToday = new String(); public String onYesterday = new String(); } public Total total = new Total(); } public Vaccinated byDays = new Vaccinated(); } public Cnt firstCnt = new Cnt("firstCnt"); public Cnt secondCnt = new Cnt("secondCnt"); public Cnt thirdCnt = new Cnt("thirdCnt"); }
31.574713
104
0.560248
71759928efa8d7684f6913364ac2b16e69a7babb
653
package io; public class ConsoleIO implements IO { @Override public void print(String l) { System.out.print(l); } public int readInt() { return Console.readInt("Saisissez un entier :"); } public boolean readBool() { int i; do { i = Console.readInt("Saisissez un boolean (0 pour false, 1 pour true) :"); } while (i != 0 && i != 1); return (i == 1); } public char readChar() { return Console.readChar("Saisissez un caractère :"); } public String readString() { return Console.readLine("Saisissez une chaîne de caractères :"); } }
22.517241
86
0.562021
ceaf45fc2f53bbee50cbdfccc23c0492c5e8b66e
3,094
package com.zeus.tool.cogen.design; import java.util.List; import com.zeus.persist.annotation.Table; import com.zeus.persist.util.MapUtil; import com.zeus.tool.cogen.annotation.HibernateSupport; import com.zeus.tool.cogen.annotation.JDBCSupport; import com.zeus.tool.cogen.annotation.MarkDelete; import com.zeus.tool.cogen.annotation.MybatisSupport; import com.zeus.tool.cogen.annotation.SpringMVCSupport; import com.zeus.tool.cogen.annotation.SpringSupport; import com.zeus.tool.cogen.annotation.StrutsSupport; public class DesignEntity { public Class<?> clazz; public String clazzPackage; public String moduleName; public String clazzName; public String instanceName; public String tableName; public String idType; public Boolean markDelete; public String nameProperty; public List<DesignField> dFields; public Boolean springMVCSupport; public Boolean strutsSupport; public Boolean springSupport; public Boolean mybatisSupport; public Boolean hibernateSupport; public Boolean jdbcSupport; private DesignEntity() { } /** * 默认的解析方法,通过注解的方式来解析 * @param clazz * @return */ public static DesignEntity resolve(Class<?> clazz) { DesignEntity dEntity = new DesignEntity(); dEntity.clazzPackage = clazz.getAnnotation(com.zeus.tool.cogen.annotation.Package.class) != null ? clazz.getAnnotation(com.zeus.tool.cogen.annotation.Package.class).name() : ""; dEntity.moduleName = dEntity.clazzPackage.substring(dEntity.clazzPackage.lastIndexOf(".") + 1, dEntity.clazzPackage.length()); dEntity.clazzName = clazz.getSimpleName(); dEntity.instanceName = ("" + dEntity.clazzName.charAt(0)).toLowerCase() + dEntity.clazzName.substring(1, dEntity.clazzName.length()); dEntity.tableName = clazz.getAnnotation(Table.class) != null ? clazz.getAnnotation(Table.class).name() : MapUtil.objectToTable(clazz); dEntity.idType = "Long"; try { dEntity.idType = clazz.getDeclaredField("id").getType().getName(); } catch (NoSuchFieldException e) { try { dEntity.idType = clazz.getDeclaredField("code").getType().getName(); } catch (NoSuchFieldException | SecurityException e1) { e1.printStackTrace(); } } catch (SecurityException e) { e.printStackTrace(); } dEntity.dFields = DesignField.resolve(clazz); for(DesignField dField:dEntity.dFields){ if(dField.viewProperties!=null&&dField.viewProperties.name){ dEntity.nameProperty = dField.fieldName; break; } } dEntity.markDelete = clazz.getAnnotation(MarkDelete.class) != null; dEntity.springMVCSupport = clazz.getAnnotation(SpringMVCSupport.class) != null; dEntity.strutsSupport = clazz.getAnnotation(StrutsSupport.class) != null; dEntity.springSupport = clazz.getAnnotation(SpringSupport.class) != null; dEntity.mybatisSupport = clazz.getAnnotation(MybatisSupport.class) != null; dEntity.hibernateSupport = clazz.getAnnotation(HibernateSupport.class) != null; dEntity.jdbcSupport = clazz.getAnnotation(JDBCSupport.class) != null; return dEntity; } }
35.159091
105
0.740142
d9da5f0c1685bca9e92bce3433d729c40402065d
348
package com.gtc.opportunity.trader.repository.stat.general; import com.gtc.opportunity.trader.domain.stat.general.XoTradeStatTotal; import org.springframework.stereotype.Repository; /** * Created by Valentyn Berezin on 26.02.18. */ @Repository public interface XoTradeStatTotalRepository extends BaseXoTradeStatRepository<XoTradeStatTotal> { }
29
97
0.827586
e9ab039d09f2cd8f0d3f482da98efcad3e338683
34,846
/******************************************************************************* * This program and the accompanying materials are made available under the terms of the MIT License available at * https://opensource.org/licenses/MIT *******************************************************************************/ package com.net2plan.niw; import java.awt.geom.Point2D; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import com.net2plan.interfaces.networkDesign.Link; import com.net2plan.interfaces.networkDesign.Net2PlanException; import com.net2plan.interfaces.networkDesign.Node; import com.net2plan.interfaces.networkDesign.Resource; import com.net2plan.niw.WNetConstants.WTYPE; /** * This class represents a node in the network, capable of initiating or ending IP and WDM links, as well as lightpaths * and service chains */ /** * @author Pablo * */ public class WNode extends WAbstractNetworkElement { // public enum OPTICALSWITCHTYPE // { // ROADM ( // e->new TreeSet<> (Arrays.asList(e)) , // add // e->new TreeSet<> (), // drop // (e1,e2)->new TreeSet<> (Arrays.asList(e2)), // express // e->new TreeSet<> () // unavoidable: propagates whatever you do // ) // , FILTERLESS_DROPANDWASTENOTDIRECTIONLESS ( // e->new TreeSet<> (Arrays.asList(e)), // add // e->e.getB().getOutgoingFibers().stream().filter(ee->e.isBidirectional()? !ee.equals(e.getBidirectionalPair()) : true).collect(Collectors.toCollection(TreeSet::new)), // drop // (e1,e2)->e1.getB().getOutgoingFibers().stream().filter(ee->e1.isBidirectional()? !ee.equals(e1.getBidirectionalPair()) : true).collect(Collectors.toCollection(TreeSet::new)), // express // e->e.getB().getOutgoingFibers().stream().filter(ee->e.isBidirectional()? !ee.equals(e.getBidirectionalPair()) : true).collect(Collectors.toCollection(TreeSet::new)) // unavoidable: propagates whatever you do // ); // // private final Function<WFiber , SortedSet<WFiber>> outFibersIfAddToOutputFiber; // private final Function<WFiber , SortedSet<WFiber>> outFibersIfDropFromInputFiber; // private final BiFunction<WFiber , WFiber , SortedSet<WFiber>> outFibersIfExpressFromInputToOutputFiber; // private final Function<WFiber , SortedSet<WFiber>> outFibersUnavoidablePropagationFromInputFiber; // // private OPTICALSWITCHTYPE(Function<WFiber, SortedSet<WFiber>> outFibersIfAddToOutputFiber, // Function<WFiber, SortedSet<WFiber>> outFibersIfDropFromInputFiber, // BiFunction<WFiber, WFiber, SortedSet<WFiber>> outFibersIfExpressFromInputToOutputFiber, // Function<WFiber, SortedSet<WFiber>> outFibersUnavoidablePropagationFromInputFiber) // { // this.outFibersIfAddToOutputFiber = outFibersIfAddToOutputFiber; // this.outFibersIfDropFromInputFiber = outFibersIfDropFromInputFiber; // this.outFibersIfExpressFromInputToOutputFiber = outFibersIfExpressFromInputToOutputFiber; // this.outFibersUnavoidablePropagationFromInputFiber = outFibersUnavoidablePropagationFromInputFiber; // } // public static OPTICALSWITCHTYPE getDefault () { return ROADM; } // public boolean isRoadm () { return this == ROADM; } // public String getShortName () { return isRoadm()? "ROADM" : "Filterless"; } // public boolean isDropAndWaste () { return this == OPTICALSWITCHTYPE.FILTERLESS_DROPANDWASTENOTDIRECTIONLESS; } // public Function<WFiber, SortedSet<WFiber>> getOutFibersIfAddToOutputFiber() // { // return this.outFibersIfAddToOutputFiber; // } // public Function<WFiber, SortedSet<WFiber>> getOutFibersIfDropFromInputFiber() // { // return this.outFibersIfDropFromInputFiber; // } // public BiFunction<WFiber, WFiber, SortedSet<WFiber>> getOutFibersIfExpressFromInputToOutputFiber() // { // return this.outFibersIfExpressFromInputToOutputFiber; // } // public Function<WFiber, SortedSet<WFiber>> getOutFibersUnavoidablePropagationFromInputFiber() // { // return this.outFibersUnavoidablePropagationFromInputFiber; // } // } static final String ATTNAMECOMMONPREFIX = NIWNAMEPREFIX + "Node_"; private static final String ATTNAMESUFFIX_TYPE = "type"; private static final String ATTNAMESUFFIX_ISCONNECTEDTOCORE = "isConnectedToNetworkCore"; private static final String RESOURCETYPE_CPU = WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER + "CPU"; private static final String RESOURCETYPE_RAM = WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER + "RAM"; private static final String RESOURCETYPE_HD = WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER + "HD"; private static final String ATTNAMESUFFIX_ARBITRARYPARAMSTRING = "ArbitraryString"; private static final String ATTNAME_OPTICALSWITCHTYPE = "ATTNAME_OPTICALSWITCHTYPE"; static final String ATTNAME_OPTICALSWITCHTYPEINITSTRING = "ATTNAME_OPTICALSWITCHTYPE_INITSTRING"; private static final String ATTNAMESUFFIX_OADMNUMADDDROPMODULES = "oadmNumAddDropModules"; private static final String ATTNAMESUFFIX_HASDIRECTEDMODULES = "oadmHasDirectedAddDropModules"; public void setArbitraryParamString(String s) { getNe().setAttribute(ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_ARBITRARYPARAMSTRING, s); } public String getArbitraryParamString() { return getNe().getAttribute(ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_ARBITRARYPARAMSTRING, ""); } private final Node n; public WNode(Node n) { super(n, Optional.empty()); this.n = n; } Resource getCpuBaseResource() { final Set<Resource> cpuResources = n.getResources(RESOURCETYPE_CPU); assert cpuResources.size() < 2; if (cpuResources.isEmpty()) setTotalNumCpus(0); assert n.getResources(RESOURCETYPE_CPU).size() == 1; return n.getResources(RESOURCETYPE_CPU).iterator().next(); } Resource getRamBaseResource() { final Set<Resource> ramResources = n.getResources(RESOURCETYPE_RAM); assert ramResources.size() < 2; if (ramResources.isEmpty()) setTotalRamGB(0); assert n.getResources(RESOURCETYPE_RAM).size() == 1; return n.getResources(RESOURCETYPE_RAM).iterator().next(); } Resource getHdBaseResource() { final Set<Resource> hdResources = n.getResources(RESOURCETYPE_HD); assert hdResources.size() < 2; if (hdResources.isEmpty()) setTotalHdGB(0); assert n.getResources(RESOURCETYPE_HD).size() == 1; return n.getResources(RESOURCETYPE_HD).iterator().next(); } public boolean isVirtualNode() { return n.hasTag(WNetConstants.TAGNODE_INDICATIONVIRTUALORIGINNODE) || n.hasTag(WNetConstants.TAGNODE_INDICATIONVIRTUALDESTINATIONNODE); } public boolean isRegularNode() { return !isVirtualNode(); } @Override public Node getNe() { return (Node) associatedNpElement; } /** Returns the number of add/drop modules that are directionless (and thus are implemented as regular degrees), in the OADM * @return see above */ public int getOadmNumAddDropDirectionlessModules () { final int index = getNe().getAttributeAsDouble (ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_OADMNUMADDDROPMODULES, 1.0).intValue(); return index < 0? 0 : index; } /** Indicates if this node architecture has directed add/drop modules in the degrees, where to place the lighpaths * @return see above */ public boolean isOadmWithDirectedAddDropModulesInTheDegrees () { final int index = getNe().getAttributeAsDouble (ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_HASDIRECTEDMODULES, 1.0).intValue(); return index != 0; } /** Indicates if this node architecture has directed add/drop modules in the degrees, where to place the lighpaths * @param isWithDirectedAddDropModules see above */ public void setIsOadmWithDirectedAddDropModulesInTheDegrees (boolean isWithDirectedAddDropModules) { getNe().setAttribute(ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_HASDIRECTEDMODULES, isWithDirectedAddDropModules? 1 : 0); } /** Sets the number of add/drop modules in the OADM that are directionless and thus are implemented as regular degrees (greater or equal to zero) * @param numModules see above */ public void setOadmNumAddDropDirectionlessModules (int numModules) { getNe().setAttribute (ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_OADMNUMADDDROPMODULES, numModules < 0? 0 : numModules); } /** Returns the lightpaths added in this node, in directed (non-directionless) modules * @return see above */ public SortedSet<WLightpath> getAddedLightpathsInDirectedModule () { return getAddedLigtpaths().stream().filter(lp->!lp.getDirectionlessAddModuleIndexInOrigin().isPresent()).collect(Collectors.toCollection(TreeSet::new)); } /** Returns the lightpaths dropped in this node, in directed (non-directionless) modules * @return see above */ public SortedSet<WLightpath> getDroppedLightpathsInDirectedModule () { return getDroppedLigtpaths().stream().filter(lp->!lp.getDirectionlessDropModuleIndexInDestination().isPresent()).collect(Collectors.toCollection(TreeSet::new)); } /** Returns the lightpaths added in this node, connected in the indicated add directionless module index * @param directionlessAddModuleIndex see above * @return see above */ public SortedSet<WLightpath> getAddedLightpathsInDirectionlessModule (int directionlessAddModuleIndex) { if (directionlessAddModuleIndex < 0) return new TreeSet<> (); return getAddedLigtpaths().stream().filter(lp->lp.getDirectionlessAddModuleIndexInOrigin().isPresent()).filter(lp->lp.getDirectionlessAddModuleIndexInOrigin().get() == directionlessAddModuleIndex).collect(Collectors.toCollection(TreeSet::new)); } /** Returns the lightpaths added in this node, connected in the indicated drop directionless module index * @param directionlessDropModuleIndex see above * @return see above */ public SortedSet<WLightpath> getDroppedLightpathsInDirectionlessModule (int directionlessDropModuleIndex) { if (directionlessDropModuleIndex < 0) return new TreeSet<> (); return getDroppedLigtpaths().stream().filter(lp->lp.getDirectionlessDropModuleIndexInDestination().isPresent()).filter(lp->lp.getDirectionlessDropModuleIndexInDestination().get() == directionlessDropModuleIndex).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the node name, which must be unique among all the nodes * @return see above */ public String getName() { return n.getName(); } /** * Sets the node name, which must be unique among all the nodes * @param name see above */ public void setName(String name) { if (name == null) WNet.ex("Names cannot be null"); if (name.contains(WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER)) throw new Net2PlanException("Names cannot contain the character: " + WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER); if (getNet().getNodes().stream().anyMatch(n -> n.getName().equals(name))) WNet.ex("Names cannot be repeated"); if (name.contains(" ")) throw new Net2PlanException("Names cannot contain spaces"); n.setName(name); } /** * Sets the icon to show in Net2Plan GUI for node at the WDM layer, and the relative size respect to other nodes. * @param urlIcon see above * @param relativeSize see above */ public void setWdmIcon(URL urlIcon, double relativeSize) { if (!getNet().isWithWdmLayer()) return; getNe().setUrlNodeIcon(getWdmNpLayer().get(), urlIcon, relativeSize); } /** * Sets the icon to show in Net2Plan GUI for node at the IP layer, and the relative size respect to other nodes. * @param urlIcon see above * @param relativeSize see above */ public void setIpIcon(URL urlIcon, double relativeSize) { if (!getNet().isWithIpLayer()) return; getNe().setUrlNodeIcon(getIpNpLayer().get(), urlIcon, relativeSize); } /** * Returns the url of the icon specified by the user for the WDM layer, or null if none * @return the url */ public Optional<URL> getUrlNodeIconWdm() { if (!getNet().isWithWdmLayer()) return Optional.empty(); return Optional.ofNullable(getNe().getUrlNodeIcon(getWdmNpLayer().get())); } /** * Returns the url of the icon specified by the user for the WDM layer, or null if none * @return the url */ public Optional<URL> getUrlNodeIconIp() { if (!getNet().isWithIpLayer()) return Optional.empty(); return Optional.ofNullable(getNe().getUrlNodeIcon(getIpNpLayer().get())); } /** * Returns the relative size in GUI Net2Plan visualization for the icon in the WDM layer fos this node * @return see above */ public double getIconRelativeSizeInWdm() { if (!getNet().isWithWdmLayer()) return 1.0; return getNe().getNodeIconRelativeSize(getWdmNpLayer().get()); } /** * Returns the relative size in GUI Net2Plan visualization for the icon in the WDM layer fos this node * @return see above */ public double getIconRelativeSizeInIp() { if (!getNet().isWithIpLayer()) return 1.0; return getNe().getNodeIconRelativeSize(getIpNpLayer().get()); } /** * Returns the (X,Y) node position * @return see above */ public Point2D getNodePositionXY() { return n.getXYPositionMap(); } /** * Sets the (X,Y) node position * @param position see above */ public void setNodePositionXY(Point2D position) { n.setXYPositionMap(position); } /** * Returns the user-defined node type * @return see above */ public String getType() { return getAttributeOrDefault(ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_TYPE, ""); } /** * Sets the user-defined node type * @param type see above */ public void setType(String type) { n.setAttribute(ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_TYPE, type); } /** * Returns if this node is connected to a core node (core nodes are not in the design) * @return see above */ public boolean isConnectedToNetworkCore() { return getAttributeAsBooleanOrDefault(ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_ISCONNECTEDTOCORE, WNetConstants.WNODE_DEFAULT_ISCONNECTEDTOCORE); } /** * Sets if this node is assumed to be connected to a core node (core nodes are not in the design) * @param isConnectedToCore see above */ public void setIsConnectedToNetworkCore(boolean isConnectedToCore) { n.setAttribute(ATTNAMECOMMONPREFIX + ATTNAMESUFFIX_ISCONNECTEDTOCORE, new Boolean(isConnectedToCore).toString()); } /** * Returns the user-defined node population * @return see above */ public double getPopulation() { return n.getPopulation(); } /** * Sets the user-defined node population * @param population see above */ public void setPoputlation(double population) { n.setPopulation(population); } /** * Returns the number of CPUs available in the node for instantiation of VNFs * @return see above */ public double getTotalNumCpus() { return n.getResources(RESOURCETYPE_CPU).stream().mapToDouble(r -> r.getCapacity()).sum(); } /** * Sets the number of CPUs available in the node for instantiation of VNFs * @param totalNumCpus see above */ public void setTotalNumCpus(double totalNumCpus) { final Set<Resource> res = n.getResources(RESOURCETYPE_CPU); if (res.size() > 1) throw new Net2PlanException("Format error"); if (res.isEmpty()) n.getNetPlan().addResource(RESOURCETYPE_CPU, RESOURCETYPE_CPU, Optional.of(n), totalNumCpus, RESOURCETYPE_CPU, new HashMap<>(), 0.0, null); else res.iterator().next().setCapacity(totalNumCpus, new HashMap<>()); } /** * Returns the total RAM (in GBytes) available in the node for instantiation of VNFs * @return see above */ public double getTotalRamGB() { return n.getResources(RESOURCETYPE_RAM).stream().mapToDouble(r -> r.getCapacity()).sum(); } /** * Sets the total RAM (in GBytes) available in the node for instantiation of VNFs * @param totalRamGB see above */ public void setTotalRamGB(double totalRamGB) { final Set<Resource> res = n.getResources(RESOURCETYPE_RAM); if (res.size() > 1) throw new Net2PlanException("Format error"); if (res.isEmpty()) res.add(n.getNetPlan().addResource(RESOURCETYPE_RAM, RESOURCETYPE_RAM, Optional.of(n), totalRamGB, "GB", new HashMap<>(), 0.0, null)); else res.iterator().next().setCapacity(totalRamGB, new HashMap<>()); } /** * Returns the total hard disk size (in GBytes) available in the node for instantiation of VNFs * @return see above */ public double getTotalHdGB() { return n.getResources(RESOURCETYPE_HD).stream().mapToDouble(r -> r.getCapacity()).sum(); } /** * Sets the total hard disk size (in GBytes) available in the node for instantiation of VNFs * @param totalHdGB see above */ public void setTotalHdGB(double totalHdGB) { final Set<Resource> res = n.getResources(RESOURCETYPE_HD); if (res.size() > 1) throw new Net2PlanException("Format error"); if (res.isEmpty()) res.add(n.getNetPlan().addResource(RESOURCETYPE_HD, RESOURCETYPE_HD, Optional.of(n), totalHdGB, "GB", new HashMap<>(), 0.0, null)); else res.iterator().next().setCapacity(totalHdGB, new HashMap<>()); } /** * Returns the current number of occupied CPUs by the instantiated VNFs * @return see above */ public double getOccupiedCpus() { return getCpuBaseResource().getOccupiedCapacity(); } /** * Returns the current amount of occupied hard-disk (in giga bytes) by the instantiated VNFs * @return see above */ public double getOccupiedHdGB() { return getHdBaseResource().getOccupiedCapacity(); } /** * Returns the current amount of occupied RAM (in giga bytes) by the instantiated VNFs * @return see above */ public double getOccupiedRamGB() { return getRamBaseResource().getOccupiedCapacity(); } /** * Indicates if the node is up or down (failed) * @return see above */ public boolean isUp() { return n.isUp(); } /** * Returns the set of nodes, for which there is a fiber form this node to them * @return see above */ public SortedSet<WNode> getNeighborNodesViaOutgoingFibers() { return getOutgoingFibers().stream().map(e -> e.getB()).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of nodes, for which there is a fiber from them to this node * @return see above */ public SortedSet<WNode> getNeighborNodesViaIncomingFibers() { return getIncomingFibers().stream().map(e -> e.getA()).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing fibers of the node * @return see above */ public SortedSet<WFiber> getOutgoingFibers() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getOutgoingLinks(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isWFiber(); }). map(ee -> new WFiber(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming fibers to the node * @return see above */ public SortedSet<WFiber> getIncomingFibers() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getIncomingLinks(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isWFiber(); }). map(ee -> new WFiber(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing IP links of the node * @return see above */ public SortedSet<WIpLink> getOutgoingIpLinks() { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return n.getOutgoingLinks(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isIpLink(); }). map(ee -> new WIpLink(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** Returns the IP connections, realizing IP unicast demands, that are initiated in this node * @return see above */ public SortedSet<WIpSourceRoutedConnection> getOutgoingIpConnections () { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return n.getOutgoingRoutes(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isIpSourceRoutedConnection(); }). map(ee -> new WIpSourceRoutedConnection(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** Returns the IP connections, realizing IP unicast demands, that are ended in this node * @return see above */ public SortedSet<WIpSourceRoutedConnection> getIncomingIpConnections () { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return n.getIncomingRoutes(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isIpSourceRoutedConnection(); }). map(ee -> new WIpSourceRoutedConnection(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming IP links to the node * @return see above */ public SortedSet<WIpLink> getIncomingIpLinks() { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return n.getIncomingLinks(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isIpLink(); }). map(ee -> new WIpLink(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing lightpath requests of the node * @return see above */ public SortedSet<WLightpathRequest> getOutgoingLigtpathRequests() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getOutgoingDemands(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isLightpathRequest(); }). map(ee -> new WLightpathRequest(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing lightpaths of the node * @return see above */ public SortedSet<WLightpath> getOutgoingLigtpaths() { return getOutgoingLigtpathRequests().stream().map(e->e.getLightpaths()).flatMap(e->e.stream()).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming lightpaths of the node * @return see above */ public SortedSet<WLightpath> getIncomingLigtpaths() { return getIncomingLigtpathRequests().stream().map(e->e.getLightpaths()).flatMap(e->e.stream()).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming lightpath requests to the node * @return see above */ public SortedSet<WLightpathRequest> getIncomingLigtpathRequests() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getIncomingDemands(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isLightpathRequest(); }). map(ee -> new WLightpathRequest(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing lightpaths of the node * @return see above */ public SortedSet<WLightpath> getAddedLigtpaths() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getOutgoingRoutes(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isLightpath(); }). map(ee -> new WLightpath(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming, outgoing and traversing lightpaths to the node * @return see above */ public SortedSet<WLightpath> getInOutOrTraversingLigtpaths() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getAssociatedRoutes(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isLightpath(); }). map(ee -> new WLightpath(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming, outgoing and traversing lightpaths to the node * @return see above */ public SortedSet<WLightpath> getExpressSwitchedLightpaths() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getAssociatedRoutes(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isLightpath(); }). map(ee -> new WLightpath(ee)).filter(lp->lp.getNodesWhereThisLightpathIsExpressOpticallySwitched().contains(this)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming lightpaths to the node * @return see above */ public SortedSet<WLightpath> getDroppedLigtpaths() { if (!getNet().isWithWdmLayer()) return new TreeSet<> (); return n.getIncomingRoutes(getNet().getWdmLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isLightpath(); }). map(ee -> new WLightpath(ee)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing service chain requests of the node: those which have the node as a potential injection * node * @return see above */ public SortedSet<WServiceChainRequest> getOutgoingServiceChainRequests() { return getNet().getServiceChainRequests().stream().filter(sc -> sc.getPotentiallyValidOrigins().contains(this)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing unicast IP demands of the node: those which have the node as origin * @return see above */ public SortedSet<WIpUnicastDemand> getOutgoingIpUnicastDemands () { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return getNe().getOutgoingDemands(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isIpUnicastDemand(); }). map(d->new WIpUnicastDemand(d)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming unicast IP demands of the node: those which have the node as destination * @return see above */ public SortedSet<WIpUnicastDemand> getIncomingIpUnicastDemands () { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return getNe().getIncomingDemands(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isIpUnicastDemand(); }). map(d->new WIpUnicastDemand(d)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming service chain requests of the node: those which have the node as a potential end node * @return see above */ public SortedSet<WServiceChainRequest> getIncomingServiceChainRequests() { return getNet().getServiceChainRequests().stream(). filter(sc -> sc.getPotentiallyValidDestinations().contains(this)). collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of outgoing service chains of the node, including those starting in a VNF in the node * @return see above */ public SortedSet<WServiceChain> getOutgoingServiceChains() { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return n.getAssociatedRoutes(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isServiceChain(); }). map(ee -> new WServiceChain(ee)). filter(sc -> sc.getA().equals(this)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming service chains to the node, including those ended in a VNF in the node * @return see above */ public SortedSet<WServiceChain> getIncomingServiceChains() { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return n.getAssociatedRoutes(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isServiceChain(); }). map(ee -> new WServiceChain(ee)).filter(sc -> sc.getB().equals(this)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns the set of incoming, outgoing and traversing service chains to the node. * @return see above */ public SortedSet<WServiceChain> getInOutOrTraversingServiceChains() { if (!getNet().isWithIpLayer()) return new TreeSet<> (); return n.getAssociatedRoutes(getNet().getIpLayer().get().getNe()).stream(). filter(d->{ WTYPE t = getNet().getWType(d).orElse(null); return t == null? false : t.isServiceChain(); }). map(ee -> new WServiceChain(ee)).collect(Collectors.toCollection(TreeSet::new)); } Link getIncomingLinkFromAnycastOrigin() { assert getNet().isWithIpLayer(); return n.getNetPlan().getNodePairLinks(getNet().getAnycastOriginNode().getNe(), n, false, getIpNpLayer().get()).stream().findFirst().orElseThrow(() -> new RuntimeException()); } Link getOutgoingLinkToAnycastDestination() { assert getNet().isWithIpLayer(); return n.getNetPlan().getNodePairLinks(n, getNet().getAnycastDestinationNode().getNe(), false, getIpNpLayer().get()).stream().findFirst().orElseThrow(() -> new RuntimeException()); } /** * Sets the node as up (working, non-failed) */ public void setAsUp() { n.setFailureState(true); final SortedSet<WLightpathRequest> affectedDemands = new TreeSet<>(); getOutgoingFibers().forEach(f -> affectedDemands.addAll(f.getTraversingLpRequestsInAtLeastOneLp())); getIncomingFibers().forEach(f -> affectedDemands.addAll(f.getTraversingLpRequestsInAtLeastOneLp())); for (WLightpathRequest lpReq : affectedDemands) lpReq.updateNetPlanObjectAndPropagateUpwards(); } /** * Sets the node as down (failed), so traversing IP links or lightpaths become down */ public void setAsDown() { n.setFailureState(false); final SortedSet<WLightpathRequest> affectedDemands = new TreeSet<>(); getOutgoingFibers().forEach(f -> affectedDemands.addAll(f.getTraversingLpRequestsInAtLeastOneLp())); getIncomingFibers().forEach(f -> affectedDemands.addAll(f.getTraversingLpRequestsInAtLeastOneLp())); for (WLightpathRequest lpReq : affectedDemands) lpReq.updateNetPlanObjectAndPropagateUpwards(); } /** * Removes this node, and all the ending and initiated links, or traversing lightpaths or service chains * */ public void remove() { this.setAsDown(); n.remove(); } @Override public String toString() { return "Node " + getName(); } /** * Returns all the VNF instances in this node, of any type * @return see above */ public SortedSet<WVnfInstance> getAllVnfInstances() { return n.getResources().stream().filter(r -> !r.getType().contains(WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER)).map(r -> new WVnfInstance(r)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns all the VNF instances in this node, of the given type * @param type see above * @return see above */ public SortedSet<WVnfInstance> getVnfInstances(String type) { if (type.contains(WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER)) throw new Net2PlanException("Names cannot contain the character: " + WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER); return n.getResources().stream().filter(r -> !r.getType().contains(WNetConstants.LISTSEPARATORANDINVALIDNAMECHARACTER)).map(r -> new WVnfInstance(r)).filter(v -> v.getType().equals(type)).collect(Collectors.toCollection(TreeSet::new)); } /** * Returns all the VNF instances in this node, of the given type * @return see above */ public SortedSet<WVnfInstance> getVnfInstances() { return n.getResources().stream().map(r -> new WVnfInstance(r)).collect(Collectors.toCollection(TreeSet::new)); } /** Indicates if this node has a filterless brodcast operation with the add, dropped and express lightpaths * @return see above */ public IOadmArchitecture getOpticalSwitchingArchitecture () { try { final String classFullName = this.getNe().getAttribute(ATTNAMECOMMONPREFIX + ATTNAME_OPTICALSWITCHTYPE, null); if (classFullName == null) throw new RuntimeException (); final Class classOfOadmArchit = Class.forName(classFullName); final IOadmArchitecture arc = (IOadmArchitecture) classOfOadmArchit.getConstructor().newInstance(); arc.initialize(this); return arc; } catch (Exception e) { e.printStackTrace(); final OadmArchitecture_generic res = new OadmArchitecture_generic(); this.getNe().setAttribute(ATTNAMECOMMONPREFIX + ATTNAME_OPTICALSWITCHTYPE, OadmArchitecture_generic.class.getName()); res.initialize(this); return res; } } public void setOpticalSwitchArchitecture (Class opticalArchitectureClass) { if (!IOadmArchitecture.class.isAssignableFrom(opticalArchitectureClass)) throw new Net2PlanException ("The architecture is not an instance of the appropriate class"); getNe().setAttribute(ATTNAMECOMMONPREFIX + ATTNAME_OPTICALSWITCHTYPE, opticalArchitectureClass.getName()); } @Override void checkConsistency() { if (this.wasRemoved()) return; assert getIncomingFibers().stream().allMatch(e->e.getB().equals(this)); assert getOutgoingFibers().stream().allMatch(e->e.getA().equals(this)); assert getIncomingIpConnections().stream().allMatch(e->e.getB().equals(this)); assert getOutgoingIpConnections().stream().allMatch(e->e.getA().equals(this)); assert getIncomingLigtpathRequests().stream().allMatch(e->e.getB().equals(this)); assert getOutgoingLigtpathRequests().stream().allMatch(e->e.getA().equals(this)); assert getDroppedLigtpaths().stream().allMatch(e->e.getB().equals(this)); assert getAddedLigtpaths().stream().allMatch(e->e.getA().equals(this)); assert getIncomingServiceChainRequests().stream().allMatch(e->e.getPotentiallyValidDestinations().contains(this)); assert getOutgoingServiceChainRequests().stream().allMatch(e->e.getPotentiallyValidOrigins().contains(this)); assert getIncomingServiceChains().stream().allMatch(e->e.getB().equals(this)); assert getOutgoingServiceChains().stream().allMatch(e->e.getA().equals(this)); assert getInOutOrTraversingLigtpaths().stream().allMatch(e->e.getSeqNodes().contains(this)); assert getInOutOrTraversingServiceChains().stream().allMatch(e->e.getSequenceOfTraversedIpNodesWithoutConsecutiveRepetitions().contains(this)); assert getNeighborNodesViaIncomingFibers().stream().allMatch(n->n.getNeighborNodesViaOutgoingFibers().contains(this)); assert getNeighborNodesViaOutgoingFibers().stream().allMatch(n->n.getNeighborNodesViaIncomingFibers().contains(this)); assert getVnfInstances().stream().allMatch(v->v.getHostingNode().equals(this)); } /** Returns the SRGs that this node belongs to, i.e. the ones that make this node fail * @return see above */ public SortedSet<WSharedRiskGroup> getSrgsThisElementIsAssociatedTo () { return getNe().getSRGs().stream().map(s->new WSharedRiskGroup(s)).collect(Collectors.toCollection(TreeSet::new)); } @Override public WTYPE getWType() { return WTYPE.WNode; } }
38.461369
261
0.729266
0e1e07398527bbcee99c6bf4512fa791c70ad0f5
1,877
package zjp.translateit.web.Interceptor; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import zjp.translateit.test.SpringMvcTest; @TestPropertySource(value = "classpath:application.properties") public class ManageTokenInterceptorTest extends SpringMvcTest { @Autowired private WebApplicationContext context; @Value("${manager.name}") private String name; @Value("${manager.password}") private String password; @Test public void preHandle() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context) .build(); mockMvc.perform(MockMvcRequestBuilders.post("/manage/token") .contentType(MediaType.APPLICATION_JSON) .param("name", name) .param("password", password) .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().is(HttpStatus.OK.value())); mockMvc.perform(MockMvcRequestBuilders.post("/manage/token") .contentType(MediaType.APPLICATION_JSON) .param("name", name) .param("password", "wrong") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().is(HttpStatus.FORBIDDEN.value())); } }
42.659091
92
0.722962
44c7d3cfb088d46190760b451e7ac51cf94aa784
2,988
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Method; public class Main { public static void expectEquals(int expected, int result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } public static void expectEquals(long expected, long result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } public static void main(String[] args) throws Exception { notInt(); notLong(); } private static void notInt() throws Exception { expectEquals(1, smaliNotInt(-2)); expectEquals(0, smaliNotInt(-1)); expectEquals(-1, smaliNotInt(0)); expectEquals(-2, smaliNotInt(1)); expectEquals(2147483647, smaliNotInt(-2147483648)); // -(2^31) expectEquals(2147483646, smaliNotInt(-2147483647)); // -(2^31 - 1) expectEquals(-2147483647, smaliNotInt(2147483646)); // 2^31 - 2 expectEquals(-2147483648, smaliNotInt(2147483647)); // 2^31 - 1 } private static void notLong() throws Exception { expectEquals(1L, smaliNotLong(-2L)); expectEquals(0L, smaliNotLong(-1L)); expectEquals(-1L, smaliNotLong(0L)); expectEquals(-2L, smaliNotLong(1L)); expectEquals(2147483647L, smaliNotLong(-2147483648L)); // -(2^31) expectEquals(2147483646L, smaliNotLong(-2147483647L)); // -(2^31 - 1) expectEquals(-2147483647L, smaliNotLong(2147483646L)); // 2^31 - 2 expectEquals(-2147483648L, smaliNotLong(2147483647L)); // 2^31 - 1 expectEquals(9223372036854775807L, smaliNotLong(-9223372036854775808L)); // -(2^63) expectEquals(9223372036854775806L, smaliNotLong(-9223372036854775807L)); // -(2^63 - 1) expectEquals(-9223372036854775807L, smaliNotLong(9223372036854775806L)); // 2^63 - 2 expectEquals(-9223372036854775808L, smaliNotLong(9223372036854775807L)); // 2^63 - 1 } // Wrappers around methods located in file not.smali. private static int smaliNotInt(int a) throws Exception { Class<?> c = Class.forName("TestNot"); Method m = c.getMethod("$opt$NotInt", int.class); int result = (Integer)m.invoke(null, a); return result; } private static long smaliNotLong(long a) throws Exception { Class<?> c = Class.forName("TestNot"); Method m = c.getMethod("$opt$NotLong", long.class); long result = (Long)m.invoke(null, a); return result; } }
37.35
92
0.685408
fb006944368d2b45e4ba86873f02ec15b727081e
782
package de.j13g.manko.util; import java.io.Serializable; import java.util.Objects; public class Pair<A, B> implements Serializable { protected final A first; protected final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public A getFirst() { return first; } public B getSecond() { return second; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair<?, ?>)) return false; Pair<?, ?> other = (Pair<?, ?>) o; return first.equals(other.first) && second.equals(other.second); } @Override public int hashCode() { return Objects.hash(first, second); } }
20.051282
72
0.575448
d6f1f0fa90093845414c6142d0c882c5441c6380
2,731
package cn.edu.hhu.reg.activity; import java.util.ArrayList; import cn.edu.hhu.reg.R; import cn.edu.hhu.reg.adapter.DepartmentListViewAdapter; import cn.edu.hhu.reg.api.ApiClient; import cn.edu.hhu.reg.api.ResponseUtils; import cn.edu.hhu.reg.api.SimpleResponse; import cn.edu.hhu.reg.common.CustomProgressDialog; import cn.edu.hhu.reg.common.ToastShow; import cn.edu.hhu.reg.common.http.HttpException; import cn.edu.hhu.reg.common.http.async.HttpAsync; import cn.edu.hhu.reg.entity.Department; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; public class DepartmentListActivity extends BaseActivity { ListView lv; CustomProgressDialog progressDialog ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_listview); UiHelper.goBack(this); ((TextView)findViewById(R.id.listview_tv_title)).setText("科室列表"); lv = (ListView) findViewById(R.id.listview_lv); getDepartmentList(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DepartmentListViewAdapter adapter = (DepartmentListViewAdapter)parent.getAdapter(); if(adapter!=null){ Department department = adapter.getItem(position); UiHelper.doctorList(DepartmentListActivity.this, department.getId()); } } }); } private void getDepartmentList() { HttpAsync httpAsync = new HttpAsync() { @Override protected void onSuccess(String json) { progressDialog.dismiss(); try { SimpleResponse<ArrayList<Department>> departmentListResponse = ResponseUtils.departmentListResponse(json); if(departmentListResponse.isSuccess()){ ArrayList<Department> list = departmentListResponse.getData(); DepartmentListViewAdapter adapter = new DepartmentListViewAdapter(list, DepartmentListActivity.this); lv.setAdapter(adapter); }else{ String msg = departmentListResponse.getMessage(); if(msg==null){ msg=""; } ToastShow.shortT("获取列表失败!"+msg); } } catch (Exception e) { ToastShow.shortT(e.getMessage()); } } @Override public void onError(HttpException exception) { progressDialog.dismiss(); ToastShow.shortT("获取列表失败!"); } }; if(progressDialog==null){ progressDialog = new CustomProgressDialog(this,"正在获取科室列表!"); } progressDialog.show(); ApiClient.departmentList(httpAsync); } @Override protected void onDestroy() { super.onDestroy(); progressDialog.dismiss(); } }
30.685393
111
0.741487
ea01b8a1a6faa9dd654825ce4a50842c4a643033
9,014
package controladores; import beans.Informe_Final; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import modelos.Modelo_Informe; @WebServlet(name = "Controlador_Informe", urlPatterns = {"/Controlador_Informe"}) public class Controlador_Informe extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); //request.setCharacterEncoding("UTF-8"); try (PrintWriter out = response.getWriter()) { Modelo_Informe mod; //HttpSession session = request.getSession(); switch(request.getParameter("opcion").charAt(0)){ // MANDAR A LA LISTA DE INFORME case 'L': request.getRequestDispatcher("Lista_Informes.jsp").forward(request, response); break; // INSERTAR INFORME case 'I': mod= new Modelo_Informe(); Informe_Final informe; try { // LLENO CON LOS DATOS ENVIADOS POR EL FORMULARIO informe= new Informe_Final(); informe.setDescripcion(request.getParameter("txtDescripcion")); informe.setId_incidente_fk(Integer.parseInt(request.getParameter("txtIncidenteFK"))); informe.setId_problema_fk(Integer.parseInt(request.getParameter("txtProblemaFK"))); informe.setId_solucion_fk(Integer.parseInt(request.getParameter("txtSolucionFK"))); if(mod.insertarInforme(informe)==1){ request.setAttribute("ALERTA", "INGRESADO"); } else { request.setAttribute("ALERTA", "NO_INGRESADO"); } request.getRequestDispatcher("Lista_Informes.jsp").forward(request, response); } catch (IOException | ServletException e) { request.setAttribute("ALERTA", "ERROR"); request.getRequestDispatcher("Lista_Informes.jsp").forward(request, response); } break; // INSERTAR INFORME case 'W': mod= new Modelo_Informe(); Informe_Final informe1; try { // LLENO CON LOS DATOS ENVIADOS POR EL FORMULARIO informe1= new Informe_Final(); informe1.setDescripcion(request.getParameter("txtDescripcion")); informe1.setId_incidente_fk(Integer.parseInt(request.getParameter("txtIncidenteFK"))); informe1.setId_problema_fk(Integer.parseInt(request.getParameter("txtProblemaFK"))); informe1.setId_solucion_fk(Integer.parseInt(request.getParameter("txtSolucionFK"))); if(mod.insertarInforme(informe1)==1){ request.setAttribute("ALERTA", "INGRESADO"); } else { request.setAttribute("ALERTA", "NO_INGRESADO"); } request.getRequestDispatcher("Lista_Informes_Propia.jsp").forward(request, response); } catch (IOException | ServletException e) { request.setAttribute("ALERTA", "ERROR"); request.getRequestDispatcher("Lista_Informes_Propia.jsp").forward(request, response); } break; // MODIFICAR INCIDENTE case 'D': mod= new Modelo_Informe(); try { // LLENO CON LOS DATOS ENVIADOS POR EL FORMULARIO informe1= new Informe_Final(); informe1.setDescripcion(request.getParameter("txtDescripcion")); informe1.setId_incidente_fk(Integer.parseInt(request.getParameter("txtIncidenteFK"))); informe1.setId_problema_fk(Integer.parseInt(request.getParameter("txtProblemaFK"))); informe1.setId_solucion_fk(Integer.parseInt(request.getParameter("txtSolucionFK"))); System.out.println("TEXT0 = "+informe1.getDescripcion()); if(mod.modificarInforme(informe1)==1){ request.setAttribute("ALERTA", "MODIFICADO"); } else { request.setAttribute("ALERTA", "NO_MODIFICADO"); } request.getRequestDispatcher("Lista_Informes.jsp").forward(request, response); } catch (IOException | ServletException e) { request.setAttribute("ALERTA", "ERROR"); request.getRequestDispatcher("Lista_Informes.jsp").forward(request, response); } break; // ELIMINAR case 'E': try { mod= new Modelo_Informe(); //mod.eliminarProblema(Integer.parseInt(request.getParameter("txtId"))); if(mod.eliminarInforme(Integer.parseInt(request.getParameter("txtId")))==1){ request.setAttribute("ALERTA", "ELIMINADO"); } else { request.setAttribute("ALERTA", "NO_ELIMINADO"); } request.getRequestDispatcher("Lista_Informes.jsp").forward(request, response); //response.sendRedirect("Lista_Problemas.jsp"); } catch (IOException | NumberFormatException e) { request.setAttribute("ALERTA", "ERROR"); request.getRequestDispatcher("Lista_Informes.jsp").forward(request, response); } break; // ELIMINAR case 'Y': try { mod= new Modelo_Informe(); //mod.eliminarProblema(Integer.parseInt(request.getParameter("txtId"))); if(mod.eliminarInforme(Integer.parseInt(request.getParameter("txtId")))==1){ request.setAttribute("ALERTA", "ELIMINADO"); } else { request.setAttribute("ALERTA", "NO_ELIMINADO"); } request.getRequestDispatcher("Lista_Informes_Propia.jsp").forward(request, response); //response.sendRedirect("Lista_Problemas.jsp"); } catch (IOException | NumberFormatException e) { request.setAttribute("ALERTA", "ERROR"); request.getRequestDispatcher("Lista_Informes_Propia.jsp").forward(request, response); } break; default: out.print("Opción No Disponible"); break; } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
37.558333
123
0.534502
cd2ad333e76b13e8e31e1c89a4a2e699354ca8dc
356
package com.google.android.play.core.common; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; public interface IntentSenderForResultStarter { void startIntentSenderForResult(IntentSender intentSender, int i, Intent intent, int i2, int i3, int i4, Bundle bundle) throws IntentSender.SendIntentException; }
35.6
164
0.823034