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
9d3e9c3123bf1ec6181245f4db97de7dc923a2ea
3,107
package edu.brown.cs.systems.pivottracing.tracepoint; import java.lang.reflect.Method; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists; import edu.brown.cs.systems.pivottracing.advice.AdviceProtos.AdviceSpec; import edu.brown.cs.systems.pivottracing.agent.WeaveProtos.MethodTracepointSpec; import edu.brown.cs.systems.pivottracing.agent.WeaveProtos.MethodTracepointSpec.Where; import edu.brown.cs.systems.pivottracing.agent.WeaveProtos.TracepointSpec; public class MethodTracepoint extends TracepointBaseImpl { public enum Interception { ENTRY, EXIT, EXCEPTION } public final Where interceptAt; public final int interceptAtLineNumber; public final String className, methodName; public final String[] args; public MethodTracepoint(String name, Where interceptAt, Method method) { this(name, interceptAt, method.getDeclaringClass().getName(), method.getName(), parametersToString(method.getParameterTypes())); } private static String[] parametersToString(Class<?>[] parameterClasses) { String[] parameterClassNames = new String[parameterClasses.length]; for (int i = 0; i < parameterClasses.length; i++) { parameterClassNames[i] = parameterClasses[i].getCanonicalName(); } return parameterClassNames; } public MethodTracepoint(String name, Where interceptAt, String fullyQualifiedClassname, String methodName, String... fullyQualifiedArgs) { super(name); this.interceptAt = interceptAt; this.interceptAtLineNumber = 0; this.className = fullyQualifiedClassname; this.methodName = methodName; this.args = fullyQualifiedArgs; } public MethodTracepoint(String name, int interceptAtLineNumber, String fullyQualifiedClassname, String methodName, String... fullyQualifiedArgs) { super(name); this.interceptAt = Where.LINENUM; this.interceptAtLineNumber = interceptAtLineNumber; this.className = fullyQualifiedClassname; this.methodName = methodName; this.args = fullyQualifiedArgs; } @Override public String toString() { return String.format("%s = %s [%s].[%s]([%s])", getName(), interceptAt, className, methodName, StringUtils.join(args, "],[")); } @Override public List<TracepointSpec> getTracepointSpecsForAdvice(AdviceSpec advice) { TracepointSpec.Builder tsb = TracepointSpec.newBuilder(); MethodTracepointSpec.Builder b = tsb.getMethodTracepointBuilder(); b.setClassName(className); b.setMethodName(methodName); b.addAllParamClass(Lists.newArrayList(args)); b.setWhere(interceptAt); if (interceptAt == Where.LINENUM) { b.setLineNumber(interceptAtLineNumber); } for (String observedVar : advice.getObserve().getVarList()) { b.addAdviceArg(exports.get(observedVar.split("\\.")[1]).getSpec()); } return Lists.<TracepointSpec>newArrayList(tsb.build()); } }
39.329114
150
0.701963
76e1432014dc686511b277c71cbdbb851448cbc4
1,483
package br.unb.cic.mase.gui; import javax.swing.JFrame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; public class MainScreen extends JFrame { private static final long serialVersionUID = 1L; private static MainScreen instance; private SimulationScreen simulationScr; private ControllerPanel controllerPan; private MainScreen() { this.setExtendedState(JFrame.MAXIMIZED_BOTH); this.getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 0.9; c.weighty = 1; c.gridx = 0; c.gridy = 0; configureCanvas(); this.getContentPane().add(simulationScr, c); configureControllers(); c.fill = GridBagConstraints.NONE; c.weightx = 0.1; c.weighty = 1; c.gridx = 1; c.gridy = 0; this.getContentPane().add(controllerPan, c); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static MainScreen getInstance() { if (instance == null) { instance = new MainScreen(); } return instance; } public void configureCanvas(){ int rows = 20; int columns = 20; simulationScr = SimulationScreen.getInstance(); simulationScr.setColumnsAndRows(columns, rows); } public void configureControllers() { controllerPan = ControllerPanel.getInstance(); } public static void main(String[] args) { MainScreen.getInstance(); } }
22.469697
56
0.698584
9368f2fc6decb9ef5f25d300b01be27090d3e1d7
5,945
/* * 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.skywalking.apm.collector.agent.grpc.provider.handler.mock; import io.grpc.ManagedChannel; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.apache.skywalking.apm.network.proto.CPU; import org.apache.skywalking.apm.network.proto.GC; import org.apache.skywalking.apm.network.proto.GCPhrase; import org.apache.skywalking.apm.network.proto.JVMMetric; import org.apache.skywalking.apm.network.proto.JVMMetrics; import org.apache.skywalking.apm.network.proto.JVMMetricsServiceGrpc; import org.apache.skywalking.apm.network.proto.Memory; import org.apache.skywalking.apm.network.proto.MemoryPool; import org.apache.skywalking.apm.network.proto.PoolType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author peng-yongsheng */ class JVMMetricMock { private static final Logger logger = LoggerFactory.getLogger(JVMMetricMock.class); void mock(ManagedChannel channel, Long[] times) { JVMMetricsServiceGrpc.JVMMetricsServiceBlockingStub jvmMetricsServiceBlockingStub = JVMMetricsServiceGrpc.newBlockingStub(channel); Set<Long> timeSet = new HashSet<>(); timeSet.addAll(Arrays.asList(times)); AtomicInteger increment = new AtomicInteger(0); timeSet.forEach(timestamp -> { JVMMetrics.Builder jvmMetrics = JVMMetrics.newBuilder(); jvmMetrics.setApplicationInstanceId(2); JVMMetric.Builder jvmMetricBuilder = JVMMetric.newBuilder(); jvmMetricBuilder.setTime(timestamp); buildCPUMetric(jvmMetricBuilder); buildGCMetric(jvmMetricBuilder); buildMemoryMetric(jvmMetricBuilder); buildMemoryPoolMetric(jvmMetricBuilder); jvmMetrics.addMetrics(jvmMetricBuilder.build()); jvmMetricsServiceBlockingStub.collect(jvmMetrics.build()); if (increment.incrementAndGet() % 100 == 0) { logger.info("sending jvm metric number: {}", increment.get()); } }); logger.info("sending jvm metric number: {}", increment.get()); } private static void buildMemoryPoolMetric(JVMMetric.Builder metricBuilder) { MemoryPool.Builder codeCache = MemoryPool.newBuilder(); codeCache.setInit(10); codeCache.setMax(100); codeCache.setCommited(10); codeCache.setUsed(50); codeCache.setType(PoolType.CODE_CACHE_USAGE); metricBuilder.addMemoryPool(codeCache); MemoryPool.Builder newGen = MemoryPool.newBuilder(); newGen.setInit(10); newGen.setMax(100); newGen.setCommited(10); newGen.setUsed(50); newGen.setType(PoolType.NEWGEN_USAGE); metricBuilder.addMemoryPool(newGen); MemoryPool.Builder oldGen = MemoryPool.newBuilder(); oldGen.setInit(10); oldGen.setMax(100); oldGen.setCommited(10); oldGen.setUsed(50); oldGen.setType(PoolType.OLDGEN_USAGE); metricBuilder.addMemoryPool(oldGen); MemoryPool.Builder survivor = MemoryPool.newBuilder(); survivor.setInit(10); survivor.setMax(100); survivor.setCommited(10); survivor.setUsed(50); survivor.setType(PoolType.SURVIVOR_USAGE); metricBuilder.addMemoryPool(survivor); MemoryPool.Builder permGen = MemoryPool.newBuilder(); permGen.setInit(10); permGen.setMax(100); permGen.setCommited(10); permGen.setUsed(50); permGen.setType(PoolType.PERMGEN_USAGE); metricBuilder.addMemoryPool(permGen); MemoryPool.Builder metaSpace = MemoryPool.newBuilder(); metaSpace.setInit(10); metaSpace.setMax(100); metaSpace.setCommited(10); metaSpace.setUsed(50); metaSpace.setType(PoolType.METASPACE_USAGE); metricBuilder.addMemoryPool(metaSpace); } private static void buildMemoryMetric(JVMMetric.Builder metricBuilder) { Memory.Builder isHeap = Memory.newBuilder(); isHeap.setInit(20); isHeap.setMax(100); isHeap.setCommitted(20); isHeap.setUsed(60); isHeap.setIsHeap(true); metricBuilder.addMemory(isHeap); Memory.Builder nonHeap = Memory.newBuilder(); nonHeap.setInit(20); nonHeap.setMax(100); nonHeap.setCommitted(20); nonHeap.setUsed(60); nonHeap.setIsHeap(false); metricBuilder.addMemory(nonHeap); } private static void buildGCMetric(JVMMetric.Builder metricBuilder) { GC.Builder newGC = GC.newBuilder(); newGC.setPhrase(GCPhrase.NEW); newGC.setCount(2); newGC.setTime(1000); metricBuilder.addGc(newGC); GC.Builder oldGC = GC.newBuilder(); oldGC.setPhrase(GCPhrase.OLD); oldGC.setCount(4); oldGC.setTime(49); metricBuilder.addGc(oldGC); } private static void buildCPUMetric(JVMMetric.Builder metricBuilder) { CPU.Builder cpu = CPU.newBuilder(); cpu.setUsagePercent(20); metricBuilder.setCpu(cpu.build()); } }
36.697531
139
0.690664
e578b60751b7737d90d5efa4e8f6f3ea8313248c
3,496
package net.xtrafrancyz.mods.minidot.items.pet; import net.minecraft.client.model.ModelPlayer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.xtrafrancyz.mods.minidot.items.MModelRenderer; public class SkullPet extends BasePet { private static final ResourceLocation tex = new ResourceLocation("minidot", "pets/skullpet.png"); private static final ResourceLocation tex1 = new ResourceLocation("minidot", "pets/skullpet2.png"); private MModelRenderer Piece1; public SkullPet() { this.textureWidth = 64; this.textureHeight = 32; this.setTextureOffset("Piece1.Shape1", 0, 0); this.setTextureOffset("Piece1.Shape17", 0, 19); this.setTextureOffset("Piece1.Shape2", 30, 0); this.setTextureOffset("Piece1.Shape16", 0, 19); this.setTextureOffset("Piece1.Shape3", 33, 0); this.setTextureOffset("Piece1.Shape15", 0, 19); this.setTextureOffset("Piece1.Shape4", 33, 0); this.setTextureOffset("Piece1.Shape14", 0, 19); this.setTextureOffset("Piece1.Shape5", 34, 4); this.setTextureOffset("Piece1.Shape13", 30, 0); this.setTextureOffset("Piece1.Shape6", 30, 3); this.setTextureOffset("Piece1.Shape12", 31, 2); this.setTextureOffset("Piece1.Shape7", 36, 2); this.setTextureOffset("Piece1.Shape11", 39, 2); this.setTextureOffset("Piece1.Shape8", 41, 3); this.setTextureOffset("Piece1.Shape10", 31, 1); this.setTextureOffset("Piece1.Shape9", 42, 3); this.Piece1 = new MModelRenderer(this, "Piece1"); this.Piece1.addBox("Shape1", -4.0F, -4.0F, -3.0F, 8, 8, 7); this.Piece1.addBox("Shape17", 0.2F, 5.0F, -4.0F, 1, 1, 1); this.Piece1.addBox("Shape2", -4.0F, -4.0F, -4.0F, 8, 4, 1); this.Piece1.addBox("Shape16", 1.6F, 5.0F, -4.0F, 1, 1, 1); this.Piece1.addBox("Shape3", -4.0F, 0.0F, -4.0F, 1, 1, 1); this.Piece1.addBox("Shape15", -1.2F, 5.0F, -4.0F, 1, 1, 1); this.Piece1.addBox("Shape4", 3.0F, 0.0F, -4.0F, 1, 1, 1); this.Piece1.addBox("Shape14", -2.6F, 5.0F, -4.0F, 1, 1, 1); this.Piece1.addBox("Shape5", -1.0F, 0.0F, -4.0F, 2, 1, 1); this.Piece1.addBox("Shape13", -3.0F, 4.0F, -4.0F, 6, 1, 5); this.Piece1.addBox("Shape6", -4.0F, 1.0F, -4.0F, 8, 1, 1); this.Piece1.addBox("Shape12", -4.5F, 2.0F, -4.5F, 2, 2, 2); this.Piece1.addBox("Shape7", -4.0F, 2.0F, -4.0F, 3, 1, 1); this.Piece1.addBox("Shape11", 2.5F, 2.0F, -4.5F, 2, 2, 2); this.Piece1.addBox("Shape8", 1.0F, 2.0F, -4.0F, 3, 1, 1); this.Piece1.addBox("Shape10", -4.0F, 3.0F, -4.0F, 8, 1, 1); this.Piece1.addBox("Shape9", -0.5F, 2.0F, -4.0F, 1, 1, 1); this.setTexture(tex); } protected void processMotion(ModelPlayer modelPlayer, EntityPlayer player, float time) { float f = MathHelper.sin(time * 0.16F) * 0.02F; GlStateManager.translate(0.6F, -0.5F + f, 0.4F); if (time % 90.0F > 30.0F) { this.setTexture(tex); } else { this.setTexture(tex1); } } public void renderAsItem(float time) { GlStateManager.scale(1.2F, 1.2F, 1.2F); super.renderAsItem(time); } public String getName() { return "\u0427\u0435\u0440\u0435\u043f"; } }
41.619048
103
0.606693
8953b005f6a890a47ac3e64841d2e8a69a3fb7fe
390
package cn.jeeweb.generator.mapper; import cn.jeeweb.generator.entity.Template; import com.baomidou.mybatisplus.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * @Title: 生成模板数据库控制层接口 * @Description: 生成模板数据库控制层接口 * @author jeeweb * @date 2017-09-15 15:10:12 * @version V1.0 * */ @Mapper public interface TemplateMapper extends BaseMapper<Template> { }
21.666667
62
0.741026
f6d5be8e6a9374614d58e9688d0781d1bd2578d9
1,998
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. */ package org.olat.commons.calendar.model; import org.olat.commons.calendar.ui.components.KalendarRenderWrapper; public class KalendarConfig { private transient String displayName; private String css; private boolean vis; private Long resId; public KalendarConfig() { this("Calendar", KalendarRenderWrapper.CALENDAR_COLOR_BLUE, true); } public KalendarConfig(String displayName, String calendarCSS, boolean visible) { this.displayName = displayName; this.css = calendarCSS; this.vis = visible; this.resId = null; } public Long getResId() { return this.resId; } public void setResId(Long resId) { this.resId = resId; } public String getCss() { return css; } public void setCss(String css) { this.css = css; } public boolean isVis() { return vis; } public void setVis(boolean vis) { this.vis = vis; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } }
24.975
81
0.725726
e638bda0ca03a380271ff8be28ac0467e0cb4e24
1,995
package com.xarql.user.front; import java.io.IOException; 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 com.xarql.auth.AuthSession; import com.xarql.user.Account; import com.xarql.util.DeveloperOptions; import com.xarql.util.ServletUtilities; /** * Servlet implementation class LogInHandler */ @WebServlet ("/user/log_in/form") public class LogInHandler extends HttpServlet { private static final long serialVersionUID = 1L; private static final String DOMAIN = DeveloperOptions.getDomain(); /** * @see HttpServlet#HttpServlet() */ public LogInHandler() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletUtilities.rejectGetMethod(response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletUtilities util = new ServletUtilities(request); if(util.hasParams("username", "password")) try { new AuthSession(request.getRequestedSessionId(), new Account(request.getParameter("username").trim().toLowerCase(), request.getParameter("password"))); response.sendRedirect(DOMAIN + "/user"); } catch(Exception e) { response.sendRedirect(DOMAIN + "/user/log_in?prefill=" + util.useParam("username") + "&fail=" + e.getMessage()); } else response.sendError(400); } }
30.692308
167
0.678697
63cfbfddaa39f2521e1c9b3d3e1c68f2046f2dff
150
package com.studentsystem.dao; import com.studentsystem.entity.Student; //学生的dao接口继承顶层dao 接口 public interface StudentDaoI extends DaoI<Student>{ }
16.666667
51
0.813333
da0b11562a7029c39a1a576e5bb300f805d75c55
5,389
package com.drajer.eca.model; import java.util.List; import java.util.Set; import org.apache.commons.collections4.SetUtils; import org.hl7.fhir.r4.model.CodeableConcept; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.drajer.ecrapp.config.ValueSetSingleton; import com.drajer.ecrapp.util.ApplicationUtils; import com.drajer.sof.model.Dstu2FhirData; import com.drajer.sof.model.LaunchDetails; import com.drajer.sof.model.R4FhirData; import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt; public class EcaUtils { private static Logger logger = LoggerFactory.getLogger(EcaUtils.class); public static boolean matchTriggerCodesForDSTU2(List<ActionData> codePaths, Dstu2FhirData data, PatientExecutionState state, LaunchDetails details) { logger.info(" Start Matching Trigger Codes "); boolean matchfound = false; state.getMatchTriggerStatus().setTriggerMatchStatus(false); for(ActionData ad: codePaths) { logger.info(" Need to match Trigger Codes for : " + ad.getPath()); List<CodeableConceptDt> ptCodes = data.getCodesForExpression(ad.getPath()); if(ptCodes != null && ptCodes.size() > 0) { logger.info(" Found a Total # of " + ptCodes.size() + " codes found for Patient." + ad.getPath()); Set<String> codesToMatch = ApplicationUtils.convertCodeableConceptsToString(ptCodes); Set<String> codesToMatchAgainst = null; if(details.getIsCovid()) { //codesToMatchAgainst = ValueSetSingleton.getInstance().getCovidValueSetsAsString(); codesToMatchAgainst = ValueSetSingleton.getInstance().getCovidValueSetsAsStringForGrouper(ad.getPath()); logger.info(" Total # of "+ codesToMatchAgainst.size() + " Codes in Trigger Code Value Set for matching for COVID-19"); } else { // codesToMatchAgainst = ValueSetSingleton.getInstance().getValueSets(); codesToMatchAgainst = ValueSetSingleton.getInstance().getValueSetsAsStringForGrouper(ad.getPath()); logger.info(" Total # of "+ codesToMatchAgainst.size() + " Codes in Trigger Code Value Set for matching for Full EICR "); } Set<String> intersection = SetUtils.intersection(codesToMatch, codesToMatchAgainst); if(intersection != null && intersection.size() > 0) { logger.info(" Number of Matched Codes = " + intersection.size()); state.getMatchTriggerStatus().setTriggerMatchStatus(true); matchfound = true; // Hardcoded value set and value set version for CONNECTATHON String valueSet = "2.16.840.1.113762.1.4.1146.1123"; String valuesetVersion = "1"; state.getMatchTriggerStatus().addMatchedCodes(intersection, valueSet, ad.getPath(), valuesetVersion); } else { logger.info(" No Matched codes found for : " + ad.getPath()); } } else { logger.info(" No Codes Found for Path " + ad.getPath()); } } logger.info(" End Matching Trigger Codes "); return matchfound; } public static boolean matchTriggerCodesForR4(List<ActionData> codePaths, R4FhirData data, PatientExecutionState state, LaunchDetails details) { logger.info(" Start Matching Trigger Codes "); boolean matchfound = false; state.getMatchTriggerStatus().setTriggerMatchStatus(false); for(ActionData ad: codePaths) { logger.info(" Need to match Trigger Codes for : " + ad.getPath()); List<CodeableConcept> ptCodes = data.getR4CodesForExpression(ad.getPath()); if(ptCodes != null && ptCodes.size() > 0) { logger.info(" Found a Total # of " + ptCodes.size() + " codes found for Patient." + ad.getPath()); Set<String> codesToMatch = ApplicationUtils.convertR4CodeableConceptsToString(ptCodes); Set<String> codesToMatchAgainst = null; if(details.getIsCovid()) { //codesToMatchAgainst = ValueSetSingleton.getInstance().getCovidValueSetsAsString(); codesToMatchAgainst = ValueSetSingleton.getInstance().getCovidValueSetsAsStringForGrouper(ad.getPath()); logger.info(" Total # of "+ codesToMatchAgainst.size() + " Codes in Trigger Code Value Set for matching for COVID-19"); } else { // codesToMatchAgainst = ValueSetSingleton.getInstance().getValueSets(); codesToMatchAgainst = ValueSetSingleton.getInstance().getValueSetsAsStringForGrouper(ad.getPath()); logger.info(" Total # of "+ codesToMatchAgainst.size() + " Codes in Trigger Code Value Set for matching for Full EICR "); } Set<String> intersection = SetUtils.intersection(codesToMatch, codesToMatchAgainst); if(intersection != null && intersection.size() > 0) { logger.info(" Number of Matched Codes = " + intersection.size()); state.getMatchTriggerStatus().setTriggerMatchStatus(true); matchfound = true; // Hardcoded value set and value set version for CONNECTATHON String valueSet = "2.16.840.1.113762.1.4.1146.1123"; String valuesetVersion = "1"; state.getMatchTriggerStatus().addMatchedCodes(intersection, valueSet, ad.getPath(), valuesetVersion); } else { logger.info(" No Matched codes found for : " + ad.getPath()); } } else { logger.info(" No Codes Found for Path " + ad.getPath()); } } logger.info(" End Matching Trigger Codes "); return matchfound; } }
34.993506
150
0.694006
63520a66d56ef9fc9f3ee913e35d954fab3ea29e
229
package ramdan.file.line.token; public interface LineTokens extends Tokens,Iterable<LineToken> { boolean empty(); int count(); long length(); LineToken head(); LineToken tail(); void add(LineToken lt); }
20.818182
64
0.676856
04ca19b1ab3259e66f7bad58ead4270a5ebbffd5
2,510
package com.tangmu.app.TengKuTV.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.ImageView; import androidx.annotation.Nullable; import com.tangmu.app.TengKuTV.R; public class CheckableImageView extends ImageView implements Checkable { private boolean isChecked; private int unCheckedImg; private int checkedImg; private int tintColor; public CheckableImageView(Context context) { this(context, null); } public CheckableImageView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public CheckableImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CheckableImageView); unCheckedImg = typedArray.getResourceId(R.styleable.CheckableImageView_unCheckedImg, 0); checkedImg = typedArray.getResourceId(R.styleable.CheckableImageView_checkedImg, 0); tintColor = typedArray.getColor(R.styleable.CheckableImageView_tintColor, Color.RED); isChecked = typedArray.getBoolean(R.styleable.CheckableImageView_checked, false); typedArray.recycle(); refresh(); } private void refresh() { if (isChecked) { if (checkedImg != 0) { setImageResource(checkedImg); } else { setColorFilter(tintColor); } } else { if (unCheckedImg != 0) { setImageResource(unCheckedImg); } else { setColorFilter(Color.TRANSPARENT); } } } @Override public void setChecked(boolean checked) { if (isChecked == checked) { return; } isChecked = checked; if (isChecked) { if (checkedImg != 0) { setImageResource(checkedImg); } else { setColorFilter(tintColor); } } else { if (unCheckedImg != 0) { setImageResource(unCheckedImg); } else { setColorFilter(Color.TRANSPARENT); } } } @Override public boolean isChecked() { return isChecked; } @Override public void toggle() { setChecked(!isChecked); } }
28.202247
102
0.618327
8fff65c5d375f8a38ec15fc060f1fba82bf05d7c
893
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.runelite.mapping.Export * net.runelite.mapping.ObfuscatedGetter * net.runelite.mapping.ObfuscatedName * net.runelite.mapping.ObfuscatedSignature */ import java.util.Collection; import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName(value="gd") public class class87 { @ObfuscatedName(value="ry") static Collection field2660; @ObfuscatedName(value="al") @ObfuscatedGetter(intValue=-714780807) @Export(value="musicTrackFileId") static int musicTrackFileId = 0; @ObfuscatedName(value="ai") @ObfuscatedSignature(descriptor="(II)Z", garbageValue="71676174") public static boolean method4760(int n) { return n == 0; } }
27.90625
69
0.739082
2896e44ad75fe80ed6e1aec4af305adab1771344
1,466
package bugs.stackoverflow.belisarius.commands; import java.util.List; import bugs.stackoverflow.belisarius.services.MonitorService; import bugs.stackoverflow.belisarius.utils.CommandUtils; import org.sobotics.chatexchange.chat.Message; public class CommandsCommand implements Command { private final Message message; private final List<Command> commands; public CommandsCommand(Message message, List<Command> commands) { this.message = message; this.commands = commands; } @Override public boolean validate() { return CommandUtils.checkForCommand(this.message.getPlainContent(), this.getName()); } @Override public void execute(MonitorService service) { StringBuilder commandString = new StringBuilder(); for (Command c : this.commands) { commandString.append(" ").append(padRight(c.getName(), 15)).append(" - ").append(c.getDescription()).append("\n"); } service.replyToMessage(this.message.getId(), "The list of commands are as follows:"); service.sendMessageToChat(commandString.toString()); } public static String padRight(String text, int padding) { return String.format("%1$-" + padding + "s", text); } @Override public String getDescription() { return "Returns the list of commands associated with this bot."; } @Override public String getName() { return "commands"; } }
29.32
129
0.680764
415d328a5585c58c1df76c9b47187a28a3a7d1ac
834
package com.vencent.transcloudtranslate.config; /** * @description:跨域配置 * @author: vencent * @create 2020-03-26 **/ /* @Configuration public class CorsConfig implements WebMvcConfigurer { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"). allowedOrigins("*"). //允许跨域的域名,可以用*表示允许任何域名使用 allowedMethods("*"). //允许任何方法(post、get等) allowedHeaders("*"). //允许任何请求头 allowCredentials(true). //带上cookie信息 exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果 } }; } }*/
29.785714
121
0.570743
04457779c857ac84e18fa50a7839ffc57be930a8
545
package jpuppeteer.cdp.client.entity.fetch; /** */ public class FailRequestRequest { /** * An id the client received in requestPaused event. */ public final String requestId; /** * Causes the request to fail with the given reason. */ public final jpuppeteer.cdp.client.constant.network.ErrorReason errorReason; public FailRequestRequest(String requestId, jpuppeteer.cdp.client.constant.network.ErrorReason errorReason) { this.requestId = requestId; this.errorReason = errorReason; } }
24.772727
113
0.702752
d32a089e4567d121e3ebbe2371e95801fbe4720c
157
package jp.osaka.appppy.sample.osakacity.constants; /** * パーツ定義 */ public enum PARTS { LOCATION, URL, CALL, PARKING, FREE, INFO }
11.214286
51
0.598726
9dfee3b91733fd3a276b70d3481deced63508d19
2,258
/* * Copyright (c) 2016, Quancheng-ec.com All right reserved. This software is the confidential and * proprietary information of Quancheng-ec.com ("Confidential Information"). You shall not disclose * such Confidential Information and shall use it only in accordance with the terms of the license * agreement you entered into with Quancheng-ec.com. */ package io.github.saluki.plugin.maven; import java.io.File; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import com.google.common.collect.Lists; import io.github.saluki.plugin.common.CommonProto2Java; /** * @author shimingliu 2016年12月17日 下午12:31:10 * @version CountMojo.java, v 0.0.1 2016年12月17日 下午12:31:10 shimingliu */ @Mojo(name = "proto2java", defaultPhase = LifecyclePhase.GENERATE_SOURCES) public class Proto2Java extends AbstractMojo { @Parameter(defaultValue = "src/main/proto") private String protoPath; @Parameter(defaultValue = "src/main/java") private String buildPath; private List<File> allProtoFile = Lists.newArrayList(); @Override public void execute() throws MojoExecutionException, MojoFailureException { File deirectory = new File(protoPath); listAllProtoFile(deirectory); CommonProto2Java protp2ServicePojo = CommonProto2Java.forConfig(protoPath, buildPath); for (File file : allProtoFile) { if (file.exists()) { String protoFilePath = file.getPath(); protp2ServicePojo.generateFile(protoFilePath); } } } private File listAllProtoFile(File file) { if (file != null) { if (file.isDirectory()) { File[] fileArray = file.listFiles(); if (fileArray != null) { for (int i = 0; i < fileArray.length; i++) { listAllProtoFile(fileArray[i]); } } } else { if (StringUtils.endsWith(file.getName(), "proto")) { allProtoFile.add(file); } } } return null; } }
32.257143
99
0.713906
c53de59ce9fdda2a688bcdffe63108ababb49730
1,465
/** * Created with IntelliJ IDEA. * User: jhasmanyquiroz * Date: 11/17/15 * Time: 11:59 AM * To change this template use File | Settings | File Templates. */ package ui.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import ui.BasePageObject; public class CourseInformationPage extends BasePageObject { @FindBy(xpath = "//button[contains(@data-js-action, 'joinForFree')]") private WebElement enrollButton; @FindBy(xpath = "//a[contains(@class, 'c-spark-cdp-modal-cta')]/button") private WebElement goToCourseButton; @FindBy(xpath = "//h1[contains(@class, 'display-3-text')]") private WebElement titleCourseEnroll; public CourseInformationPage() { PageFactory.initElements(driver, this); waitUntilPageObjectIsLoaded(); } public CourseInformationPage clickEnrollButtonSuccessful() { enrollButton.click(); return this; } public CoursePage clickGoToCourseSuccessfull() { goToCourseButton.click(); return new CoursePage(); } public boolean isTitleCoursePresent(String titleCourse) { return titleCourseEnroll.getText().equalsIgnoreCase(titleCourse); } @Override public void waitUntilPageObjectIsLoaded() { //wait.until(ExpectedConditions.visibilityOf(titleCourseEnroll)); } }
29.3
76
0.713993
9e9cb670ba0d9fac4018e466bbd9534cdb76bb32
5,542
package week1.controller; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import week1.model.Bill; import week1.model.Product; import week1.model.Seller; import java.time.LocalDateTime; public class ProxyITerminalControllerImplTest { private ITerminalController terminalController; @Before public void setUp() throws Exception { terminalController = new ProxyITerminalControllerImpl(ITerminalControllerFactory.create(new Seller())); } @After public void tearDown() throws Exception { terminalController.getAllBills().clear(); terminalController = null; } @Test public void login() throws Exception { terminalController.login("login", "password"); Assert.assertNull(null); } @Test public void createBill() throws Exception { terminalController.createBill(); Assert.assertNull(null); } @Test public void addProduct() throws Exception { Bill bill = terminalController.createBill(); terminalController.addProduct(bill.getId(), new Product()); Assert.assertNull(null); } @Test public void getAllBills() throws Exception { terminalController.getAllBills(); Assert.assertNull(null); } @Test public void closeBill() throws Exception { Bill bill = terminalController.createBill(); terminalController.closeBill(bill.getId()); Assert.assertNull(null); } @Test public void findBillById() throws Exception { Bill bill = terminalController.createBill(); terminalController.findBillById(bill.getId()); Assert.assertNull(null); } @Test public void findSellerByLoginOrFullName() throws Exception { terminalController.findSellerByLoginOrFullName("worker1"); Assert.assertNull(null); } @Test public void getTopOfSalesman() throws Exception { terminalController.createBill(); terminalController.addProduct(0, new Product("Milk", 2.220)); terminalController.addProduct(0, new Product("Cheese", 0.30)); terminalController.addProduct(0, new Product("Milk", 15.50)); terminalController.addProduct(0, new Product("Milk", 2.220)); terminalController.addProduct(0, new Product("Milk", 0.010)); terminalController.addProduct(0, new Product("Milk", 0.010)); terminalController.addProduct(0, new Product("Milk", 0.010));// 20.27 terminalController.login("worker123", "password11"); terminalController.createBill(); terminalController.addProduct(1, new Product("Cake", 27.170)); terminalController.addProduct(1, new Product("Cheese", 33.30)); terminalController.addProduct(1, new Product("Water", 15.50)); terminalController.addProduct(1, new Product("Milk", 2.220)); // 78.19 terminalController.login("worker", "password"); terminalController.createBill(); terminalController.addProduct(2, new Product("Watermelon", 3.990)); terminalController.addProduct(2, new Product("Cheese", 0.30)); terminalController.addProduct(2, new Product("Milk", 15.50)); terminalController.addProduct(2, new Product("Juice", 9.0)); // 28.79 terminalController.getTopOfSalesman(); Assert.assertNull(null); } @Test public void doSomeStatisticStuff() throws Exception { terminalController.createBill(); terminalController.addProduct(0, new Product("Milk", 2.220)); terminalController.addProduct(0, new Product("Cheese", 0.30)); terminalController.addProduct(0, new Product("Milk", 15.50)); terminalController.addProduct(0, new Product("Milk", 2.220)); terminalController.addProduct(0, new Product("Milk", 0.010)); terminalController.addProduct(0, new Product("Milk", 0.010)); terminalController.addProduct(0, new Product("Milk", 0.010));// 20.27 terminalController.login("worker123", "password11"); terminalController.createBill(); terminalController.addProduct(1, new Product("Cake", 27.170)); terminalController.addProduct(1, new Product("Cheese", 33.30)); terminalController.addProduct(1, new Product("Water", 15.50)); terminalController.addProduct(1, new Product("Milk", 2.220)); // 78.19 terminalController.login("worker", "password"); terminalController.createBill(); terminalController.addProduct(2, new Product("Watermelon", 3.990)); terminalController.addProduct(2, new Product("Cheese", 0.30)); terminalController.addProduct(2, new Product("Milk", 15.50)); terminalController.addProduct(2, new Product("Juice", 9.0)); // 28.79 terminalController.doSomeStatisticStuff(); Assert.assertNull(null); } @Test public void filter() throws Exception { LocalDateTime startTime = LocalDateTime.parse("2014-01-01T00:00:00"); LocalDateTime endTime = LocalDateTime.parse("2016-12-31T23:59:59"); terminalController.filter(startTime, endTime, new Bill.CreationDateComparator()); Assert.assertNull(null); } @Test public void turnOnTerminalLogger() throws Exception { terminalController.turnOnTerminalLogger(); Assert.assertNull(null); } @Test public void turnOnDatabaseLogger() throws Exception { terminalController.turnOnDatabaseLogger(); Assert.assertNull(null); } }
33.792683
111
0.673764
cba8c15b7355b54ef59bcda91e7e5c576546cae0
156
package aula.threads; public class ExecutarTelaFilaThread { public static void main(String[] args) { TelaFilaThread tela = new TelaFilaThread(); } }
17.333333
45
0.74359
3185197f179c2c6e4aab8a4b33b3404daf523366
101
package br.com.leonardo.mercadolivre.model.enuns; public enum Status { INICIADA, SUCESSO; }
14.428571
49
0.722772
71fb320f6fdae58d9c35dfcabdf4131e5344dbed
1,705
package org.jakartaeerecipes.chapter06.recipe06_04; import java.util.Iterator; import java.util.List; import javax.persistence.*; import org.jakartaeerecipes.chapter06.entity.BookAuthor06; /** * Recipe 6-4: Persistence Unit Test * * @author juneau */ public class SequenceTest { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("JakartaEERecipesLOCAL"); EntityManager em = emf.createEntityManager(); try { EntityTransaction entr = em.getTransaction(); entr.begin(); BookAuthor06 author = new BookAuthor06(); author.setFirst("JOE"); author.setLast("TESTER"); author.setBio("An author test account."); boolean successful = false; try { em.persist(author); successful = true; } finally { if (successful){ entr.commit(); } else { entr.rollback(); } } Query query = em.createNamedQuery("BookAuthor06.findAll"); List authorList = query.getResultList(); Iterator authorIterator = authorList.iterator(); while (authorIterator.hasNext()) { author = (BookAuthor06) authorIterator.next(); System.out.print("Name:" + author.getFirst() + " " + author.getLast()); System.out.println(); } } catch (Exception ex){ System.err.println(ex); } finally { if (em != null){ em.close(); } } } }
31.574074
99
0.537243
cb21505e2601ad9949102bbeb73fae5a58c3d2db
3,718
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" package com.theartofdev.edmodo.cropper.quick.start; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; public class MainActivity extends AppCompatActivity { /** * Persist URI image to crop URI if specific permissions are required */ private Uri mCropImageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * Start pick image activity with chooser. */ public void onSelectImageClick(View view) { CropImage.startPickImageActivity(this); } @Override @SuppressLint("NewApi") protected void onActivityResult(int requestCode, int resultCode, Intent data) { // handle result of pick image chooser if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) { Uri imageUri = CropImage.getPickImageResultUri(this, data); // For API >= 23 we need to check specifically that we have permissions to read external storage. boolean requirePermissions = false; if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) { // request permissions and handle the result in onRequestPermissionsResult() requirePermissions = true; mCropImageUri = imageUri; requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0); } else { // no permissions required or already grunted, can start crop image activity startCropImageActivity(imageUri); } } // handle result of CropImageActivity if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { ((ImageView) findViewById(R.id.quick_start_cropped_image)).setImageURI(result.getUri()); } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show(); } } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // required permissions granted, start crop image activity startCropImageActivity(mCropImageUri); } else { Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show(); } } /** * Start crop image activity for the given image. */ private void startCropImageActivity(Uri imageUri) { CropImage.activity(imageUri) .setGuidelines(CropImageView.Guidelines.ON) .start(this); } }
36.811881
119
0.678322
69fe02e8e9531193ab963132d84c8eda6f2e3ecf
5,985
package org.intermine.bio.dataconversion; import java.io.Reader; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.ConstraintOp; import org.intermine.metadata.Model; import org.intermine.model.bio.Gene; import org.intermine.model.bio.Organism; import org.intermine.model.bio.Protein; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.query.BagConstraint; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryCollectionReference; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.util.FormattedTextParser; import org.intermine.xml.full.Item; /** * * @author chenyian */ public class PredictedPpiConverter extends BioFileConverter { // private static final Logger LOG = Logger.getLogger(PredictedPpiConverter.class); // // Only human low confidence interactions are available private static final String TAXON_ID = "9606"; private String osAlias = null; public void setOsAlias(String osAlias) { this.osAlias = osAlias; } /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the Model */ public PredictedPpiConverter(ItemWriter writer, Model model) { super(writer, model); } /** * * * {@inheritDoc} */ public void process(Reader reader) throws Exception { getProteinGeneMap(); Iterator<String[]> iterator = FormattedTextParser.parseCsvDelimitedReader(reader); while (iterator.hasNext()) { String[] cols = iterator.next(); Set<String> geneSet1 = proteinGeneMap.get(cols[0]); Set<String> geneSet2 = proteinGeneMap.get(cols[1]); if (geneSet1 == null || geneSet2 == null) { // LOG.info(String.format("null values: %s(%s) -- %s(%s)", cols[0], geneSet1, cols[1], geneSet2)); continue; } if (geneSet1.size() > 1 || geneSet2.size() > 1) { // LOG.info(String.format("multiple results: %s(%s) -- %s(%s)", cols[0], geneSet1.toString(), cols[1], geneSet2.toString())); continue; } String gene1 = geneSet1.iterator().next(); String gene2 = geneSet2.iterator().next(); if (gene1.equals(gene2)) { continue; } createInteraction(gene1, gene2, cols[2]); } } private Set<String> processedInteractions = new HashSet<String>(); private void createInteraction(String gene1, String gene2, String score) throws ObjectStoreException { if (!processedInteractions.contains(gene1 + "-" + gene2) && !processedInteractions.contains(gene2 + "-" + gene1)) { Item interaction1 = createItem("Interaction"); interaction1.setReference("gene1", getGene(gene1)); interaction1.setReference("gene2", getGene(gene2)); interaction1.setAttribute("psopiaScore", score); store(interaction1); Item interaction2 = createItem("Interaction"); interaction2.setReference("gene1", getGene(gene2)); interaction2.setReference("gene2", getGene(gene1)); interaction2.setAttribute("psopiaScore", score); store(interaction2); processedInteractions.add(gene1 + "-" + gene2); } else { // LOG.info(String.format("duplicated pairs: %s -- %s", gene1, gene2)); } } private Map<String, String> geneMap = new HashMap<String, String>(); private String getGene(String geneId) throws ObjectStoreException { String ret = geneMap.get(geneId); if (ret == null) { Item item = createItem("Gene"); item.setAttribute("primaryIdentifier", geneId); store(item); ret = item.getIdentifier(); geneMap.put(geneId, ret); } return ret; } private Map<String, Set<String>> proteinGeneMap = new HashMap<String, Set<String>>(); @SuppressWarnings("unchecked") private void getProteinGeneMap() throws Exception { Query q = new Query(); QueryClass qcProtein = new QueryClass(Protein.class); QueryClass qcGene = new QueryClass(Gene.class); QueryClass qcOrganism = new QueryClass(Organism.class); QueryField qfGeneId = new QueryField(qcGene, "primaryIdentifier"); QueryField qfPrimaryAcc = new QueryField(qcProtein, "primaryAccession"); QueryField qfOrganismTaxonId = new QueryField(qcOrganism, "taxonId"); q.addFrom(qcProtein); q.addFrom(qcOrganism); q.addFrom(qcGene); q.addToSelect(qfPrimaryAcc); q.addToSelect(qfGeneId); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); // organism in our list cs.addConstraint(new BagConstraint(qfOrganismTaxonId, ConstraintOp.IN, Arrays.asList(TAXON_ID))); QueryObjectReference qor = new QueryObjectReference(qcProtein, "organism"); cs.addConstraint(new ContainsConstraint(qor, ConstraintOp.CONTAINS, qcOrganism)); QueryCollectionReference qcr = new QueryCollectionReference(qcProtein, "genes"); cs.addConstraint(new ContainsConstraint(qcr, ConstraintOp.CONTAINS, qcGene)); q.setConstraint(cs); ObjectStore os = ObjectStoreFactory.getObjectStore(osAlias); Results results = os.execute(q); Iterator<Object> iterator = results.iterator(); while (iterator.hasNext()) { ResultsRow<String> rr = (ResultsRow<String>) iterator.next(); String proteinAcc = rr.get(0); if (proteinGeneMap.get(proteinAcc) == null) { proteinGeneMap.put(proteinAcc, new HashSet<String>()); } proteinGeneMap.get(proteinAcc).add(rr.get(1)); } } }
34.595376
131
0.715957
e3a3bd2c80e8982022f49ecdc3244627e9ce5dc9
210
package com.viseator.chartit; /** * Created by viseator on 10/18/17. * Wu Di * viseator@gmail.com */ public abstract class ChartViewFragment extends BaseFragment{ public abstract void updateData(); }
17.5
61
0.728571
41aa18fa96ca510c9beedc2dc49a369aabdd8ad6
41,102
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|bootstrap operator|. name|load operator|. name|table package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|TableType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|Warehouse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|api operator|. name|Database import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|api operator|. name|InvalidOperationException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|api operator|. name|MetaException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl operator|. name|DDLWork import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl operator|. name|table operator|. name|partition operator|. name|add operator|. name|AlterTableAddPartitionDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl operator|. name|table operator|. name|partition operator|. name|drop operator|. name|AlterTableDropPartitionDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|ReplCopyTask import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Task import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|TaskFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|Utilities import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|ReplExternalTables import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|util operator|. name|ReplUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|util operator|. name|ReplUtils operator|. name|ReplLoadOpType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|bootstrap operator|. name|events operator|. name|TableEvent import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|bootstrap operator|. name|load operator|. name|ReplicationState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|util operator|. name|TaskTracker import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|bootstrap operator|. name|load operator|. name|util operator|. name|Context import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|bootstrap operator|. name|load operator|. name|util operator|. name|PathUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|io operator|. name|AcidUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|HiveException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|Partition import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|Table import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|EximUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|HiveTableName import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|ImportSemanticAnalyzer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|SemanticException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|repl operator|. name|ReplLogger import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|ExprNodeGenericFuncDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|ImportTableDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|LoadMultiFilesDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|LoadTableDesc import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|LoadTableDesc operator|. name|LoadFileType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|plan operator|. name|MoveWork import|; end_import begin_import import|import name|org operator|. name|datanucleus operator|. name|util operator|. name|StringUtils import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|java operator|. name|io operator|. name|Serializable import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Iterator import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|conf operator|. name|HiveConf operator|. name|ConfVars operator|. name|REPL_ENABLE_MOVE_OPTIMIZATION import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|exec operator|. name|repl operator|. name|bootstrap operator|. name|load operator|. name|ReplicationState operator|. name|PartitionState import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|ImportSemanticAnalyzer operator|. name|isPartitioned import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|parse operator|. name|ImportSemanticAnalyzer operator|. name|partSpecToString import|; end_import begin_class specifier|public class|class name|LoadPartitions block|{ specifier|private specifier|static name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|LoadPartitions operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|final name|Context name|context decl_stmt|; specifier|private specifier|final name|ReplLogger name|replLogger decl_stmt|; specifier|private specifier|final name|TableContext name|tableContext decl_stmt|; specifier|private specifier|final name|TableEvent name|event decl_stmt|; specifier|private specifier|final name|TaskTracker name|tracker decl_stmt|; specifier|private specifier|final name|AlterTableAddPartitionDesc name|lastReplicatedPartition decl_stmt|; specifier|private specifier|final name|ImportTableDesc name|tableDesc decl_stmt|; specifier|private name|Table name|table decl_stmt|; specifier|public name|LoadPartitions parameter_list|( name|Context name|context parameter_list|, name|ReplLogger name|replLogger parameter_list|, name|TaskTracker name|tableTracker parameter_list|, name|TableEvent name|event parameter_list|, name|String name|dbNameToLoadIn parameter_list|, name|TableContext name|tableContext parameter_list|) throws|throws name|HiveException block|{ name|this argument_list|( name|context argument_list|, name|replLogger argument_list|, name|tableContext argument_list|, name|tableTracker argument_list|, name|event argument_list|, name|dbNameToLoadIn argument_list|, literal|null argument_list|) expr_stmt|; block|} specifier|public name|LoadPartitions parameter_list|( name|Context name|context parameter_list|, name|ReplLogger name|replLogger parameter_list|, name|TableContext name|tableContext parameter_list|, name|TaskTracker name|limiter parameter_list|, name|TableEvent name|event parameter_list|, name|String name|dbNameToLoadIn parameter_list|, name|AlterTableAddPartitionDesc name|lastReplicatedPartition parameter_list|) throws|throws name|HiveException block|{ name|this operator|. name|tracker operator|= operator|new name|TaskTracker argument_list|( name|limiter argument_list|) expr_stmt|; name|this operator|. name|event operator|= name|event expr_stmt|; name|this operator|. name|context operator|= name|context expr_stmt|; name|this operator|. name|replLogger operator|= name|replLogger expr_stmt|; name|this operator|. name|lastReplicatedPartition operator|= name|lastReplicatedPartition expr_stmt|; name|this operator|. name|tableContext operator|= name|tableContext expr_stmt|; name|this operator|. name|tableDesc operator|= name|event operator|. name|tableDesc argument_list|( name|dbNameToLoadIn argument_list|) expr_stmt|; name|this operator|. name|table operator|= name|ImportSemanticAnalyzer operator|. name|tableIfExists argument_list|( name|tableDesc argument_list|, name|context operator|. name|hiveDb argument_list|) expr_stmt|; block|} specifier|public name|TaskTracker name|tasks parameter_list|() throws|throws name|Exception block|{ comment|/* We are doing this both in load table and load partitions */ name|Database name|parentDb init|= name|context operator|. name|hiveDb operator|. name|getDatabase argument_list|( name|tableDesc operator|. name|getDatabaseName argument_list|() argument_list|) decl_stmt|; name|LoadTable operator|. name|TableLocationTuple name|tableLocationTuple init|= name|LoadTable operator|. name|tableLocation argument_list|( name|tableDesc argument_list|, name|parentDb argument_list|, name|tableContext argument_list|, name|context argument_list|) decl_stmt|; name|tableDesc operator|. name|setLocation argument_list|( name|tableLocationTuple operator|. name|location argument_list|) expr_stmt|; if|if condition|( name|table operator|== literal|null condition|) block|{ comment|//new table name|table operator|= name|tableDesc operator|. name|toTable argument_list|( name|context operator|. name|hiveConf argument_list|) expr_stmt|; if|if condition|( name|isPartitioned argument_list|( name|tableDesc argument_list|) condition|) block|{ name|updateReplicationState argument_list|( name|initialReplicationState argument_list|() argument_list|) expr_stmt|; if|if condition|( operator|! name|forNewTable argument_list|() operator|. name|hasReplicationState argument_list|() condition|) block|{ comment|// Add ReplStateLogTask only if no pending table load tasks left for next cycle name|Task argument_list|< name|? argument_list|> name|replLogTask init|= name|ReplUtils operator|. name|getTableReplLogTask argument_list|( name|tableDesc argument_list|, name|replLogger argument_list|, name|context operator|. name|hiveConf argument_list|) decl_stmt|; name|tracker operator|. name|addDependentTask argument_list|( name|replLogTask argument_list|) expr_stmt|; block|} return|return name|tracker return|; block|} block|} else|else block|{ comment|// existing if|if condition|( name|table operator|. name|isPartitioned argument_list|() condition|) block|{ name|List argument_list|< name|AlterTableAddPartitionDesc argument_list|> name|partitionDescs init|= name|event operator|. name|partitionDescriptions argument_list|( name|tableDesc argument_list|) decl_stmt|; if|if condition|( operator|! name|event operator|. name|replicationSpec argument_list|() operator|. name|isMetadataOnly argument_list|() operator|&& operator|! name|partitionDescs operator|. name|isEmpty argument_list|() condition|) block|{ name|updateReplicationState argument_list|( name|initialReplicationState argument_list|() argument_list|) expr_stmt|; if|if condition|( operator|! name|forExistingTable argument_list|( name|lastReplicatedPartition argument_list|) operator|. name|hasReplicationState argument_list|() condition|) block|{ comment|// Add ReplStateLogTask only if no pending table load tasks left for next cycle name|Task argument_list|< name|? argument_list|> name|replLogTask init|= name|ReplUtils operator|. name|getTableReplLogTask argument_list|( name|tableDesc argument_list|, name|replLogger argument_list|, name|context operator|. name|hiveConf argument_list|) decl_stmt|; name|tracker operator|. name|addDependentTask argument_list|( name|replLogTask argument_list|) expr_stmt|; block|} return|return name|tracker return|; block|} block|} block|} return|return name|tracker return|; block|} specifier|private name|void name|updateReplicationState parameter_list|( name|ReplicationState name|replicationState parameter_list|) block|{ if|if condition|( operator|! name|tracker operator|. name|canAddMoreTasks argument_list|() condition|) block|{ name|tracker operator|. name|setReplicationState argument_list|( name|replicationState argument_list|) expr_stmt|; block|} block|} specifier|private name|ReplicationState name|initialReplicationState parameter_list|() throws|throws name|SemanticException block|{ return|return operator|new name|ReplicationState argument_list|( operator|new name|PartitionState argument_list|( name|tableDesc operator|. name|getTableName argument_list|() argument_list|, name|lastReplicatedPartition argument_list|) argument_list|) return|; block|} specifier|private name|TaskTracker name|forNewTable parameter_list|() throws|throws name|Exception block|{ name|Iterator argument_list|< name|AlterTableAddPartitionDesc argument_list|> name|iterator init|= name|event operator|. name|partitionDescriptions argument_list|( name|tableDesc argument_list|) operator|. name|iterator argument_list|() decl_stmt|; while|while condition|( name|iterator operator|. name|hasNext argument_list|() operator|&& name|tracker operator|. name|canAddMoreTasks argument_list|() condition|) block|{ name|AlterTableAddPartitionDesc name|currentPartitionDesc init|= name|iterator operator|. name|next argument_list|() decl_stmt|; comment|/* the currentPartitionDesc cannot be inlined as we need the hasNext() to be evaluated post the current retrieved lastReplicatedPartition */ name|addPartition argument_list|( name|iterator operator|. name|hasNext argument_list|() argument_list|, name|currentPartitionDesc argument_list|, literal|null argument_list|) expr_stmt|; block|} return|return name|tracker return|; block|} specifier|private name|void name|addPartition parameter_list|( name|boolean name|hasMorePartitions parameter_list|, name|AlterTableAddPartitionDesc name|addPartitionDesc parameter_list|, name|Task argument_list|< name|? argument_list|> name|ptnRootTask parameter_list|) throws|throws name|Exception block|{ name|tracker operator|. name|addTask argument_list|( name|tasksForAddPartition argument_list|( name|table argument_list|, name|addPartitionDesc argument_list|, name|ptnRootTask argument_list|) argument_list|) expr_stmt|; if|if condition|( name|hasMorePartitions operator|&& operator|! name|tracker operator|. name|canAddMoreTasks argument_list|() condition|) block|{ name|ReplicationState name|currentReplicationState init|= operator|new name|ReplicationState argument_list|( operator|new name|PartitionState argument_list|( name|table operator|. name|getTableName argument_list|() argument_list|, name|addPartitionDesc argument_list|) argument_list|) decl_stmt|; name|updateReplicationState argument_list|( name|currentReplicationState argument_list|) expr_stmt|; block|} block|} comment|/** * returns the root task for adding a partition */ specifier|private name|Task argument_list|< name|? argument_list|> name|tasksForAddPartition parameter_list|( name|Table name|table parameter_list|, name|AlterTableAddPartitionDesc name|addPartitionDesc parameter_list|, name|Task argument_list|< name|? argument_list|> name|ptnRootTask parameter_list|) throws|throws name|MetaException throws|, name|HiveException block|{ name|AlterTableAddPartitionDesc operator|. name|PartitionDesc name|partSpec init|= name|addPartitionDesc operator|. name|getPartitions argument_list|() operator|. name|get argument_list|( literal|0 argument_list|) decl_stmt|; name|Path name|sourceWarehousePartitionLocation init|= operator|new name|Path argument_list|( name|partSpec operator|. name|getLocation argument_list|() argument_list|) decl_stmt|; name|Path name|replicaWarehousePartitionLocation init|= name|locationOnReplicaWarehouse argument_list|( name|table argument_list|, name|partSpec argument_list|) decl_stmt|; name|partSpec operator|. name|setLocation argument_list|( name|replicaWarehousePartitionLocation operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|LOG operator|. name|debug argument_list|( literal|"adding dependent CopyWork/AddPart/MoveWork for partition " operator|+ name|partSpecToString argument_list|( name|partSpec operator|. name|getPartSpec argument_list|() argument_list|) operator|+ literal|" with source location: " operator|+ name|partSpec operator|. name|getLocation argument_list|() argument_list|) expr_stmt|; name|Task argument_list|< name|? argument_list|> name|addPartTask init|= name|TaskFactory operator|. name|get argument_list|( operator|new name|DDLWork argument_list|( operator|new name|HashSet argument_list|<> argument_list|() argument_list|, operator|new name|HashSet argument_list|<> argument_list|() argument_list|, name|addPartitionDesc argument_list|) argument_list|, name|context operator|. name|hiveConf argument_list|) decl_stmt|; name|Task argument_list|< name|? argument_list|> name|ckptTask init|= name|ReplUtils operator|. name|getTableCheckpointTask argument_list|( name|tableDesc argument_list|, operator|( name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> operator|) name|partSpec operator|. name|getPartSpec argument_list|() argument_list|, name|context operator|. name|dumpDirectory argument_list|, name|context operator|. name|hiveConf argument_list|) decl_stmt|; name|boolean name|isOnlyDDLOperation init|= name|event operator|. name|replicationSpec argument_list|() operator|. name|isMetadataOnly argument_list|() operator||| operator|( name|TableType operator|. name|EXTERNAL_TABLE operator|. name|equals argument_list|( name|table operator|. name|getTableType argument_list|() argument_list|) operator|&& operator|! name|event operator|. name|replicationSpec argument_list|() operator|. name|isMigratingToExternalTable argument_list|() operator|) decl_stmt|; if|if condition|( name|isOnlyDDLOperation condition|) block|{ comment|// Set Checkpoint task as dependant to add partition tasks. So, if same dump is retried for comment|// bootstrap, we skip current partition update. name|addPartTask operator|. name|addDependentTask argument_list|( name|ckptTask argument_list|) expr_stmt|; if|if condition|( name|ptnRootTask operator|== literal|null condition|) block|{ name|ptnRootTask operator|= name|addPartTask expr_stmt|; block|} else|else block|{ name|ptnRootTask operator|. name|addDependentTask argument_list|( name|addPartTask argument_list|) expr_stmt|; block|} return|return name|ptnRootTask return|; block|} name|Path name|stagingDir init|= name|replicaWarehousePartitionLocation decl_stmt|; comment|// if move optimization is enabled, copy the files directly to the target path. No need to create the staging dir. name|LoadFileType name|loadFileType decl_stmt|; if|if condition|( name|event operator|. name|replicationSpec argument_list|() operator|. name|isInReplicationScope argument_list|() operator|&& name|context operator|. name|hiveConf operator|. name|getBoolVar argument_list|( name|REPL_ENABLE_MOVE_OPTIMIZATION argument_list|) condition|) block|{ name|loadFileType operator|= name|LoadFileType operator|. name|IGNORE expr_stmt|; if|if condition|( name|event operator|. name|replicationSpec argument_list|() operator|. name|isMigratingToTxnTable argument_list|() condition|) block|{ comment|// Migrating to transactional tables in bootstrap load phase. comment|// It is enough to copy all the original files under base_1 dir and so write-id is hardcoded to 1. comment|// ReplTxnTask added earlier in the DAG ensure that the write-id=1 is made valid in HMS metadata. name|stagingDir operator|= operator|new name|Path argument_list|( name|stagingDir argument_list|, name|AcidUtils operator|. name|baseDir argument_list|( name|ReplUtils operator|. name|REPL_BOOTSTRAP_MIGRATION_BASE_WRITE_ID argument_list|) argument_list|) expr_stmt|; block|} block|} else|else block|{ name|loadFileType operator|= name|event operator|. name|replicationSpec argument_list|() operator|. name|isReplace argument_list|() condition|? name|LoadFileType operator|. name|REPLACE_ALL else|: operator|( name|event operator|. name|replicationSpec argument_list|() operator|. name|isMigratingToTxnTable argument_list|() condition|? name|LoadFileType operator|. name|KEEP_EXISTING else|: name|LoadFileType operator|. name|OVERWRITE_EXISTING operator|) expr_stmt|; name|stagingDir operator|= name|PathUtils operator|. name|getExternalTmpPath argument_list|( name|replicaWarehousePartitionLocation argument_list|, name|context operator|. name|pathInfo argument_list|) expr_stmt|; block|} name|Task argument_list|< name|? argument_list|> name|copyTask init|= name|ReplCopyTask operator|. name|getLoadCopyTask argument_list|( name|event operator|. name|replicationSpec argument_list|() argument_list|, operator|new name|Path argument_list|( name|sourceWarehousePartitionLocation argument_list|, name|EximUtil operator|. name|DATA_PATH_NAME argument_list|) argument_list|, name|stagingDir argument_list|, name|context operator|. name|hiveConf argument_list|, literal|false argument_list|) decl_stmt|; name|Task argument_list|< name|? argument_list|> name|movePartitionTask init|= literal|null decl_stmt|; if|if condition|( name|loadFileType operator|!= name|LoadFileType operator|. name|IGNORE condition|) block|{ comment|// no need to create move task, if file is moved directly to target location. name|movePartitionTask operator|= name|movePartitionTask argument_list|( name|table argument_list|, name|partSpec argument_list|, name|stagingDir argument_list|, name|loadFileType argument_list|) expr_stmt|; block|} if|if condition|( name|ptnRootTask operator|== literal|null condition|) block|{ name|ptnRootTask operator|= name|copyTask expr_stmt|; block|} else|else block|{ name|ptnRootTask operator|. name|addDependentTask argument_list|( name|copyTask argument_list|) expr_stmt|; block|} comment|// Set Checkpoint task as dependant to the tail of add partition tasks. So, if same dump is comment|// retried for bootstrap, we skip current partition update. name|copyTask operator|. name|addDependentTask argument_list|( name|addPartTask argument_list|) expr_stmt|; if|if condition|( name|movePartitionTask operator|!= literal|null condition|) block|{ name|addPartTask operator|. name|addDependentTask argument_list|( name|movePartitionTask argument_list|) expr_stmt|; name|movePartitionTask operator|. name|addDependentTask argument_list|( name|ckptTask argument_list|) expr_stmt|; block|} else|else block|{ name|addPartTask operator|. name|addDependentTask argument_list|( name|ckptTask argument_list|) expr_stmt|; block|} return|return name|ptnRootTask return|; block|} comment|/** * This will create the move of partition data from temp path to actual path */ specifier|private name|Task argument_list|< name|? argument_list|> name|movePartitionTask parameter_list|( name|Table name|table parameter_list|, name|AlterTableAddPartitionDesc operator|. name|PartitionDesc name|partSpec parameter_list|, name|Path name|tmpPath parameter_list|, name|LoadFileType name|loadFileType parameter_list|) block|{ name|MoveWork name|moveWork init|= operator|new name|MoveWork argument_list|( operator|new name|HashSet argument_list|<> argument_list|() argument_list|, operator|new name|HashSet argument_list|<> argument_list|() argument_list|, literal|null argument_list|, literal|null argument_list|, literal|false argument_list|) decl_stmt|; if|if condition|( name|AcidUtils operator|. name|isTransactionalTable argument_list|( name|table argument_list|) condition|) block|{ if|if condition|( name|event operator|. name|replicationSpec argument_list|() operator|. name|isMigratingToTxnTable argument_list|() condition|) block|{ comment|// Write-id is hardcoded to 1 so that for migration, we just move all original files under base_1 dir. comment|// ReplTxnTask added earlier in the DAG ensure that the write-id is made valid in HMS metadata. name|LoadTableDesc name|loadTableWork init|= operator|new name|LoadTableDesc argument_list|( name|tmpPath argument_list|, name|Utilities operator|. name|getTableDesc argument_list|( name|table argument_list|) argument_list|, name|partSpec operator|. name|getPartSpec argument_list|() argument_list|, name|loadFileType argument_list|, name|ReplUtils operator|. name|REPL_BOOTSTRAP_MIGRATION_BASE_WRITE_ID argument_list|) decl_stmt|; name|loadTableWork operator|. name|setInheritTableSpecs argument_list|( literal|false argument_list|) expr_stmt|; name|loadTableWork operator|. name|setStmtId argument_list|( literal|0 argument_list|) expr_stmt|; comment|// Need to set insertOverwrite so base_1 is created instead of delta_1_1_0. name|loadTableWork operator|. name|setInsertOverwrite argument_list|( literal|true argument_list|) expr_stmt|; name|moveWork operator|. name|setLoadTableWork argument_list|( name|loadTableWork argument_list|) expr_stmt|; block|} else|else block|{ name|LoadMultiFilesDesc name|loadFilesWork init|= operator|new name|LoadMultiFilesDesc argument_list|( name|Collections operator|. name|singletonList argument_list|( name|tmpPath argument_list|) argument_list|, name|Collections operator|. name|singletonList argument_list|( operator|new name|Path argument_list|( name|partSpec operator|. name|getLocation argument_list|() argument_list|) argument_list|) argument_list|, literal|true argument_list|, literal|null argument_list|, literal|null argument_list|) decl_stmt|; name|moveWork operator|. name|setMultiFilesDesc argument_list|( name|loadFilesWork argument_list|) expr_stmt|; block|} block|} else|else block|{ name|LoadTableDesc name|loadTableWork init|= operator|new name|LoadTableDesc argument_list|( name|tmpPath argument_list|, name|Utilities operator|. name|getTableDesc argument_list|( name|table argument_list|) argument_list|, name|partSpec operator|. name|getPartSpec argument_list|() argument_list|, name|loadFileType argument_list|, literal|0L argument_list|) decl_stmt|; name|loadTableWork operator|. name|setInheritTableSpecs argument_list|( literal|false argument_list|) expr_stmt|; name|moveWork operator|. name|setLoadTableWork argument_list|( name|loadTableWork argument_list|) expr_stmt|; block|} name|moveWork operator|. name|setIsInReplicationScope argument_list|( name|event operator|. name|replicationSpec argument_list|() operator|. name|isInReplicationScope argument_list|() argument_list|) expr_stmt|; return|return name|TaskFactory operator|. name|get argument_list|( name|moveWork argument_list|, name|context operator|. name|hiveConf argument_list|) return|; block|} comment|/** * Since the table level location will be set by taking into account the base directory configuration * for external table, we don't have to do anything specific for partition location since it will always * be a child of the table level location. * Looks like replication does not handle a specific location provided for a partition and the partition * path will always be a child on target. */ specifier|private name|Path name|locationOnReplicaWarehouse parameter_list|( name|Table name|table parameter_list|, name|AlterTableAddPartitionDesc operator|. name|PartitionDesc name|partSpec parameter_list|) throws|throws name|MetaException throws|, name|HiveException block|{ name|String name|child init|= name|Warehouse operator|. name|makePartPath argument_list|( name|partSpec operator|. name|getPartSpec argument_list|() argument_list|) decl_stmt|; if|if condition|( name|tableDesc operator|. name|isExternal argument_list|() condition|) block|{ if|if condition|( name|event operator|. name|replicationSpec argument_list|() operator|. name|isMigratingToExternalTable argument_list|() condition|) block|{ return|return operator|new name|Path argument_list|( name|tableDesc operator|. name|getLocation argument_list|() argument_list|, name|child argument_list|) return|; block|} name|String name|externalLocation init|= name|ReplExternalTables operator|. name|externalTableLocation argument_list|( name|context operator|. name|hiveConf argument_list|, name|partSpec operator|. name|getLocation argument_list|() argument_list|) decl_stmt|; return|return operator|new name|Path argument_list|( name|externalLocation argument_list|) return|; block|} if|if condition|( name|tableDesc operator|. name|getLocation argument_list|() operator|== literal|null condition|) block|{ if|if condition|( name|table operator|. name|getDataLocation argument_list|() operator|== literal|null condition|) block|{ name|Database name|parentDb init|= name|context operator|. name|hiveDb operator|. name|getDatabase argument_list|( name|tableDesc operator|. name|getDatabaseName argument_list|() argument_list|) decl_stmt|; return|return operator|new name|Path argument_list|( name|context operator|. name|warehouse operator|. name|getDefaultTablePath argument_list|( name|parentDb argument_list|, name|tableDesc operator|. name|getTableName argument_list|() argument_list|, name|tableDesc operator|. name|isExternal argument_list|() argument_list|) argument_list|, name|child argument_list|) return|; block|} else|else block|{ return|return operator|new name|Path argument_list|( name|table operator|. name|getDataLocation argument_list|() operator|. name|toString argument_list|() argument_list|, name|child argument_list|) return|; block|} block|} else|else block|{ return|return operator|new name|Path argument_list|( name|tableDesc operator|. name|getLocation argument_list|() argument_list|, name|child argument_list|) return|; block|} block|} specifier|private name|Task argument_list|< name|? argument_list|> name|dropPartitionTask parameter_list|( name|Table name|table parameter_list|, name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|partSpec parameter_list|) throws|throws name|SemanticException block|{ name|Task argument_list|< name|DDLWork argument_list|> name|dropPtnTask init|= literal|null decl_stmt|; name|Map argument_list|< name|Integer argument_list|, name|List argument_list|< name|ExprNodeGenericFuncDesc argument_list|> argument_list|> name|partSpecsExpr init|= name|ReplUtils operator|. name|genPartSpecs argument_list|( name|table argument_list|, name|Collections operator|. name|singletonList argument_list|( name|partSpec argument_list|) argument_list|) decl_stmt|; if|if condition|( name|partSpecsExpr operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ name|AlterTableDropPartitionDesc name|dropPtnDesc init|= operator|new name|AlterTableDropPartitionDesc argument_list|( name|HiveTableName operator|. name|of argument_list|( name|table argument_list|) argument_list|, name|partSpecsExpr argument_list|, literal|true argument_list|, name|event operator|. name|replicationSpec argument_list|() argument_list|) decl_stmt|; name|dropPtnTask operator|= name|TaskFactory operator|. name|get argument_list|( operator|new name|DDLWork argument_list|( operator|new name|HashSet argument_list|<> argument_list|() argument_list|, operator|new name|HashSet argument_list|<> argument_list|() argument_list|, name|dropPtnDesc argument_list|) argument_list|, name|context operator|. name|hiveConf argument_list|) expr_stmt|; block|} return|return name|dropPtnTask return|; block|} specifier|private name|TaskTracker name|forExistingTable parameter_list|( name|AlterTableAddPartitionDesc name|lastPartitionReplicated parameter_list|) throws|throws name|Exception block|{ name|boolean name|encounteredTheLastReplicatedPartition init|= operator|( name|lastPartitionReplicated operator|== literal|null operator|) decl_stmt|; name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|lastReplicatedPartSpec init|= literal|null decl_stmt|; if|if condition|( operator|! name|encounteredTheLastReplicatedPartition condition|) block|{ name|lastReplicatedPartSpec operator|= name|lastPartitionReplicated operator|. name|getPartitions argument_list|() operator|. name|get argument_list|( literal|0 argument_list|) operator|. name|getPartSpec argument_list|() expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Start processing from partition info spec : {}" argument_list|, name|StringUtils operator|. name|mapToString argument_list|( name|lastReplicatedPartSpec argument_list|) argument_list|) expr_stmt|; block|} name|Iterator argument_list|< name|AlterTableAddPartitionDesc argument_list|> name|partitionIterator init|= name|event operator|. name|partitionDescriptions argument_list|( name|tableDesc argument_list|) operator|. name|iterator argument_list|() decl_stmt|; while|while condition|( operator|! name|encounteredTheLastReplicatedPartition operator|&& name|partitionIterator operator|. name|hasNext argument_list|() condition|) block|{ name|AlterTableAddPartitionDesc name|addPartitionDesc init|= name|partitionIterator operator|. name|next argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|currentSpec init|= name|addPartitionDesc operator|. name|getPartitions argument_list|() operator|. name|get argument_list|( literal|0 argument_list|) operator|. name|getPartSpec argument_list|() decl_stmt|; name|encounteredTheLastReplicatedPartition operator|= name|lastReplicatedPartSpec operator|. name|equals argument_list|( name|currentSpec argument_list|) expr_stmt|; block|} while|while condition|( name|partitionIterator operator|. name|hasNext argument_list|() operator|&& name|tracker operator|. name|canAddMoreTasks argument_list|() condition|) block|{ name|AlterTableAddPartitionDesc name|addPartitionDesc init|= name|partitionIterator operator|. name|next argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|partSpec init|= name|addPartitionDesc operator|. name|getPartitions argument_list|() operator|. name|get argument_list|( literal|0 argument_list|) operator|. name|getPartSpec argument_list|() decl_stmt|; name|Task argument_list|< name|? argument_list|> name|ptnRootTask init|= literal|null decl_stmt|; name|ReplLoadOpType name|loadPtnType init|= name|getLoadPartitionType argument_list|( name|partSpec argument_list|) decl_stmt|; switch|switch condition|( name|loadPtnType condition|) block|{ case|case name|LOAD_NEW case|: break|break; case|case name|LOAD_REPLACE case|: name|ptnRootTask operator|= name|dropPartitionTask argument_list|( name|table argument_list|, name|partSpec argument_list|) expr_stmt|; break|break; case|case name|LOAD_SKIP case|: continue|continue; default|default: break|break; block|} name|addPartition argument_list|( name|partitionIterator operator|. name|hasNext argument_list|() argument_list|, name|addPartitionDesc argument_list|, name|ptnRootTask argument_list|) expr_stmt|; block|} return|return name|tracker return|; block|} specifier|private name|ReplLoadOpType name|getLoadPartitionType parameter_list|( name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|partSpec parameter_list|) throws|throws name|InvalidOperationException throws|, name|HiveException block|{ name|Partition name|ptn init|= name|context operator|. name|hiveDb operator|. name|getPartition argument_list|( name|table argument_list|, name|partSpec argument_list|, literal|false argument_list|) decl_stmt|; if|if condition|( name|ptn operator|== literal|null condition|) block|{ return|return name|ReplLoadOpType operator|. name|LOAD_NEW return|; block|} if|if condition|( name|ReplUtils operator|. name|replCkptStatus argument_list|( name|tableContext operator|. name|dbNameToLoadIn argument_list|, name|ptn operator|. name|getParameters argument_list|() argument_list|, name|context operator|. name|dumpDirectory argument_list|) condition|) block|{ return|return name|ReplLoadOpType operator|. name|LOAD_SKIP return|; block|} return|return name|ReplLoadOpType operator|. name|LOAD_REPLACE return|; block|} block|} end_class end_unit
14.366305
813
0.810812
cf2fc20a0a218f6378278cf9a1c1c3e494fb7dac
2,129
package cn.rzedu.sc.goods.config; import com.github.wxpay.sdk.WXPayConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.ByteArrayInputStream; import java.io.InputStream; @Component public class SFWXPayConfig implements WXPayConfig { /** 微信分配的公众号ID */ private static String APP_ID; /** 微信支付分配的商户号 */ private static String MCH_ID; /** 商户平台设置的密钥key */ private static String KEY; /** 接收微信支付结果通知的回调地址 */ private static String NOTIFY_URL; @Value("${wechat.config.appId}") public void setAPP_ID(String appId) { SFWXPayConfig.APP_ID = appId; } @Value("${wechat.config.pay.mchId}") public void setMCH_ID(String mchId) { SFWXPayConfig.MCH_ID = mchId; } @Value("${wechat.config.pay.key}") public void setKEY(String key) { SFWXPayConfig.KEY = key; } @Value("${wechat.config.pay.notifyUrl}") public void setNOTIFY_URL(String notifyUrl) { SFWXPayConfig.NOTIFY_URL = notifyUrl; } public String getNotifyUrl() { return NOTIFY_URL; } private byte[] certData; public SFWXPayConfig() throws Exception { /* String certPath = ""; File file = new File(certPath); InputStream certStream = new FileInputStream(file); this.certData = new byte[(int) file.length()]; certStream.read(this.certData); certStream.close();*/ } @Override public String getAppID() { return APP_ID; } @Override public String getMchID() { return MCH_ID; } @Override public String getKey() { return KEY; } @Override public InputStream getCertStream() { ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData); return certBis; } @Override public int getHttpConnectTimeoutMs() { return 8000; } @Override public int getHttpReadTimeoutMs() { return 10000; } }
23.141304
80
0.612964
f24649832129c22feefcdd3285ae21a5e085c917
768
package net.minecraft.src; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public class NBTTagString extends NBTBase { public String stringValue; public NBTTagString() { } public NBTTagString(String var1) { this.stringValue = var1; if (var1 == null) { throw new IllegalArgumentException("Empty string not allowed"); } } void writeTagContents(DataOutput var1) throws IOException { var1.writeUTF(this.stringValue); } void readTagContents(DataInput var1) throws IOException { this.stringValue = var1.readUTF(); } public byte getType() { return 8; } public String toString() { return "" + this.stringValue; } }
21.333333
75
0.643229
f3dc3142a98dcc1a0a3c4c1ffc6931a56ee862ca
1,940
package com.intelligentmusicplayer.android.musicplaying; import android.content.Context; import android.media.MediaPlayer; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.MediaSourceFactory; import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DataSpec; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.upstream.RawResourceDataSource; import com.google.android.exoplayer2.util.Util; import com.intelligentmusicplayer.android.MyApplication; import com.intelligentmusicplayer.android.R; public class MusicDataInner extends MusicData { private int id; public MusicDataInner(String title,int id){ super(title); this.id = id; } @Override public MediaSource getMediaSource() { //构建Raw文件播放源--RawResourceDataSource DataSpec dataSpec = new DataSpec(RawResourceDataSource.buildRawResourceUri(id)); final RawResourceDataSource rawResourceDataSource = new RawResourceDataSource(MyApplication.getContext()); try { rawResourceDataSource.open(dataSpec); } catch (RawResourceDataSource.RawResourceDataSourceException e) { e.printStackTrace(); } //构建ExoPlayer能识别的播放源--MediaSource DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(MyApplication.getContext(), Util.getUserAgent(MyApplication.getContext(), "intelligentMusicPlayer")); MediaSource dataSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(rawResourceDataSource.getUri()); return dataSource; } }
41.276596
120
0.773711
8a7d93dede35cc9432c233e33de2296c93e23ebb
9,742
/* * Copyright (c) 2019 Hydrox6 <ikada@protonmail.ch> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.dps; import com.google.inject.Provides; import net.runelite.api.*; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.InteractingChanged; import net.runelite.api.events.StatChanged; import net.runelite.api.events.HitsplatApplied; import net.runelite.client.callback.ClientThread; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.ClientToolbar; import net.runelite.client.ui.NavigationButton; import net.runelite.client.util.ImageUtil; import net.runelite.http.api.item.ItemEquipmentStats; import net.runelite.http.api.item.ItemStats; import javax.inject.Inject; import javax.swing.*; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.HashMap; import java.util.HashMap; /* Create a new repo at github. Clone the repo from fedorahosted to your local machine. git remote rename origin upstream git remote add origin https://github.com/tmpjac/RL git push origin master Now you can work with it just like any other github repo. To pull in patches from upstream, simply run git pull upstream master && git push origin master. */ @PluginDescriptor( name = "DPS2", description = "Shows the current ammo the player has equipped2", tags = {"bolts", "darts", "chinchompa", "equipment"} ) public class DPSPlugin extends Plugin { @Inject private Client client; @Inject private ClientThread clientThread; @Inject private ClientToolbar clientToolbar; @Inject private ItemManager itemManager; @Inject private DPSConfig dpsConfig; @Provides DPSConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(DPSConfig.class); } private int _count; private NavigationButton navButton; private DPSPanel dpsPanel; private int _initialHP; private HashMap<String,AttackTuple> _lastGearAgainstEnemy; private String _lastEnemy; private HashMap<AttackTuple,DamageTuple> _ats; private ArrayList<AttackTuple> _atOrder; @Override protected void startUp() throws Exception { _count = 0; //dpsPanel = injector.getInstance(DPSPanel2.class); _ats = new HashMap<AttackTuple,DamageTuple>(); _atOrder = new ArrayList<AttackTuple>(); dpsPanel = new DPSPanel(itemManager,_ats, _atOrder, dpsConfig); _lastGearAgainstEnemy = new HashMap<String,AttackTuple>(); _lastEnemy = ""; final BufferedImage icon = ImageUtil.loadImageResource(getClass(), "mail.png"); _initialHP = -1; navButton = NavigationButton.builder() .tooltip("DPS") .icon(icon) .priority(5) .panel(dpsPanel) .build(); clientToolbar.addNavigation(navButton); } @Override protected void shutDown() throws Exception { } @Subscribe public void onConfigChanged(ConfigChanged cc){ System.out.println("Config changed"); System.out.println(cc.getNewValue()); SwingUtilities.invokeLater(() -> { dpsPanel.redrawAll(); }); } //set lastEnemy @Subscribe public void onInteractingChanged(InteractingChanged interactingChanged){ Actor target = interactingChanged.getTarget(); Actor source = interactingChanged.getSource(); if (null == target || !(target instanceof NPC) || !(source == client.getLocalPlayer())) return; //System.out.println("Interacting " + target.getName() + target.getCombatLevel()); _lastEnemy = target.getName() + target.getCombatLevel(); //barbarian17 } //capture AttackTuple and save with respect to enemy @Subscribe public void onAnimationChanged(AnimationChanged event){ if (event.getActor() instanceof Player && event.getActor().getName() != null){ Player eventSource = (Player)event.getActor(); if (eventSource == null || eventSource.getName() == null || eventSource.getInteracting() == null || eventSource.getInteracting().getName() == null) return; if (eventSource.equals(client.getLocalPlayer())){ AnimationData ad = AnimationData.dataForAnimation(eventSource.getAnimation()); if (ad == null) return; System.out.println(ad.attackStyle); System.out.println(ad.animationId); int currentAttackStyleVarbit = client.getVar(VarPlayer.ATTACK_STYLE); int currentEquippedWeaponTypeVarbit = client.getVar(Varbits.EQUIPPED_WEAPON_TYPE); int currentCastingModeVarbit = client.getVar(Varbits.DEFENSIVE_CASTING_MODE); Item weapon = client.getItemContainer(InventoryID.EQUIPMENT).getItems()[EquipmentInventorySlot.WEAPON.getSlotIdx()]; ItemStats stats = itemManager.getItemStats(weapon.getId(),false); System.out.println(stats); int attackSpeed = stats.getEquipment().getAspeed(); AttackStyle[] attackStyles = WeaponType.getWeaponType(currentEquippedWeaponTypeVarbit).getAttackStyles(); AttackStyle attackStyle = attackStyles[currentAttackStyleVarbit]; if (attackStyle == AttackStyle.CASTING && currentCastingModeVarbit == 1){ attackStyle = AttackStyle.DEFENSIVE_CASTING; } if (attackStyle == AttackStyle.RAPID){ attackSpeed -= 1; } Prayer[] combatPrayers = {Prayer.HAWK_EYE, Prayer.MYSTIC_LORE, Prayer.MYSTIC_MIGHT, Prayer.EAGLE_EYE, Prayer.CHIVALRY, Prayer.PIETY, Prayer.RIGOUR, Prayer.AUGURY}; Prayer activePrayer = null; String activePrayerName = ""; for (Prayer p : combatPrayers){ if(client.isPrayerActive(p) && ad.attackStyle.isUsingSuccessfulOffensivePray(p)){ activePrayer = p; activePrayerName = p.name(); } } System.out.println("Attack Speed: " + attackSpeed); System.out.println("Style: " + attackStyle); System.out.println("Prayer: " + activePrayer); AttackTuple atNew =new AttackTuple(weapon.getId(),_lastEnemy,attackSpeed,activePrayerName); //System.out.println("HP Drop " + atNew); _lastGearAgainstEnemy.put( _lastEnemy, atNew ); } } } //lookup AttackTuple on enemy, add AttackTuple to _ats, and update DPSPanel @Subscribe public void onHitsplatApplied(HitsplatApplied h){ if(h.getHitsplat().isMine() ){ //System.out.println("Hitsplat applied " + h.getActor()); //System.out.println(h.getActor()); //System.out.println(client.getLocalPlayer()); if(h.getActor() != client.getLocalPlayer()) { AttackTuple at = _lastGearAgainstEnemy.get(h.getActor().getName()+h.getActor().getCombatLevel()); if (null == at) return; //if first hit is a splash, no gear info exists. for now ignore if (_ats.containsKey(at)){ DamageTuple curr = _ats.get(at); curr._hits += 1; curr._damage += h.getHitsplat().getAmount(); if (!at._prayer.equals("")) curr._numOnPrayer += 1; _atOrder.remove(at); _atOrder.add(at); //add to the end of order }else{ _ats.put(at,new DamageTuple(h.getHitsplat().getAmount(),at._prayer.equals("")?0:1)); _atOrder.add(at); //add to the end of order } SwingUtilities.invokeLater(() -> { dpsPanel.update(at, h.getHitsplat().getAmount()); }); //System.out.println("Hitsplat " + at); } } } }
33.826389
179
0.648943
30616c2a3684518f27075580c3150c538ecb7efd
2,574
/* * 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 me.whitewood.simpledb.sql.adapter.json; import com.google.common.collect.Lists; import me.whitewood.simpledb.sql.adapter.json.JsonAdapterSchema; import org.apache.calcite.jdbc.JavaTypeFactoryImpl; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.schema.Table; import org.apache.calcite.sql.type.SqlTypeName; import org.junit.Test; import java.io.File; import java.util.Map; import static org.junit.Assert.*; /** * Tests for {@link JsonAdapterSchema}. **/ public class JsonAdapterSchemaTest { private File baseDire = new File("src/test/resources/testdb"); private JsonAdapterSchema jsonAdapterSchema = new JsonAdapterSchema(baseDire, null); @Test public void testCreateTableMap() { Map<String, Table> tableMap = jsonAdapterSchema.getTableMap(); assertEquals(2, tableMap.size()); RelDataTypeFactory relDataTypeFactory = new JavaTypeFactoryImpl(); RelDataType expectedType = relDataTypeFactory.createStructType( Lists.newArrayList( relDataTypeFactory.createSqlType(SqlTypeName.DOUBLE), relDataTypeFactory.createSqlType(SqlTypeName.VARCHAR), relDataTypeFactory.createSqlType(SqlTypeName.VARCHAR), relDataTypeFactory.createSqlType(SqlTypeName.BOOLEAN) ), Lists.newArrayList("order_id", "buyer_id", "create_time", "is_prepaid")); // RelDataType doesn't implement proper equal, so we compare the string representations assertEquals(expectedType.toString(), tableMap.get("tbl_order".toUpperCase()) .getRowType(relDataTypeFactory).toString()); } }
42.196721
95
0.722222
9e4de48a849b2d6ecb51c78fd26542270513fbbb
5,651
package ru.inovus.egisz.medorg.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.inovus.egisz.medorg.callback.ResponseCommand; import ru.inovus.egisz.medorg.exceptions.ConsumerHttpBadGatewayException; import ru.inovus.egisz.medorg.exceptions.NotDeliveredException; import ru.inovus.egisz.medorg.rest.RestCallbackCommand; import ru.inovus.egisz.medorg.rest.XmlResultContent; import ru.inovus.egisz.medorg.util.HttpRequester; import ru.inovus.egisz.medorg.util.XmlHelper; import javax.annotation.Resource; import javax.ejb.*; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import java.io.IOException; import java.net.HttpURLConnection; @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "java:jboss/exported/jms/queue/RestCallbackQueue")}) public class ConsumerSender implements MessageListener { private static final Logger logger = LoggerFactory.getLogger(ConsumerSender.class); @EJB private MessageInfoService messageInfoService; @Resource private MessageDrivenContext messageDrivenContext; @Override public void onMessage(Message message) { ResponseCommand response = null; try { response = message.getBody(ResponseCommand.class); } catch (JMSException e) { logger.error("MEDORG. Не удается разобрать ответ из JMS-очереди", e); } if (response == null) return; final String id = response.getMessageId(); final RestCallbackCommand command = messageInfoService.getConsumerByMessageId(id); if (command != null) { final String restCallbackUrl = command.getCallbackUrl(); final String authorizedUserName = command.getAuthorizedUserName(); logger.debug("MEDORG. Извлечена привязка restCallbackUrl {} к id принятого сообщения {} для потребителя {}", restCallbackUrl, id, authorizedUserName); final String data = getResultData(id, response.getOid(), response.getResponse()); logger.debug("MEDORG. Подготовлено к отправке на сервис {} потребителя {} результирующее сообщение: {}", restCallbackUrl, authorizedUserName, data); if (data != null) { try { responseDelivering(restCallbackUrl, authorizedUserName, data, id); logger.debug("MEDORG. Доставлено на сервис {} потребителя {} результирующее сообщение: {}.", restCallbackUrl, authorizedUserName, data); messageInfoService.deleteMessage(id); logger.debug("MEDORG. Удалена привязка restCallbackUrl {} к id принятого сообщения {}", restCallbackUrl, id); } catch (RuntimeException e) { logger.warn("MEDORG. Не удалось отправить клиенту сообщение с id {}. Будет предпринята попытка обработать его позднее", id); messageDrivenContext.setRollbackOnly(); } } } else { logger.warn("MEDORG. Не найдена информация по сообщению с id {}. Будет предпринята попытка обработать его позднее", id); messageDrivenContext.setRollbackOnly(); } } /** * Доставка результирующего сообщения ЕГИСЗ ИПС на сервис потребителя * * @param restCallbackUrl url - для отправки результата обработки * @param authorizedUserName логин авторизированного пользователя * @param data строка результирующего сообщения подготовленного к отправке на сервис потребителя * @param id * @throws ConsumerHttpBadGatewayException */ private void responseDelivering(final String restCallbackUrl, final String authorizedUserName, final String data, final String id) { int responseCode; try { responseCode = HttpRequester.post(restCallbackUrl, data); } catch (IOException ex) { throw new NotDeliveredException(ex); } if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) { throw new ConsumerHttpBadGatewayException("MEDORG. В связи с проблемой работы сервиса " + restCallbackUrl + " (HTTP-статус 502 Bad Gateway) потребителя " + authorizedUserName + ", не удалось доставить результирующее сообщение ЕГИСЗ ИПС: " + data); } else if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_ACCEPTED) { throw new NotDeliveredException("HTTP-статус полученного сообщения от потребителя: " + responseCode); } } /** * Возвращает тело запроса потребителю результирующего сообщения ЕГИСЗ * * @param egiszRespMessageId id принятого сообщения ЕГИСЗ * @param oid идентификатор базового объекта * @param response документ, кодированный в base64, который содержит результат обработки сообщения * @return */ private String getResultData(final String egiszRespMessageId, String oid, String response) { String result = null; final XmlResultContent content = new XmlResultContent(egiszRespMessageId, oid, response); try { result = XmlHelper.instanceToString(content, XmlResultContent.class); } catch (Exception ex) { logger.error("MEDORG. Не удалось преобразовать строку response в объект XmlResultContent для id принятого сообщения ЕГИСЗ ИПС {}: oid={}, response={}", egiszRespMessageId, oid, response, ex); } return result; } }
40.654676
259
0.691205
760e951cc1bb9b1109f366dd2ee89d4bab762676
3,977
/******************************************************************************* * Copyright 2016-2017 Dell 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. * * @microservice: support-notifications * @author: Jim White, Dell * @version: 1.0.0 *******************************************************************************/ package org.edgexfoundry.core.metadata.suites; import org.edgexfoundry.controller.integration.AddressableControllerTest; import org.edgexfoundry.controller.integration.CallbackExecutorTest; import org.edgexfoundry.controller.integration.CommandControllerTest; import org.edgexfoundry.controller.integration.DeviceControllerTest; import org.edgexfoundry.controller.integration.DeviceProfileControllerTest; import org.edgexfoundry.controller.integration.DeviceReportControllerTest; import org.edgexfoundry.controller.integration.DeviceServiceControllerTest; import org.edgexfoundry.controller.integration.ProvisionWatcherControllerTest; import org.edgexfoundry.controller.integration.ScheduleControllerTest; import org.edgexfoundry.controller.integration.ScheduleEventControllerTest; import org.edgexfoundry.dao.integration.AddressableDaoTest; import org.edgexfoundry.dao.integration.AddressableRepositoryTest; import org.edgexfoundry.dao.integration.CommandRepositoryTest; import org.edgexfoundry.dao.integration.DeviceDaoTest; import org.edgexfoundry.dao.integration.DeviceProfileDaoTest; import org.edgexfoundry.dao.integration.DeviceReportDaoTest; import org.edgexfoundry.dao.integration.DeviceReportRepositoryTest; import org.edgexfoundry.dao.integration.DeviceRepositoryTest; import org.edgexfoundry.dao.integration.DeviceServiceDaoTest; import org.edgexfoundry.dao.integration.DeviceServiceRepositoryTest; import org.edgexfoundry.dao.integration.ProvisionWatcherRepositoryTest; import org.edgexfoundry.dao.integration.ScheduleDaoTest; import org.edgexfoundry.dao.integration.ScheduleEventDaoTest; import org.edgexfoundry.dao.integration.ScheduleEventRepositoryTest; import org.edgexfoundry.dao.integration.ScheduleRepositoryTest; import org.edgexfoundry.integration.mongodb.MongoDBConnectivityTest; import org.edgexfoundry.integration.spring.SpringConfigurationTest; import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Used in development only. Remove @Ignore to run just the integration tests (not unit tests). * These tests do require other resources to run. * * @author Jim White * */ @Ignore @RunWith(Suite.class) @Suite.SuiteClasses({AddressableControllerTest.class, CallbackExecutorTest.class, CommandControllerTest.class, DeviceControllerTest.class, DeviceProfileControllerTest.class, DeviceReportControllerTest.class, DeviceServiceControllerTest.class, ProvisionWatcherControllerTest.class, ScheduleControllerTest.class, ScheduleEventControllerTest.class, AddressableDaoTest.class, AddressableRepositoryTest.class, CommandRepositoryTest.class, DeviceDaoTest.class, DeviceProfileDaoTest.class, DeviceReportDaoTest.class, DeviceReportRepositoryTest.class, DeviceRepositoryTest.class, DeviceServiceDaoTest.class, DeviceServiceRepositoryTest.class, ProvisionWatcherRepositoryTest.class, ScheduleDaoTest.class, ScheduleEventDaoTest.class, ScheduleEventRepositoryTest.class, ScheduleEventRepositoryTest.class, ScheduleRepositoryTest.class, MongoDBConnectivityTest.class, SpringConfigurationTest.class}) public class IntegrationTestSuite { }
53.026667
100
0.811164
83bcf3481e5df0a07dca1b5c6fd8f3baa2c19485
1,334
package com.examples.audio; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Allows {@link MediaPlayerHolder} to report media playback duration and progress updates to * the {@link MainActivity}. */ public abstract class PlaybackInfoListener { @IntDef({State.INVALID, State.PLAYING, State.PAUSED, State.RESET, State.COMPLETED}) @Retention(RetentionPolicy.SOURCE) @interface State { int INVALID = -1; int PLAYING = 0; int PAUSED = 1; int RESET = 2; int COMPLETED = 3; } public static String convertStateToString(@State int state) { String stateString; switch (state) { case State.COMPLETED: stateString = "COMPLETED"; break; case State.INVALID: stateString = "INVALID"; break; case State.PAUSED: stateString = "PAUSED"; break; case State.PLAYING: stateString = "PLAYING"; break; case State.RESET: stateString = "RESET"; break; default: stateString = "N/A"; } return stateString; } void onLogUpdated(String formattedMessage) { } void onDurationChanged(int duration) { } void onPositionChanged(int position) { } void onStateChanged(@State int state) { } void onPlaybackCompleted() { } }
20.84375
94
0.669415
6d67f4a512c3d76e4d91f7b6defc509522905234
231
package id.ac.unpar.siamodels.matakuliah; import id.ac.unpar.siamodels.InfoMataKuliah; import id.ac.unpar.siamodels.MataKuliah; @InfoMataKuliah(nama = "Jaringan Komputer", sks = 4) public class AIF133305 extends MataKuliah { }
21
52
0.787879
afbb7f3bc74e564ba8896d124a548efe22b6ad9b
1,093
//Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). // //Note: The solution set must not contain duplicate subsets. // //Example: // //Input: [1,2,2] //Output: //[ // [2], // [1], // [1,2,2], // [2,2], // [1,2], // [] //] package wenxinjie1; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class leetcode90_Subsets_II { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); helper(res, new ArrayList<Integer>(), nums, 0); return res; } public void helper(List<List<Integer>> res, List<Integer> cur, int[] nums, int index){ res.add(new ArrayList<>(cur)); for (int i = index; i < nums.length; i ++){ if (i > index && nums[i] == nums[i-1]) continue; cur.add(nums[i]); helper(res, cur, nums, i+1); cur.remove(cur.size()-1); } } } //Time: O(2^n) //Space: O(2 ^ n) //Difficulty: medium
23.76087
114
0.576395
51b7feec41efa93be5c43c2fa7fcbca4aa2b1374
5,787
package com.jeecg.superquery.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.jeecgframework.poi.excel.annotation.Excel; /** * @Title: Entity * @Description: 高级查询 * @author onlineGenerator * @date 2017-12-04 18:10:18 * @version V1.0 * */ @Entity @Table(name = "super_query_main", schema = "") @SuppressWarnings("serial") public class SuperQueryMainEntity implements java.io.Serializable { /**主键*/ private String id; /**创建人名称*/ private String createName; /**创建人登录名称*/ private String createBy; /**创建日期*/ private java.util.Date createDate; /**更新人名称*/ private String updateName; /**更新人登录名称*/ private String updateBy; /**更新日期*/ private java.util.Date updateDate; /**所属部门*/ private String sysOrgCode; /**所属公司*/ private String sysCompanyCode; /**查询规则名称*/ @Excel(name="查询规则名称",width=15) private String queryName; /**查询规则编码*/ @Excel(name="查询规则编码",width=15) private String queryCode; /**查询类型*/ @Excel(name="查询类型",width=15,dicCode="sel_type") private String queryType; /**说明*/ @Excel(name="说明",width=15) private String content; /** *方法: 取得java.lang.String *@return: java.lang.String 主键 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") @Column(name ="ID",nullable=false,length=36) public String getId(){ return this.id; } /** *方法: 设置java.lang.String *@param: java.lang.String 主键 */ public void setId(String id){ this.id = id; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人名称 */ @Column(name ="CREATE_NAME",nullable=true,length=50) public String getCreateName(){ return this.createName; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人名称 */ public void setCreateName(String createName){ this.createName = createName; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人登录名称 */ @Column(name ="CREATE_BY",nullable=true,length=50) public String getCreateBy(){ return this.createBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人登录名称 */ public void setCreateBy(String createBy){ this.createBy = createBy; } /** *方法: 取得java.util.Date *@return: java.util.Date 创建日期 */ @Column(name ="CREATE_DATE",nullable=true,length=20) public java.util.Date getCreateDate(){ return this.createDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 创建日期 */ public void setCreateDate(java.util.Date createDate){ this.createDate = createDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 更新人名称 */ @Column(name ="UPDATE_NAME",nullable=true,length=50) public String getUpdateName(){ return this.updateName; } /** *方法: 设置java.lang.String *@param: java.lang.String 更新人名称 */ public void setUpdateName(String updateName){ this.updateName = updateName; } /** *方法: 取得java.lang.String *@return: java.lang.String 更新人登录名称 */ @Column(name ="UPDATE_BY",nullable=true,length=50) public String getUpdateBy(){ return this.updateBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 更新人登录名称 */ public void setUpdateBy(String updateBy){ this.updateBy = updateBy; } /** *方法: 取得java.util.Date *@return: java.util.Date 更新日期 */ @Column(name ="UPDATE_DATE",nullable=true,length=20) public java.util.Date getUpdateDate(){ return this.updateDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 更新日期 */ public void setUpdateDate(java.util.Date updateDate){ this.updateDate = updateDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 所属部门 */ @Column(name ="SYS_ORG_CODE",nullable=true,length=50) public String getSysOrgCode(){ return this.sysOrgCode; } /** *方法: 设置java.lang.String *@param: java.lang.String 所属部门 */ public void setSysOrgCode(String sysOrgCode){ this.sysOrgCode = sysOrgCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 所属公司 */ @Column(name ="SYS_COMPANY_CODE",nullable=true,length=50) public String getSysCompanyCode(){ return this.sysCompanyCode; } /** *方法: 设置java.lang.String *@param: java.lang.String 所属公司 */ public void setSysCompanyCode(String sysCompanyCode){ this.sysCompanyCode = sysCompanyCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 查询规则名称 */ @Column(name ="QUERY_NAME",nullable=true,length=50) public String getQueryName(){ return this.queryName; } /** *方法: 设置java.lang.String *@param: java.lang.String 查询规则名称 */ public void setQueryName(String queryName){ this.queryName = queryName; } /** *方法: 取得java.lang.String *@return: java.lang.String 查询规则编码 */ @Column(name ="QUERY_CODE",nullable=true,length=50) public String getQueryCode(){ return this.queryCode; } /** *方法: 设置java.lang.String *@param: java.lang.String 查询规则编码 */ public void setQueryCode(String queryCode){ this.queryCode = queryCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 查询类型 */ @Column(name ="QUERY_TYPE",nullable=true,length=50) public String getQueryType(){ return this.queryType; } /** *方法: 设置java.lang.String *@param: java.lang.String 查询类型 */ public void setQueryType(String queryType){ this.queryType = queryType; } /** *方法: 取得java.lang.String *@return: java.lang.String 说明 */ @Column(name ="CONTENT",nullable=true,length=32) public String getContent(){ return this.content; } /** *方法: 设置java.lang.String *@param: java.lang.String 说明 */ public void setContent(String content){ this.content = content; } }
19.886598
68
0.68291
69b5487855e6bd33cda731e004c2b7bb2b380ddb
1,008
package a3.network.api; import java.io.Serializable; import java.util.Arrays; import ray.rml.Matrix3; import ray.rml.Matrix3f; public class Rotation implements Serializable { private static final long serialVersionUID = -3441167665366306905L; final float[] rotationArray; public Rotation(float[] rotationArray) { this.rotationArray = rotationArray; } public float[] getRotationArray() { return this.rotationArray; } public Matrix3 toMatrix3() { return Matrix3f.createFrom(this.rotationArray); } public static Rotation fromMatrix3(Matrix3 rot) { return new Rotation(rot.toFloatArray()); } public static Rotation defaultRotation() { return Rotation.fromMatrix3(Matrix3f.createIdentityMatrix()); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append(" [ ") .append("rotation=\"").append(Arrays.toString(getRotationArray())).append("\"") .append("\" ]"); return sb.toString(); } }
22.4
82
0.731151
09b15abf62d45a3cb10f2d54e61260b9cfe0f62f
1,040
package GUI; import Producers.Resource; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; public class Utils { public static BufferedImage getScaledImage(Image srcImg, int w, int h) { BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(srcImg, 0, 0, w, h, null); g2.dispose(); return resizedImg; } public static String getColouredValue(Resource resource, int neededValue) { int resCurrentValue = (int) resource.getValue(); String redColor = "<font color='red'>"; String redColorEnd = "</font>"; return resCurrentValue < neededValue ? redColor + resCurrentValue + redColorEnd + " / " + neededValue : String.valueOf(resCurrentValue); } }
33.548387
108
0.640385
73ca4a849103ed4c9791f53ceddc5fa27afc3d27
456
package tw.idv.ken.kata.wordwrapper; public class Kata2 { public String wrap(String content, int lineWidth) { StringBuilder sb = new StringBuilder(); int lineBreaks = 1; for(int i=0;i<content.length(); i++){ sb.append(content.charAt(i)); if(i == (lineWidth * lineBreaks - 1)){ sb.append("\n"); lineBreaks ++; } } return sb.toString(); } }
26.823529
55
0.515351
88c7d602c57a66fdaf4bb54b9b4ffcfbcfbbe016
263
// https://www.codewars.com/kata/514b92a657cdc65150000006 public class Solution { public int solution(int number) { int sum = 0; for(int i = 1; i < number; i++) { if(i % 3 == 0 || i % 5 == 0) sum += i; } return sum; } }
17.533333
57
0.51711
9adc528dcab4b7235161e043f294b92c65fd5733
7,696
/* ### * IP: GHIDRA * * 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 ghidra.app.plugin.core.interpreter; import static org.junit.Assert.*; import java.io.*; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.apache.commons.lang3.StringUtils; import org.junit.*; import ghidra.app.plugin.core.console.CodeCompletion; import ghidra.framework.options.ToolOptions; import ghidra.test.AbstractGhidraHeadedIntegrationTest; import ghidra.test.DummyTool; import resources.Icons; /** * Test the InterpreterPanel/InterpreterConsole's stdIn InputStream handling by * manually creating a JFrame (while a regular Ghidra tool is running) * to host the panel in. */ public class InterpreterPanelTest extends AbstractGhidraHeadedIntegrationTest { private JFrame frame; private InterpreterPanel ip; private JTextPane inputTextPane; private Document inputDoc; private BufferedReader reader; @Before public void setUp() throws Exception { ip = createIP(); inputTextPane = ip.inputTextPane; inputDoc = inputTextPane.getDocument(); reader = new BufferedReader(new InputStreamReader(ip.getStdin())); frame = new JFrame("InterpreterPanel test frame"); frame.getContentPane().add(ip); frame.setSize(400, 400); runSwing(() -> frame.setVisible(true)); } @After public void tearDown() throws Exception { runSwing(() -> { frame.setVisible(false); frame.dispose(); }); } @Test(timeout = 20000) public void testInputStream_AddRead() throws Exception { doBackgroundTriggerTextTest(List.of("test1", "abc123")); } @Test(timeout = 20000) public void testInputStream_ClearResetsStream() throws Exception { doBackgroundTriggerTextTest(List.of("test1", "abc123")); doSwingMultilinePasteTest(List.of("testLine1", "testLine2", "testLine3")); ip.clear(); doBackgroundTriggerTextTest(List.of("test2", "abc456")); doSwingMultilinePasteTest(List.of("testLine4", "testLine5", "testLine6")); } @Test(timeout = 20000) public void testInputStream_CloseStreamBeforeReading() throws Exception { ip.getStdin().close(); assertNull(reader.readLine()); // should always get NULL results because stream is now 'closed' assertNull(reader.readLine()); // " " ip.stdin.addText("test_while_closed\n"); // text added after close shouldn't be preserved assertNull(reader.readLine()); // should always get NULL results because stream is now 'closed' ip.clear(); // stream should now be open again doBackgroundTriggerTextTest(List.of("test2", "abc456")); } @Test(timeout = 20000) public void testInputStream_CloseStreamWhileBlocking() throws Exception { AtomicReference<String> result = new AtomicReference<>("Non-null value"); doBackgroundReadLine(result); // this thread will block on readLine() ip.getStdin().close(); // this will be set to null when readLine() returns waitFor(() -> result.get() == null); ip.clear(); // stream should now be open again doBackgroundTriggerTextTest(List.of("test2", "abc456")); } @Test(timeout = 20000) public void testInputStream_InterruptStreamWhileBlocking() throws Exception { AtomicReference<String> result = new AtomicReference<>("Non-null value"); Thread t = doBackgroundReadLine(result); // this thread will block on readLine() t.interrupt(); // this will be set to null when readLine() returns waitFor(() -> result.get() == null); ip.clear(); // stream should now be open again doBackgroundTriggerTextTest(List.of("test2", "abc456")); } @Test(timeout = 20000) public void testInputStream_ReadSingleBytes() throws IOException { doBackgroundPasteTest1AtATime("testvalue\n"); CountDownLatch startLatch = new CountDownLatch(1); closeStreamViaBackgroundThread(startLatch); startLatch.countDown(); assertEquals(-1, ip.getStdin().read()); } @Test(timeout = 20000) public void testInputStream_Available() throws IOException { assertEquals(0, ip.getStdin().available()); triggerText(inputTextPane, "testvalue\n"); waitForSwing(); assertTrue(ip.getStdin().available() > 0); } private InterpreterPanel createIP() { InterpreterConnection dummyIC = new InterpreterConnection() { @Override public String getTitle() { return "Dummy Title"; } @Override public ImageIcon getIcon() { return Icons.STOP_ICON; } @Override public List<CodeCompletion> getCompletions(String cmd) { return List.of(); } }; DummyTool tool = new DummyTool() { @Override public ToolOptions getOptions(String categoryName) { return new ToolOptions("Dummy"); } }; InterpreterPanel result = new InterpreterPanel(tool, dummyIC); result.setPrompt("PROMPT:"); return result; } private void doSwingMultilinePasteTest(List<String> multiLineTestValues) throws IOException { // simulates what happens during a paste when multi-line string with // "\n"s is pasted. runSwingLater(() -> { try { String multiLineString = StringUtils.join(multiLineTestValues, "\n") + '\n'; inputDoc.insertString(0, multiLineString, null); } catch (BadLocationException e) { // ignore } }); for (String expectedValue : multiLineTestValues) { String actualValue = reader.readLine(); assertEquals(expectedValue, actualValue); } } private void doBackgroundPasteTest1AtATime(String testValue) throws IOException { runSwingLater(() -> { try { inputDoc.insertString(0, testValue, null); } catch (BadLocationException e) { // ignore } }); for (int i = 0; i < testValue.length(); i++) { char expectedChar = testValue.charAt(i); int actualValue = ip.getStdin().read(); assertEquals(expectedChar, (char) actualValue); } } private void doBackgroundTriggerTextTest(List<String> testValues) throws Exception { new Thread(() -> { for (String s : testValues) { triggerText(inputTextPane, s + "\n"); } }).start(); for (String expectedValue : testValues) { String actualValue = reader.readLine(); assertEquals(expectedValue, actualValue); } } private Thread doBackgroundReadLine(AtomicReference<String> result) throws InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); Thread t = new Thread(() -> { try { startLatch.countDown(); result.set(reader.readLine()); } catch (IOException e) { // test will fail } }); t.start(); startLatch.await(2, TimeUnit.SECONDS); // the background thread is now spun-up and ready to read // the smallest of sleeps to give the thread a chance to read after the latch was reached sleep(10); return t; } private void closeStreamViaBackgroundThread(CountDownLatch startLatch) { new Thread(() -> { try { startLatch.await(2, TimeUnit.SECONDS); // the smallest of sleeps to give the thread a chance to read after the latch was reached sleep(10); ip.getStdin().close(); } catch (InterruptedException | IOException e) { // ignore } }).start(); } }
27.985455
98
0.716996
6700e7fcf1fd7ec1eec715f6d9305b73bbc54617
4,913
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.indexer; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import org.joda.time.DateTime; import javax.annotation.Nullable; import java.util.Map; import java.util.Objects; public class TaskStatusPlus { private final String id; private final String type; private final DateTime createdTime; private final DateTime queueInsertionTime; private final TaskState state; private final Long duration; private final TaskLocation location; @Nullable private final Map<String, Object> metrics; @Nullable private final String errorMsg; @Nullable private final Map<String, Object> context; @JsonCreator public TaskStatusPlus( @JsonProperty("id") String id, @JsonProperty("type") @Nullable String type, // nullable for backward compatibility @JsonProperty("createdTime") DateTime createdTime, @JsonProperty("queueInsertionTime") DateTime queueInsertionTime, @JsonProperty("statusCode") @Nullable TaskState state, @JsonProperty("duration") @Nullable Long duration, @JsonProperty("location") TaskLocation location, @JsonProperty("metrics") Map<String, Object> metrics, @JsonProperty("errorMsg") String errorMsg, @JsonProperty("context") Map<String, Object> context ) { if (state != null && state.isComplete()) { Preconditions.checkNotNull(duration, "duration"); } this.id = Preconditions.checkNotNull(id, "id"); this.type = Preconditions.checkNotNull(type, "type"); this.createdTime = Preconditions.checkNotNull(createdTime, "createdTime"); this.queueInsertionTime = Preconditions.checkNotNull(queueInsertionTime, "queueInsertionTime"); this.state = state; this.duration = duration; this.location = Preconditions.checkNotNull(location, "location"); this.metrics = metrics; this.errorMsg = errorMsg; this.context = context; } @JsonProperty public String getId() { return id; } @Nullable @JsonProperty public String getType() { return type; } @JsonProperty public DateTime getCreatedTime() { return createdTime; } @JsonProperty public DateTime getQueueInsertionTime() { return queueInsertionTime; } @Nullable @JsonProperty("statusCode") public TaskState getState() { return state; } @Nullable @JsonProperty public Long getDuration() { return duration; } @JsonProperty public TaskLocation getLocation() { return location; } @Nullable @JsonProperty("metrics") public Map<String, Object> getMetrics() { return metrics; } @Nullable @JsonProperty("errorMsg") public String getErrorMsg() { return errorMsg; } @Nullable @JsonProperty("context") public Map<String, Object> getContext() { return context; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final TaskStatusPlus that = (TaskStatusPlus) o; if (!id.equals(that.id)) { return false; } if (!type.equals(that.type)) { return false; } if (!createdTime.equals(that.createdTime)) { return false; } if (!queueInsertionTime.equals(that.queueInsertionTime)) { return false; } if (!Objects.equals(state, that.state)) { return false; } if (!Objects.equals(duration, that.duration)) { return false; } if (!Objects.equals(location, that.location)) { return false; } if (!Objects.equals(errorMsg, that.errorMsg)) { return false; } if (!Objects.equals(location, that.location)) { return false; } return Objects.equals(context, that.context); } @Override public int hashCode() { return Objects.hash( id, type, createdTime, queueInsertionTime, state, duration, location, metrics, errorMsg, context ); } }
23.620192
99
0.680236
ee122db004485d7ecf70eb239a090bbadd4542f0
208
package com.simibubi.create.foundation.render.backend.gl.attrib; public interface IVertexAttrib { String attribName(); IAttribSpec attribSpec(); int getDivisor(); int getBufferIndex(); }
16
64
0.721154
07ebf6a6acd8dd4ed939218983b577793626f48d
2,431
package domain.use_cases.user_manager.address; import domain.gateway.UserAddressInterface; import domain.presenter.UserAddressPresenterInterface; import domain.requests.UpdateAddressRequest; public abstract class UpdateAddressFactory { protected UserAddressInterface repository; private String id; private String userID; private String country; private String state; private String city; private String neighborhood; private String street; private String number; private String commit; public UpdateAddressFactory(UserAddressInterface repository, UpdateAddressRequest request) { this.repository = repository; this.setId(request.getId()); this.setUserID(request.getUserID()); this.setCountry(request.getCountry()); this.setState(request.getState()); this.setCity(request.getCity()); this.setNeighborhood(request.getNeighborhood()); this.setStreet(request.getStreet()); this.setNumber(request.getNumber()); this.setCommit(request.getCommit()); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getNeighborhood() { return neighborhood; } public void setNeighborhood(String neighborhood) { this.neighborhood = neighborhood; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getCommit() { return commit; } public void setCommit(String commit) { this.commit = commit; } public abstract void execute(UserAddressPresenterInterface presenter); }
22.933962
96
0.645825
112e97aebfc08e7c42c02227beeb8203dfe9daaf
2,741
package uk.gov.dwp.queue.triage.core.jms.activemq.configuration; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import uk.gov.dwp.queue.triage.core.jms.JmsMessagePropertyExtractor; import uk.gov.dwp.queue.triage.core.jms.MessageTextExtractor; import uk.gov.dwp.queue.triage.core.jms.activemq.ActiveMQDestinationExtractor; import uk.gov.dwp.queue.triage.core.jms.activemq.ActiveMQFailedMessageFactory; import uk.gov.dwp.queue.triage.core.jms.activemq.browser.spring.QueueBrowserCallbackBeanDefinitionFactory; import uk.gov.dwp.queue.triage.core.jms.activemq.browser.spring.QueueBrowserScheduledExecutorServiceBeanDefinitionFactory; import uk.gov.dwp.queue.triage.core.jms.activemq.browser.spring.QueueBrowserServiceBeanDefinitionFactory; import uk.gov.dwp.queue.triage.core.jms.activemq.spring.ActiveMQConnectionFactoryBeanDefinitionFactory; import uk.gov.dwp.queue.triage.core.jms.activemq.spring.ActiveMQConnectionFactoryFactoryBeanDefinitionFactory; import uk.gov.dwp.queue.triage.core.jms.activemq.spring.FailedMessageListenerBeanDefinitionFactory; import uk.gov.dwp.queue.triage.core.jms.activemq.spring.JmsBeanDefinitionRegistryPostProcessor; import uk.gov.dwp.queue.triage.core.jms.activemq.spring.NamedMessageListenerContainerBeanDefinitionFactory; import uk.gov.dwp.queue.triage.core.jms.spring.JmsTemplateBeanDefinitionFactory; public class MessageConsumerApplicationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext applicationContext) { final ConfigurableEnvironment environment = applicationContext.getEnvironment(); applicationContext.addBeanFactoryPostProcessor(new JmsBeanDefinitionRegistryPostProcessor( environment, new ActiveMQConnectionFactoryFactoryBeanDefinitionFactory(), new ActiveMQConnectionFactoryBeanDefinitionFactory(), new FailedMessageListenerBeanDefinitionFactory(brokerName -> new ActiveMQFailedMessageFactory( new MessageTextExtractor(), new ActiveMQDestinationExtractor(brokerName), new JmsMessagePropertyExtractor() )), new NamedMessageListenerContainerBeanDefinitionFactory(), new JmsTemplateBeanDefinitionFactory(), new QueueBrowserCallbackBeanDefinitionFactory(), new QueueBrowserServiceBeanDefinitionFactory(), new QueueBrowserScheduledExecutorServiceBeanDefinitionFactory() )); } }
65.261905
125
0.796425
fb97dda49c17ca17732646e2a022c70cd4c30926
664
package org.apache.sling.graalvm.http; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.equalTo; import javax.ws.rs.core.MediaType; @QuarkusTest public class SlingResourceTest { @Test public void testSlingResourceEndpoint() { final String prefix = "/sling/"; final String path = "chouc/route"; given() .when().get(prefix + path) .then() .statusCode(200) .contentType(MediaType.APPLICATION_JSON); //TODO .body("path", equalTo(prefix + path)); } }
23.714286
58
0.65512
09e14c6af12394ad7d8419cbb70fce51ac803f43
3,425
package eco.ui; import eco.render.TextureAtlas; import eco.render.Render; import eco.render.RenderUtil; import org.lwjgl.opengl.GL11; import java.awt.*; /** * A <i>ToggleTextButton</i> behaves just like a normal <i>TextButton</i>, but * will toggle to it's second texture when pressed, not just when moused over * * @author phil */ public class ToggleTextButton extends eco.ui.Button { private float width; private float height; private String text; private boolean toggle; public ToggleTextButton(float x, float y, float width, float height, int tex, int tey, int texselected, int teyselected, IClickEvent action, String text, boolean on) { super(x, y, width, tex, tey, texselected, teyselected, action); this.width = width; this.height = height; this.text = text; toggle = on; } public void click(float mousex, float mousey) { Rectangle rect = new Rectangle((int) getX(), (int) getY(), (int) width, (int) height); if (rect.contains(mousex, mousey)) { setClickFlag(true); toggle ^= true; action.onClick(this); } } public void render(float mousex, float mousey) { TextureAtlas atlas = Render.atlas; Rectangle rect = new Rectangle((int) getX(), (int) getY(), (int) width, (int) height); if (rect.contains(mousex, mousey) || toggle) { GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(atlas.getCoord(getTexselected(), false), atlas.getCoord(getTeyselected(), false)); GL11.glVertex2f(getX(), getY()); GL11.glTexCoord2f(atlas.getCoord(getTexselected(), true), atlas.getCoord(getTeyselected(), false)); GL11.glVertex2f(getX() + width, getY()); GL11.glTexCoord2f(atlas.getCoord(getTexselected(), true), atlas.getCoord(getTeyselected(), true)); GL11.glVertex2f(getX() + width, getY() + height); GL11.glTexCoord2f(atlas.getCoord(getTexselected(), false), atlas.getCoord(getTeyselected(), true)); GL11.glVertex2f(getX(), getY() + height); GL11.glEnd(); } else { GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(atlas.getCoord(getTex(), false), atlas.getCoord(getTey(), false)); GL11.glVertex2f(getX(), getY()); GL11.glTexCoord2f(atlas.getCoord(getTex(), true), atlas.getCoord(getTey(), false)); GL11.glVertex2f(getX() + width, getY()); GL11.glTexCoord2f(atlas.getCoord(getTex(), true), atlas.getCoord(getTey(), true)); GL11.glVertex2f(getX() + width, getY() + height); GL11.glTexCoord2f(atlas.getCoord(getTex(), false), atlas.getCoord(getTey(), true)); GL11.glVertex2f(getX(), getY() + height); GL11.glEnd(); } } public void render2() { int centX = (int) getX(); centX += (width - RenderUtil.font.getWidth(text)) / 2; RenderUtil.drawString(text, centX, (int) getY() + ((height - RenderUtil.font.getHeight(text)) / 2)); } public void setToggle(boolean toggle) { this.toggle = toggle; } }
35.677083
112
0.569635
8d4cce45f42cfc953576ac6215fd0738f5dcd866
2,306
package seedu.address.ui; import java.util.Comparator; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.module.Module; import seedu.address.model.tag.Tag; /** * An UI component that displays information of a {@code Module} without prereqs. */ public class SimpleModuleCard extends UiPart<Region> { private static final String FXML = "SimpleModuleListCard.fxml"; /** * Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX. * As a consequence, UI elements' variable names cannot be set to such keywords * or an exception will be thrown by JavaFX during runtime. * * @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on AddressBook level 4</a> */ public final Module module; @FXML private HBox moduleCardPane; @FXML private Label name; @FXML private Label mcCount; @FXML private FlowPane tags; public SimpleModuleCard(Module module) { super(FXML); this.module = module; name.setText(module.getModuleCode().value + " " + module.getName().fullName); mcCount.setText(Integer.toString(module.getMcCount())); module.getTags().asUnmodifiableObservableList().stream() .sorted(Comparator.comparing(Tag::getTagName)) .forEach(tag -> { Label tagLabel = new Label(tag.getTagName()); tagLabel.setWrapText(true); if (tag.isDefault()) { tagLabel.setId("defaultTag"); } else { tagLabel.setId("userTag"); } tags.getChildren().add(tagLabel); }); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof SimpleModuleCard)) { return false; } // state check SimpleModuleCard card = (SimpleModuleCard) other; return module.equals(card.module); } }
30.746667
114
0.612316
6eed7decd808df294f027563dbda91e6717f9f0b
200
package me.yifeiyuan.flapdev.components.generictest; import me.yifeiyuan.flapdev.components.base.BaseModel; /** * Created by 程序亦非猿 on 2019/1/29. */ public class GenericModel extends BaseModel { }
20
54
0.775
57a3dc408ae2f5646096fb56a2c4f2ab28cf3e99
425
package uz.maniac4j.participantservice.participant; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface ParticipantRepository extends JpaRepository<Participant,Long> { boolean existsByUsername(String username); Optional<Participant> findByUsername(String username); List<Participant> findAllByOrganizationIdOrderByIdDesc(Long id); }
32.692308
80
0.828235
0a5524ef37cfbc6e983b89550394db5f6017aa5f
2,960
/* * Copyright (c) Numerical Method Inc. * http://www.numericalmethod.com/ * * THIS SOFTWARE IS LICENSED, NOT SOLD. * * YOU MAY USE THIS SOFTWARE ONLY AS DESCRIBED IN THE LICENSE. * IF YOU ARE NOT AWARE OF AND/OR DO NOT AGREE TO THE TERMS OF THE LICENSE, * DO NOT USE THIS SOFTWARE. * * THE SOFTWARE IS PROVIDED "AS IS", WITH NO WARRANTY WHATSOEVER, * EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, * ANY WARRANTIES OF ACCURACY, ACCESSIBILITY, COMPLETENESS, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, NON-INFRINGEMENT, * TITLE AND USEFULNESS. * * IN NO EVENT AND UNDER NO LEGAL THEORY, * WHETHER IN ACTION, CONTRACT, NEGLIGENCE, TORT, OR OTHERWISE, * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIMS, DAMAGES OR OTHER LIABILITIES, * ARISING AS A RESULT OF USING OR OTHER DEALINGS IN THE SOFTWARE. */ package com.numericalmethod.suanshu.optimization.constrained.convex.sdp.socp.qp.lp.problem; import com.numericalmethod.suanshu.matrix.doubles.ImmutableMatrix; import com.numericalmethod.suanshu.optimization.constrained.problem.ConstrainedOptimProblem; import com.numericalmethod.suanshu.vector.doubles.ImmutableVector; /** * A linear programming (LP) problem minimizes a linear objective function subject to a collection of linear constraints. * <blockquote><pre><i> * min c'x * </i></pre></blockquote> * s.t. * <blockquote><pre><i> * A * x &ge; b * Aeq * x = beq * </i></pre></blockquote> * some <i>x &ge; 0</i>, some <i>x</i> are free. * * @author Haksun Li */ public interface LPProblem extends ConstrainedOptimProblem { /** * Get the objective function. * * @return the objective function */ public ImmutableVector c(); /** * Get the coefficients, <i>A</i>, of the greater-than-or-equal-to constraints <i>A * x &ge; b</i>. * * @return the coefficients of the greater-than-or-equal-to constraints */ public ImmutableMatrix A(); /** * Get the values, <i>b</i>, of the greater-than-or-equal-to constraints <i>A * x &ge; b</i>. * * @return the values of the greater-than-or-equal-to constraints */ public ImmutableVector b(); /** * Get the coefficients, <i>Aeq</i>, of the equality constraints <i>Aeq * x &ge; beq</i>. * * @return the coefficients of the equality constraints */ public ImmutableMatrix Aeq(); /** * Get the values, <i>beq</i>, of the equality constraints <i>Aeq * x &ge; beq</i>. * * @return the values of the equality constraints */ public ImmutableVector beq(); /** * Check whether x<sub>i</sub> is a free variable <em>after</em> handling the box constraints. * * @param i the index of a variable, counting from 1 * @return {@code true} if x<sub>i</sub> is free */ public boolean isFree(int i); }
33.636364
122
0.651014
720811d477f2bd08c4cc7e619f9b90c24dd53163
1,558
package com.example.bonvoyage; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; public class RiderPostPayment extends AppCompatActivity { private FirebaseHandler firebaseHandler; private FirebaseFirestore db; /** * Handles the call for rider transaction and send's the rider to rating fragment * @param savedInstanceState */ protected void onCreateView(@Nullable Bundle savedInstanceState) { FirebaseUser fb_rider = firebaseHandler.getCurrentUser(); db = FirebaseFirestore.getInstance(); DocumentReference docRef = db.collection("riders").document(fb_rider.getEmail()); docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Rider rider = documentSnapshot.toObject(Rider.class); float cost = firebaseHandler.getCostOfRideFromDatabase(rider.getEmail()); firebaseHandler.riderTransaction(rider, cost); startActivity(new Intent(RiderPostPayment.this, RiderRatingFragment.class)); } }); } }
41
93
0.718228
babad5456b5358b5cd4455959efaac11897b160e
2,785
package com.wavefront.agent.handlers; import com.wavefront.dto.Event; import com.wavefront.dto.SourceTag; import org.easymock.EasyMock; import wavefront.report.ReportEvent; import wavefront.report.ReportPoint; import wavefront.report.ReportSourceTag; import wavefront.report.Span; import wavefront.report.SpanLogs; import javax.annotation.Nonnull; /** * Mock factory for testing * * @author vasily@wavefront.com */ public class MockReportableEntityHandlerFactory { public static ReportPointHandlerImpl getMockReportPointHandler() { return EasyMock.createMock(ReportPointHandlerImpl.class); } public static ReportSourceTagHandlerImpl getMockSourceTagHandler() { return EasyMock.createMock(ReportSourceTagHandlerImpl.class); } public static ReportPointHandlerImpl getMockHistogramHandler() { return EasyMock.createMock(ReportPointHandlerImpl.class); } public static SpanHandlerImpl getMockTraceHandler() { return EasyMock.createMock(SpanHandlerImpl.class); } public static SpanLogsHandlerImpl getMockTraceSpanLogsHandler() { return EasyMock.createMock(SpanLogsHandlerImpl.class); } public static EventHandlerImpl getMockEventHandlerImpl() { return EasyMock.createMock(EventHandlerImpl.class); } public static ReportableEntityHandlerFactory createMockHandlerFactory( ReportableEntityHandler<ReportPoint, String> mockReportPointHandler, ReportableEntityHandler<ReportSourceTag, SourceTag> mockSourceTagHandler, ReportableEntityHandler<ReportPoint, String> mockHistogramHandler, ReportableEntityHandler<Span, String> mockTraceHandler, ReportableEntityHandler<SpanLogs, String> mockTraceSpanLogsHandler, ReportableEntityHandler<ReportEvent, Event> mockEventHandler) { return new ReportableEntityHandlerFactory() { @SuppressWarnings("unchecked") @Override public <T, U> ReportableEntityHandler<T, U> getHandler(HandlerKey handlerKey) { switch (handlerKey.getEntityType()) { case POINT: return (ReportableEntityHandler<T, U>) mockReportPointHandler; case SOURCE_TAG: return (ReportableEntityHandler<T, U>) mockSourceTagHandler; case HISTOGRAM: return (ReportableEntityHandler<T, U>) mockHistogramHandler; case TRACE: return (ReportableEntityHandler<T, U>) mockTraceHandler; case TRACE_SPAN_LOGS: return (ReportableEntityHandler<T, U>) mockTraceSpanLogsHandler; case EVENT: return (ReportableEntityHandler<T, U>) mockEventHandler; default: throw new IllegalArgumentException("Unknown entity type"); } } @Override public void shutdown(@Nonnull String handle) { } }; } }
33.963415
85
0.744345
3155bba8cd12794676077105a2c9b8c95f6d40cc
5,009
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. package com.starrocks.scheduler; import com.google.common.collect.Maps; import com.google.common.collect.Queues; import com.starrocks.common.Config; import com.starrocks.common.util.UUIDUtil; import com.starrocks.scheduler.persist.TaskRunStatus; import com.starrocks.scheduler.persist.TaskRunStatusChange; import com.starrocks.server.GlobalStateMgr; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.concurrent.Future; public class TaskRunManager { private static final Logger LOG = LogManager.getLogger(TaskRunManager.class); // taskId -> pending TaskRun Queue, for each Task only support 1 running taskRun currently, // so the map value is FIFO queue private final Map<Long, Queue<TaskRun>> pendingTaskRunMap = Maps.newConcurrentMap(); // taskId -> running TaskRun, for each Task only support 1 running taskRun currently, // so the map value is not queue private final Map<Long, TaskRun> runningTaskRunMap = Maps.newConcurrentMap(); // include SUCCESS/FAILED/CANCEL taskRun private final TaskRunHistory taskRunHistory = new TaskRunHistory(); // Use to execute actual TaskRun private final TaskRunExecutor taskRunExecutor = new TaskRunExecutor(); public SubmitResult submitTaskRun(TaskRun taskRun) { // duplicate submit if (taskRun.getStatus() != null) { return new SubmitResult(taskRun.getStatus().getQueryId(), SubmitResult.SubmitStatus.FAILED); } if (pendingTaskRunMap.keySet().size() > Config.task_runs_queue_length) { LOG.warn("pending TaskRun exceeds task_runs_queue_length:{}, reject the submit.", Config.task_runs_queue_length); return new SubmitResult(null, SubmitResult.SubmitStatus.REJECTED); } String queryId = UUIDUtil.genUUID().toString(); TaskRunStatus status = taskRun.initStatus(queryId, System.currentTimeMillis()); GlobalStateMgr.getCurrentState().getEditLog().logTaskRunCreateStatus(status); long taskId = taskRun.getTaskId(); Queue<TaskRun> taskRuns = pendingTaskRunMap.computeIfAbsent(taskId, u -> Queues.newConcurrentLinkedQueue()); taskRuns.offer(taskRun); return new SubmitResult(queryId, SubmitResult.SubmitStatus.SUBMITTED); } // check if a running TaskRun is complete and remove it from running TaskRun map public void checkRunningTaskRun() { Iterator<Long> runningIterator = runningTaskRunMap.keySet().iterator(); while (runningIterator.hasNext()) { Long taskId = runningIterator.next(); TaskRun taskRun = runningTaskRunMap.get(taskId); if (taskRun == null) { LOG.warn("failed to get running TaskRun by taskId:{}", taskId); runningIterator.remove(); return; } Future<?> future = taskRun.getFuture(); if (future.isDone()) { runningIterator.remove(); taskRunHistory.addHistory(taskRun.getStatus()); TaskRunStatusChange statusChange = new TaskRunStatusChange(taskRun.getTaskId(), taskRun.getStatus(), Constants.TaskRunState.RUNNING, taskRun.getStatus().getState()); GlobalStateMgr.getCurrentState().getEditLog().logUpdateTaskRun(statusChange); } } } // schedule the pending TaskRun that can be run into running TaskRun map public void scheduledPendingTaskRun() { int currentRunning = runningTaskRunMap.size(); Iterator<Long> pendingIterator = pendingTaskRunMap.keySet().iterator(); while (pendingIterator.hasNext()) { Long taskId = pendingIterator.next(); TaskRun runningTaskRun = runningTaskRunMap.get(taskId); if (runningTaskRun == null) { Queue<TaskRun> taskRunQueue = pendingTaskRunMap.get(taskId); if (taskRunQueue.size() == 0) { pendingIterator.remove(); } else { if (currentRunning >= Config.task_runs_concurrency) { break; } TaskRun pendingTaskRun = taskRunQueue.poll(); taskRunExecutor.executeTaskRun(pendingTaskRun); runningTaskRunMap.put(taskId, pendingTaskRun); // RUNNING state persistence is not necessary currently currentRunning++; } } } } public Map<Long, Queue<TaskRun>> getPendingTaskRunMap() { return pendingTaskRunMap; } public Map<Long, TaskRun> getRunningTaskRunMap() { return runningTaskRunMap; } public TaskRunHistory getTaskRunHistory() { return taskRunHistory; } }
41.741667
116
0.659812
0a225a49fc859a75e79135dc672d06496aa91bf0
47,665
package vista; import controlador.CoordinadorCuarentenario; import java.awt.Color; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import logica.LogicaCuarentenario; import maps.java.MapsJava; import maps.java.ShowMaps; import modeloBO.CuarentenarioBO; import modeloBO.UsuarioBO; import sizin.Box; import sizin.ClaseObjetoParaComboBox; import sizin.ClaseObjetoParaLista; import sizin.ConfiguracionGlobal; import sizin.JFrameConFondo; import sizin.JLabelImagenAjusta; import sizin.JTextFieldLimit; import sizin.Lista; import sizin.MyRenderer; import sizin.Reloj; import sizin.Tabla; import sizin.URLabel; import sizin.Ubicacion; /** * * @author Erneski Coronado */ public class Epidemiologia extends JFrameConFondo { private Lista tax = new Lista(); private URLabel label; ConfiguracionGlobal config = new ConfiguracionGlobal(); private ClaseObjetoParaLista taxo = null; Tabla cua = new Tabla(); Tabla inc= new Tabla(); LogicaCuarentenario miLogicaCua; CoordinadorCuarentenario miCoordinadorCuarentenario; private Epidemiologia miVentanaEpi; Integer id_cuarentena=0; private Box comboestado = new Box(); Ubicacion ObjUbicacion=new Ubicacion(); /** * Creates new form Epidemiologia */ public Epidemiologia() { MapsJava.setKey("AIzaSyCzWaJYw_MW87ganzyaVlxB9igfGMTTrW8"); initComponents(); setImagen("imagenes/fondo_difuminado.jpg");//se pasa la imagen de fondo del formulario JLabelImagenAjusta logo = new JLabelImagenAjusta(); logo.ImagenJLabel(jLabelLogo, "imagenes/logo_sistema.png"); jLabelLogo_des.setText(JLabelImagenAjusta.convertToMultiline("SISTEMA DE INFORMACIÓN PARA EL REGISTRO Y ANALISIS\n" + "DE MUESTRAS ZOOPATÓGENAS DE LA RED DE \n" + "LABORATORIOS DE DIAGNÓSTICO ZOOSANITARIO DEL INSAI\n")); Reloj r = new Reloj(); jLabelFechaRG.setText(r.Hora()); label = new URLabel(); //tax= new Lista(); tax.consultalist(config.lista_taxon_inicial, "tax.tsn", "tax.nombre_completo", "tax.rango_id", "ran.rango");//cargamos la consulta para cargar la especie tax.LLenarLista();//llenamos el combo de la especie cua.crearmodelocuarentenario(); cua.columnastabla(4, config.tabla_cuarentenario); cua.LlenarTabla(); inc.crearmodeloinciencias(); Integer tam_inc[] = {70,180,160,220,100,100,160,120,120,100,120,140,160,80,80,70,160,100,100}; for (int i = 0; i < 19; i++) { jTableIncidencias.getColumnModel().getColumn(i).setPreferredWidth(tam_inc[i]); jTableIncidencias.getColumnModel().getColumn(i).setHeaderRenderer(new MyRenderer(Color.CYAN.brighter(), Color.BLACK.darker())); } jTableCuarentenarios.setModel(cua.getModelo()); jTextFieldNombreComun.setDocument(new JTextFieldLimit(45, false)); jTextFieldDescripcion.setDocument(new JTextFieldLimit(255, false)); jInternalFrameOrganismos.setVisible(false); comboestado.consultabox2(config.box_consulta_estado, "id_estado", "estado"); comboestado.LLenarBoxConID(); jComboBoxEstado.setModel(comboestado.getModelo()); Integer tam_detalle[] = {80, 160, 160, 250}; for (int i = 0; i < 4; i++) { jTableCuarentenarios.getColumnModel().getColumn(i).setPreferredWidth(tam_detalle[i]); jTableCuarentenarios.getColumnModel().getColumn(i).setHeaderRenderer(new MyRenderer(Color.CYAN.brighter(), Color.BLACK.darker())); } } private void iniciarCuarentena() { /*Se instancian las clases*/ miLogicaCua = new LogicaCuarentenario(); miCoordinadorCuarentenario = new CoordinadorCuarentenario(); /*Se establecen las relaciones entre clases*/ this.setCoordinadorCuarentenario(miCoordinadorCuarentenario); miLogicaCua.setCoordinador(miCoordinadorCuarentenario); miCoordinadorCuarentenario.setMiVentanaConfiguracion(miVentanaEpi); miCoordinadorCuarentenario.setMiLogica(miLogicaCua); } public void setCoordinadorCuarentenario(CoordinadorCuarentenario miCoordinador) { this.miCoordinadorCuarentenario = miCoordinador; } private void iniciar() { /*Se instancian las clases*/ miVentanaEpi = new Epidemiologia(); miVentanaEpi.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabelFechaRG = new javax.swing.JLabel(); jLabelLogo_des = new javax.swing.JLabel(); jLabelLogo = new javax.swing.JLabel(); jPanelBotonesSolicitud = new javax.swing.JPanel(); jButtonAbrirOrganismos = new javax.swing.JButton(); jButtonAbrirBuscarIncidencia = new javax.swing.JButton(); jSeparatorSolicitudes = new javax.swing.JSeparator(); jLayeredPane1 = new javax.swing.JLayeredPane(); jInternalFrameOrganismos = new javax.swing.JInternalFrame(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTableCuarentenarios = new javax.swing.JTable(); jPanel3 = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); jListTaxon = new javax.swing.JList(); jButtonTaxReset = new javax.swing.JButton(); jTextFieldNombreComun = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jButtonTax = new javax.swing.JButton(); jPanelUrl = new javax.swing.JPanel(); jTextFieldDescripcion = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButtonEliminar = new javax.swing.JButton(); jInternalFrameIncidencias = new javax.swing.JInternalFrame(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTableIncidencias = new javax.swing.JTable(); jPanel6 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jComboBoxEstado = new javax.swing.JComboBox(); jButtonBuscar = new javax.swing.JButton(); jButtonMapa = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("SIZOIN - Epidemiología"); setExtendedState(6); jLabelFechaRG.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabelFechaRG.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabelFechaRG.setText("jLabel1"); jLabelLogo_des.setFont(new java.awt.Font("Candara", 1, 18)); // NOI18N jLabelLogo_des.setForeground(new java.awt.Color(255, 102, 102)); jLabelLogo_des.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jPanelBotonesSolicitud.setBackground(new java.awt.Color(255, 255, 255)); jPanelBotonesSolicitud.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButtonAbrirOrganismos.setBackground(new java.awt.Color(204, 255, 204)); jButtonAbrirOrganismos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/agregar32.png"))); // NOI18N jButtonAbrirOrganismos.setToolTipText("Agregar Organismos Cuarentenarios en Venezuela"); jButtonAbrirOrganismos.setBorderPainted(false); jButtonAbrirOrganismos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButtonAbrirOrganismosMouseClicked(evt); } }); jButtonAbrirBuscarIncidencia.setBackground(new java.awt.Color(204, 204, 255)); jButtonAbrirBuscarIncidencia.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/buscar32.png"))); // NOI18N jButtonAbrirBuscarIncidencia.setToolTipText("Consultar Incidencias Epidemiológicas"); jButtonAbrirBuscarIncidencia.setBorderPainted(false); jButtonAbrirBuscarIncidencia.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButtonAbrirBuscarIncidenciaMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jButtonAbrirBuscarIncidenciaMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jButtonAbrirBuscarIncidenciaMouseExited(evt); } }); javax.swing.GroupLayout jPanelBotonesSolicitudLayout = new javax.swing.GroupLayout(jPanelBotonesSolicitud); jPanelBotonesSolicitud.setLayout(jPanelBotonesSolicitudLayout); jPanelBotonesSolicitudLayout.setHorizontalGroup( jPanelBotonesSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBotonesSolicitudLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelBotonesSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonAbrirBuscarIncidencia) .addComponent(jButtonAbrirOrganismos)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelBotonesSolicitudLayout.setVerticalGroup( jPanelBotonesSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBotonesSolicitudLayout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(jButtonAbrirOrganismos) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonAbrirBuscarIncidencia) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLayeredPane1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); jLayeredPane1.setMaximumSize(new java.awt.Dimension(1200, 481)); jLayeredPane1.setMinimumSize(new java.awt.Dimension(745, 481)); jLayeredPane1.setPreferredSize(new java.awt.Dimension(780, 481)); jInternalFrameOrganismos.setClosable(true); jInternalFrameOrganismos.setTitle("Organismos Cuarentenarios"); jInternalFrameOrganismos.setMaximumSize(new java.awt.Dimension(757, 457)); jInternalFrameOrganismos.setMinimumSize(new java.awt.Dimension(757, 457)); jInternalFrameOrganismos.setVisible(true); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Organismos Cuarentenarios Registrados")); jTableCuarentenarios.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTableCuarentenariosMouseClicked(evt); } }); jScrollPane1.setViewportView(jTableCuarentenarios); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jListTaxon.setModel(tax.modelo); jListTaxon.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { jListTaxonValueChanged(evt); } }); jScrollPane4.setViewportView(jListTaxon); jButtonTaxReset.setBackground(new java.awt.Color(255, 255, 255)); jButtonTaxReset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/refrescar.png"))); // NOI18N jButtonTaxReset.setToolTipText("Resetear Taxonomía"); jButtonTaxReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTaxResetActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel2.setText("Descripción:"); jButtonTax.setBackground(new java.awt.Color(255, 255, 255)); jButtonTax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/buscar.png"))); // NOI18N jButtonTax.setToolTipText("Buscar Hijos del Taxon"); jButtonTax.setPreferredSize(new java.awt.Dimension(32, 32)); jButtonTax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTaxActionPerformed(evt); } }); jPanelUrl.setBackground(new java.awt.Color(255, 255, 255)); jPanelUrl.setBorder(javax.swing.BorderFactory.createTitledBorder("Ayuda Taxonómica")); javax.swing.GroupLayout jPanelUrlLayout = new javax.swing.GroupLayout(jPanelUrl); jPanelUrl.setLayout(jPanelUrlLayout); jPanelUrlLayout.setHorizontalGroup( jPanelUrlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 372, Short.MAX_VALUE) ); jPanelUrlLayout.setVerticalGroup( jPanelUrlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 69, Short.MAX_VALUE) ); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel1.setText("Nombre Común:"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldNombreComun, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldDescripcion)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonTax, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonTaxReset, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addComponent(jPanelUrl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButtonTax, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonTaxReset)) .addComponent(jPanelUrl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldNombreComun, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jTextFieldDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jButton1.setBackground(new java.awt.Color(255, 255, 255)); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/agregar.png"))); // NOI18N jButton1.setToolTipText("Agregar el organismo"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButtonEliminar.setBackground(new java.awt.Color(255, 255, 255)); jButtonEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/papelera32.png"))); // NOI18N jButtonEliminar.setToolTipText("Eliminar el organismo"); jButtonEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonEliminarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButtonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); javax.swing.GroupLayout jInternalFrameOrganismosLayout = new javax.swing.GroupLayout(jInternalFrameOrganismos.getContentPane()); jInternalFrameOrganismos.getContentPane().setLayout(jInternalFrameOrganismosLayout); jInternalFrameOrganismosLayout.setHorizontalGroup( jInternalFrameOrganismosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jInternalFrameOrganismosLayout.setVerticalGroup( jInternalFrameOrganismosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jInternalFrameIncidencias.setClosable(true); jInternalFrameIncidencias.setTitle("Organismos Cuarentenarios"); jInternalFrameIncidencias.setMaximumSize(new java.awt.Dimension(757, 457)); jInternalFrameIncidencias.setMinimumSize(new java.awt.Dimension(757, 457)); jInternalFrameIncidencias.setVisible(true); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Incidencias Epidemiológicas")); jScrollPane2.setAutoscrolls(true); jTableIncidencias.setModel(inc.modelo); jTableIncidencias.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); jTableIncidencias.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTableIncidenciasMouseClicked(evt); } }); jScrollPane2.setViewportView(jTableIncidencias); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1076, Short.MAX_VALUE) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE) .addContainerGap()) ); jPanel6.setBackground(new java.awt.Color(255, 255, 255)); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel4.setText("Estado:"); jComboBoxEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jButtonBuscar.setBackground(new java.awt.Color(255, 255, 255)); jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/buscar.png"))); // NOI18N jButtonBuscar.setToolTipText("Agregar el organismo"); jButtonBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonBuscarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(jComboBoxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBoxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jButtonMapa.setBackground(new java.awt.Color(255, 255, 255)); jButtonMapa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/globo16.png"))); // NOI18N jButtonMapa.setToolTipText("Visualizar en mapa"); jButtonMapa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonMapaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonMapa, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jButtonMapa, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); javax.swing.GroupLayout jInternalFrameIncidenciasLayout = new javax.swing.GroupLayout(jInternalFrameIncidencias.getContentPane()); jInternalFrameIncidencias.getContentPane().setLayout(jInternalFrameIncidenciasLayout); jInternalFrameIncidenciasLayout.setHorizontalGroup( jInternalFrameIncidenciasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jInternalFrameIncidenciasLayout.setVerticalGroup( jInternalFrameIncidenciasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1); jLayeredPane1.setLayout(jLayeredPane1Layout); jLayeredPane1Layout.setHorizontalGroup( jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jInternalFrameOrganismos, javax.swing.GroupLayout.PREFERRED_SIZE, 716, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(482, Short.MAX_VALUE)) .addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jInternalFrameIncidencias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(18, Short.MAX_VALUE))) ); jLayeredPane1Layout.setVerticalGroup( jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jInternalFrameOrganismos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jInternalFrameIncidencias, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap())) ); jLayeredPane1.setLayer(jInternalFrameOrganismos, javax.swing.JLayeredPane.DEFAULT_LAYER); jLayeredPane1.setLayer(jInternalFrameIncidencias, javax.swing.JLayeredPane.DEFAULT_LAYER); try { jInternalFrameIncidencias.setMaximum(true); } catch (java.beans.PropertyVetoException e1) { e1.printStackTrace(); } javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabelLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabelFechaRG, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabelLogo_des, javax.swing.GroupLayout.PREFERRED_SIZE, 473, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 505, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addComponent(jPanelBotonesSolicitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1210, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) .addComponent(jSeparatorSolicitudes) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabelFechaRG, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelLogo_des, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparatorSolicitudes, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanelBotonesSolicitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 364, Short.MAX_VALUE)) .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonAbrirOrganismosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAbrirOrganismosMouseClicked jInternalFrameOrganismos.setVisible(true); jInternalFrameOrganismos.toFront(); }//GEN-LAST:event_jButtonAbrirOrganismosMouseClicked private void jButtonAbrirBuscarIncidenciaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAbrirBuscarIncidenciaMouseClicked jInternalFrameIncidencias.setVisible(true); jInternalFrameIncidencias.toFront(); }//GEN-LAST:event_jButtonAbrirBuscarIncidenciaMouseClicked private void jButtonAbrirBuscarIncidenciaMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAbrirBuscarIncidenciaMouseEntered /* jLabelImagenAjusta aju=new jLabelImagenAjusta(); aju.ImagenJLabel(jLabelvisualizar, "iconos/presentabuscarregistro.jpg");*/ }//GEN-LAST:event_jButtonAbrirBuscarIncidenciaMouseEntered private void jButtonAbrirBuscarIncidenciaMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonAbrirBuscarIncidenciaMouseExited }//GEN-LAST:event_jButtonAbrirBuscarIncidenciaMouseExited private void jButtonTaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTaxActionPerformed ClaseObjetoParaLista taxo_1 = (ClaseObjetoParaLista) jListTaxon.getSelectedValue(); //creamos objeto para extraer el id Integer tsn = taxo_1.getId(); tax.consultalist(config.taxonomia(tsn), "tax.tsn", "tax.nombre_completo", "tax.rango_id", "ran.rango");//cargamos la consulta para cargar la especie tax.LLenarLista();//llenamos el combo de la especie }//GEN-LAST:event_jButtonTaxActionPerformed private void jListTaxonValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListTaxonValueChanged taxo = (ClaseObjetoParaLista) jListTaxon.getSelectedValue(); //creamos objeto para extraer el id @SuppressWarnings("UnusedAssignment") String url = null;//hay que limpiarlo para que lo muestre vacio jPanelUrl.add(label); label.setLocation(10, 30); if (taxo != null) { url = "http://www.itis.gov/servlet/SingleRpt/SingleRpt?search_topic=TSN&search_value=" + taxo.getId(); label.setURL(url); label.setText("Rango Taxonomico: " + taxo.getRango() + ", Mas sobre " + taxo.getNombre()); label.setSize(350, 15); } }//GEN-LAST:event_jListTaxonValueChanged private void jButtonTaxResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTaxResetActionPerformed tax.consultalist(config.lista_taxon_inicial, "tax.tsn", "tax.nombre_completo", "tax.rango_id", "ran.rango");//cargamos la consulta para cargar la especie tax.LLenarLista();//llenamos el combo de la especie label.setURL(""); label.setText(""); }//GEN-LAST:event_jButtonTaxResetActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { this.iniciarCuarentena(); CuarentenarioBO miCuarentena = new CuarentenarioBO(); miCuarentena.setId_tsn(taxo.getId()); miCuarentena.setNombre_comun(jTextFieldNombreComun.getText()); miCuarentena.setDescripcion(jTextFieldDescripcion.getText()); if (miCoordinadorCuarentenario.registrarOrganismo(miCuarentena) == true) { jTextFieldNombreComun.setText(null); jTextFieldDescripcion.setText(null); cua.LlenarTabla(); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Error en el Ingreso de Datos", "Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton1ActionPerformed private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed this.iniciarCuarentena(); if (id_cuarentena != null) { this.iniciarCuarentena(); int respuesta = JOptionPane.showConfirmDialog(this, "Desea eliminar el organismo seleccionado de la lista cuarentenaria?", "Confirmacion", JOptionPane.YES_NO_OPTION); if (respuesta == JOptionPane.YES_NO_OPTION) { if (miCoordinadorCuarentenario.eliminarOrganismo(id_cuarentena) == true) { cua.LlenarTabla(); } } } else { JOptionPane.showMessageDialog(null, "Seleccione en la tabla el usuario a eliminar", "Informacion", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_jButtonEliminarActionPerformed private void jTableCuarentenariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableCuarentenariosMouseClicked id_cuarentena = Integer.parseInt(jTableCuarentenarios.getModel().getValueAt(jTableCuarentenarios.getSelectedRow(), 0).toString()); }//GEN-LAST:event_jTableCuarentenariosMouseClicked private void jTableIncidenciasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableIncidenciasMouseClicked ObjUbicacion.setLatitud(Double.parseDouble(jTableIncidencias.getModel().getValueAt(jTableIncidencias.getSelectedRow(), 14).toString())); ObjUbicacion.setLongitud(Double.parseDouble(jTableIncidencias.getModel().getValueAt(jTableIncidencias.getSelectedRow(), 13).toString())); }//GEN-LAST:event_jTableIncidenciasMouseClicked private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed if (jComboBoxEstado.getSelectedIndex() != 0) { String sql; ClaseObjetoParaComboBox estado = (ClaseObjetoParaComboBox) jComboBoxEstado.getSelectedItem();//variable para extraer el id del tipo de analisis String est = estado.getNombre(); sql = config.tabla_consulta_incidencias(est); //jTableIncidencias.setModel(inc.getModelo()); //if (miCoordinadorCuarentenario.buscarRegistro(sql) == true) { inc.columnastabla(19, sql); inc.LlenarTabla(); //} else { //JOptionPane.showMessageDialog(null, "Este estado no reporta incidencias"); //} } }//GEN-LAST:event_jButtonBuscarActionPerformed private void jButtonMapaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMapaActionPerformed ShowMaps ObjShow=new ShowMaps(); //String direccionMapa=ObjShow.getURLMap(ObjUbicacion.getDireccion()); String coordenadas="https://www.google.co.ve/maps/@"+ObjUbicacion.getLatitud()+","+ObjUbicacion.getLongitud()+",14z?hl=es"; try { try { //JOptionPane.showMessageDialog(rootPane, coordenadas, coordenadas, WIDTH, null); Desktop.getDesktop().browse(new URI(coordenadas)); } catch (IOException ex) { Logger.getLogger(Epidemiologia.class.getName()).log(Level.SEVERE, null, ex); } } catch (URISyntaxException ex) { Logger.getLogger(Epidemiologia.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButtonMapaActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Epidemiologia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Epidemiologia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Epidemiologia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Epidemiologia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Epidemiologia().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButtonAbrirBuscarIncidencia; private javax.swing.JButton jButtonAbrirOrganismos; private javax.swing.JButton jButtonBuscar; private javax.swing.JButton jButtonEliminar; private javax.swing.JButton jButtonMapa; private javax.swing.JButton jButtonTax; private javax.swing.JButton jButtonTaxReset; private javax.swing.JComboBox jComboBoxEstado; private javax.swing.JInternalFrame jInternalFrameIncidencias; private javax.swing.JInternalFrame jInternalFrameOrganismos; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabelFechaRG; private javax.swing.JLabel jLabelLogo; private javax.swing.JLabel jLabelLogo_des; private javax.swing.JLayeredPane jLayeredPane1; private javax.swing.JList jListTaxon; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanelBotonesSolicitud; private javax.swing.JPanel jPanelUrl; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSeparator jSeparatorSolicitudes; private javax.swing.JTable jTableCuarentenarios; private javax.swing.JTable jTableIncidencias; private javax.swing.JTextField jTextFieldDescripcion; private javax.swing.JTextField jTextFieldNombreComun; // End of variables declaration//GEN-END:variables }
57.220888
179
0.689122
7381ad5d1e1a8c0cdfc3b508291baa6b81195c5d
2,316
/* * Maisam Alatrach 20091817 * Oudai Fayek 20091861 * Latrobe University * 29/05/2020 */ package com.pages; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.main.DbHandler; import com.main.Log; /* * * update password page SERVLET * Get and Post methods * */ public class UpdatePass extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UpdatePass() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); RequestDispatcher rd = request.getRequestDispatcher("Admin"); rd.include(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //Configure database String[] dbConfig = new String[3]; dbConfig[0] = getServletContext().getInitParameter("dbhost"); dbConfig[1] = getServletContext().getInitParameter("dbusername"); dbConfig[2] = getServletContext().getInitParameter("dbpassword"); DbHandler dbHandler = new DbHandler(dbConfig[0],dbConfig[1],dbConfig[2]); PrintWriter writer=response.getWriter(); String pass = request.getParameter("pass"); String confirm_pass = request.getParameter("confirm_pass"); try { if(request.getSession().getAttribute("session")!=null && pass.contentEquals(confirm_pass) ) { dbHandler.connect(); String username = (String) request.getSession().getAttribute("username"); dbHandler.updatePass(username, pass); Log log = new Log(0,"password successfully updated", "Local Site", true); dbHandler.writeLog(log); dbHandler.disconnect(); response.sendRedirect("Result"); }else { response.sendRedirect("Admin"); } } catch (Exception e) { Log log = new Log(0,e.toString(), "Local Site", false); dbHandler.writeLog(log); writer.append(e.toString()); } } }
30.077922
119
0.738774
934c0ebe9623318db3dbb16211215e2d22ec4ca2
2,240
package org.nico.ratel.landlords.server.robot; import org.nico.noson.Noson; import org.nico.ratel.landlords.entity.ClientSide; import org.nico.ratel.landlords.entity.PokerSell; import org.nico.ratel.landlords.entity.Room; import org.nico.ratel.landlords.enums.SellType; import org.nico.ratel.landlords.enums.ServerEventCode; import org.nico.ratel.landlords.helper.PokerHelper; import org.nico.ratel.landlords.helper.TimeHelper; import org.nico.ratel.landlords.print.SimplePrinter; import org.nico.ratel.landlords.robot.RobotDecisionMakers; import org.nico.ratel.landlords.server.ServerContains; import org.nico.ratel.landlords.server.event.ServerEventListener; public class RobotEventListener_CODE_GAME_POKER_PLAY implements RobotEventListener{ @Override public void call(ClientSide robot, String data) { ServerContains.THREAD_EXCUTER.execute(() -> { Room room = ServerContains.getRoom(robot.getRoomId()); PokerSell lastPokerSell = null; PokerSell pokerSell = null; if(room.getLastSellClient() != robot.getId()) { lastPokerSell = room.getLastPokerShell(); pokerSell = RobotDecisionMakers.howToPlayPokers(room.getDifficultyCoefficient(), lastPokerSell, robot.getPokers()); }else { pokerSell = RobotDecisionMakers.howToPlayPokers(room.getDifficultyCoefficient(), null, robot.getPokers()); } if(pokerSell != null && lastPokerSell != null) { SimplePrinter.serverLog("Robot monitoring[room:" + room.getId() + "]"); SimplePrinter.serverLog("last sell -> " + lastPokerSell.toString()); SimplePrinter.serverLog("robot sell -> " + pokerSell.toString()); SimplePrinter.serverLog("robot poker -> " + PokerHelper.textOnlyNoType(robot.getPokers())); } TimeHelper.sleep(300); if(pokerSell == null || pokerSell.getSellType() == SellType.ILLEGAL) { ServerEventListener.get(ServerEventCode.CODE_GAME_POKER_PLAY_PASS).call(robot, data); }else { Character[] cs = new Character[pokerSell.getSellPokers().size()]; for(int index = 0; index < cs.length; index ++) { cs[index] = pokerSell.getSellPokers().get(index).getLevel().getAlias()[0]; } ServerEventListener.get(ServerEventCode.CODE_GAME_POKER_PLAY).call(robot, Noson.reversal(cs)); } }); } }
42.264151
119
0.75
6e3cf5b565575ccd9dbf9603350e5e129be92167
1,115
package fr.zom.zapi.utils; import net.minecraft.item.Food; import net.minecraft.potion.EffectInstance; import javax.annotation.Nullable; import java.util.function.Supplier; public class FoodUtils { public static Food createFood(boolean isMeat, boolean isFastToEat, int hunger, float saturation, @Nullable Supplier<EffectInstance> effect, float probability) { Food.Builder builder = new Food.Builder(); if( isMeat ) { builder.meat(); } if( isFastToEat ) { builder.fastToEat(); } if( effect != null ) { builder.effect(effect, probability); } builder.hunger(hunger).saturation(saturation); return builder.build(); } public static Food createFood(boolean isMeat, boolean isFastToEat, int hunger, float saturation) { return createFood(isMeat, isFastToEat, hunger, saturation, null, 0); } public static Food createFood(boolean isMeat, int hunger, float saturation) { return createFood(isMeat, false, hunger, saturation, null, 0); } public static Food createFood(int hunger, float saturation) { return createFood(true, false, hunger, saturation, null, 0); } }
22.3
159
0.733632
3d8a266d5687f823593d5d7e7cf19f5edc9b7f27
4,180
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.myapp.gui.Matiere; import com.codename1.components.FloatingActionButton; import com.codename1.components.InfiniteProgress; import com.codename1.components.MultiButton; import com.codename1.ui.Button; import com.codename1.ui.Component; import static com.codename1.ui.Component.BOTTOM; import static com.codename1.ui.Component.CENTER; import com.codename1.ui.Container; import com.codename1.ui.Display; import com.codename1.ui.FontImage; import com.codename1.ui.Form; import com.codename1.ui.Toolbar; import com.codename1.ui.layouts.BoxLayout; import com.codename1.ui.layouts.FlowLayout; import com.codename1.ui.plaf.Style; import com.codename1.ui.util.Resources; import com.mycompany.myapp.gui.HomeForm; import com.mycompany.myapp.gui.SideMenuBaseForm; import entities.Matiere; import java.io.IOException; import java.util.ArrayList; import services.ServiceMatiere; /** * * @author Eya */ public class ListMatiereForm extends SideMenuBaseForm { public ArrayList<Matiere> matieres; public ListMatiereForm(Resources res) { super(BoxLayout.y()); Toolbar tb = getToolbar(); tb.setTitleCentered(false); Button menuButton = new Button(""); menuButton.setUIID("Title"); FontImage.setMaterialIcon(menuButton, FontImage.MATERIAL_MENU); menuButton.addActionListener(e -> getToolbar().openSideMenu()); Container titleCmp = BoxLayout.encloseY( FlowLayout.encloseIn(menuButton) ); FloatingActionButton fab = FloatingActionButton.createFAB(FontImage.MATERIAL_SCHOOL); fab.addActionListener(e -> { new HomeForm(res).show(); }); fab.getAllStyles().setMarginUnit(Style.UNIT_TYPE_PIXELS); // fab.getAllStyles().setMargin(BOTTOM, completedTasks.getPreferredH() - fab.getPreferredH() / 2); tb.setTitleComponent(fab.bindFabToContainer(titleCmp, CENTER, BOTTOM)); Form current = this; matieres = ServiceMatiere.getInstance().getAll(); int fiveMM = Display.getInstance().convertToPixels(5); Toolbar.setGlobalToolbar(true); add(new InfiniteProgress()); Display.getInstance().scheduleBackgroundTask(() -> { Display.getInstance().callSerially(() -> { removeAll(); for (Matiere u : matieres) { MultiButton mb = new MultiButton(u.getNom()); mb.addActionListener(e -> new ShowMatiere(res, current, u).show()); add(mb); }; revalidate(); }); }); tb.addSearchCommand(e -> { String text = (String) e.getSource(); if (text == null || text.length() == 0) { // clear search for (Component cmp : getContentPane()) { cmp.setHidden(false); cmp.setVisible(true); } getContentPane().animateLayout(150); } else { text = text.toLowerCase(); for (Component cmp : getContentPane()) { MultiButton mb = (MultiButton) cmp; String line1 = mb.getTextLine1(); boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1; mb.setHidden(!show); mb.setVisible(show); } getContentPane().animateLayout(150); } }, 4); FloatingActionButton AddBtn = FloatingActionButton.createFAB(FontImage.MATERIAL_ADD); // Button AddBtn = new Button("ajouter une Matiere"); AddBtn.addActionListener(e -> new AddMatiereForm(res, current).show());; AddBtn.bindFabToContainer(getContentPane()); // getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> new HomeForm().show()); setupSideMenu(res); } }
34.545455
116
0.622727
833d3896bb53a1f41b9092f2e9b845c8b90cc070
18,798
package com.salesmanager.shop.store.api.v1.product; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.salesmanager.core.business.services.catalog.category.CategoryService; import com.salesmanager.core.business.services.catalog.product.ProductService; import com.salesmanager.core.model.catalog.category.Category; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.ProductCriteria; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.model.catalog.product.PersistableProduct; import com.salesmanager.shop.model.catalog.product.ReadableProduct; import com.salesmanager.shop.model.catalog.product.ReadableProductList; import com.salesmanager.shop.store.controller.product.facade.ProductFacade; import com.salesmanager.shop.store.controller.store.facade.StoreFacade; import com.salesmanager.shop.utils.ImageFilePath; import com.salesmanager.shop.utils.LanguageUtils; /** * API to create, read, update and delete a Product * API to create Manufacturer * @author Carl Samson * */ @Controller @RequestMapping("/api/v1") public class ProductApi { private static final Logger LOGGER = LoggerFactory.getLogger(ProductApi.class); // @Inject // private MerchantStoreService merchantStoreService; @Inject private CategoryService categoryService; // @Inject // private CustomerService customerService; @Inject private ProductService productService; @Inject private ProductFacade productFacade; @Inject @Qualifier("img") private ImageFilePath imageUtils; @Inject private StoreFacade storeFacade; @Inject private LanguageUtils languageUtils; @ResponseStatus(HttpStatus.CREATED) @RequestMapping( value={"/private/products/{productId}/category/{categoryId}","/auth/products/{productId}/category/{categoryId}"}, method=RequestMethod.POST) public @ResponseBody ReadableProduct addProductToCategory(@PathVariable Long productId, @PathVariable Long categoryId, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE); Language language = languageUtils.getRESTLanguage(request, merchantStore); //get the product Product product = productService.getById(productId); Category category = categoryService.getById(categoryId); ReadableProduct readableProduct = productFacade.addProductToCategory(category, product, language); return readableProduct; } catch (Exception e) { LOGGER.error("Error while adding product to category",e); try { response.sendError(503, "Error while adding product to category " + e.getMessage()); } catch (Exception ignore) { } return null; } } @ResponseStatus(HttpStatus.CREATED) @RequestMapping( value={"/private/products","/auth/products"}, method=RequestMethod.POST) public @ResponseBody PersistableProduct create(@Valid @RequestBody PersistableProduct product, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE); Language language = languageUtils.getRESTLanguage(request, merchantStore); productFacade.saveProduct(merchantStore, product, language); return product; } catch (Exception e) { LOGGER.error("Error while creating product",e); try { response.sendError(503, "Error while creating product " + e.getMessage()); } catch (Exception ignore) { } return null; } } @ResponseStatus(HttpStatus.OK) @RequestMapping( value={"/private/products/{id}","/auth/products/{id}"}, method=RequestMethod.DELETE) public void delete(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) throws Exception { try { Product product = productService.getById(id); if(product != null){ productFacade.deleteProduct(product); }else{ response.sendError(404, "No Product found for ID : " + id); } } catch (Exception e) { LOGGER.error("Error while deleting product",e); try { response.sendError(503, "Error while deleting product " + e.getMessage()); } catch (Exception ignore) { } } } /** @RequestMapping( value="/private/{store}/manufacturer", method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public PersistableManufacturer createManufacturer(@PathVariable final String store, @Valid @RequestBody PersistableManufacturer manufacturer, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } } if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); response.sendError(503, "Merchant store is null for code " + store); return null; } PersistableManufacturerPopulator populator = new PersistableManufacturerPopulator(); populator.setLanguageService(languageService); com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer manuf = new com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer(); populator.populate(manufacturer, manuf, merchantStore, merchantStore.getDefaultLanguage()); manufacturerService.save(manuf); manufacturer.setId(manuf.getId()); return manufacturer; } catch (Exception e) { LOGGER.error("Error while saving product",e); try { response.sendError(503, "Error while saving product " + e.getMessage()); } catch (Exception ignore) { } return null; } } @RequestMapping( value="/private/{store}/product/optionValue", method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public PersistableProductOptionValue createProductOptionValue(@PathVariable final String store, @Valid @RequestBody PersistableProductOptionValue optionValue, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } } if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); response.sendError(503, "Merchant store is null for code " + store); return null; } PersistableProductOptionValuePopulator populator = new PersistableProductOptionValuePopulator(); populator.setLanguageService(languageService); com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue optValue = new com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue(); populator.populate(optionValue, optValue, merchantStore, merchantStore.getDefaultLanguage()); productOptionValueService.save(optValue); optionValue.setId(optValue.getId()); return optionValue; } catch (Exception e) { LOGGER.error("Error while saving product option value",e); try { response.sendError(503, "Error while saving product option value" + e.getMessage()); } catch (Exception ignore) { } return null; } } @RequestMapping( value="/private/{store}/product/option", method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public PersistableProductOption createProductOption(@PathVariable final String store, @Valid @RequestBody PersistableProductOption option, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } } if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); response.sendError(503, "Merchant store is null for code " + store); return null; } PersistableProductOptionPopulator populator = new PersistableProductOptionPopulator(); populator.setLanguageService(languageService); com.salesmanager.core.model.catalog.product.attribute.ProductOption opt = new com.salesmanager.core.model.catalog.product.attribute.ProductOption(); populator.populate(option, opt, merchantStore, merchantStore.getDefaultLanguage()); productOptionService.save(opt); option.setId(opt.getId()); return option; } catch (Exception e) { LOGGER.error("Error while saving product option",e); try { response.sendError(503, "Error while saving product option" + e.getMessage()); } catch (Exception ignore) { } return null; } } @RequestMapping( value="/private/{store}/product/review", method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public PersistableProductReview createProductReview(@PathVariable final String store, @Valid @RequestBody PersistableProductReview review, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } } if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); response.sendError(500, "Merchant store is null for code " + store); return null; } //rating already exist ProductReview prodReview = productReviewService.getByProductAndCustomer(review.getProductId(), review.getCustomerId()); if(prodReview!=null) { response.sendError(500, "A review already exist for this customer and product"); return null; } //rating maximum 5 if(review.getRating()>Constants.MAX_REVIEW_RATING_SCORE) { response.sendError(503, "Maximum rating score is " + Constants.MAX_REVIEW_RATING_SCORE); return null; } PersistableProductReviewPopulator populator = new PersistableProductReviewPopulator(); populator.setLanguageService(languageService); populator.setCustomerService(customerService); populator.setProductService(productService); com.salesmanager.core.model.catalog.product.review.ProductReview rev = new com.salesmanager.core.model.catalog.product.review.ProductReview(); populator.populate(review, rev, merchantStore, merchantStore.getDefaultLanguage()); productReviewService.create(rev); review.setId(rev.getId()); return review; } catch (Exception e) { LOGGER.error("Error while saving product review",e); try { response.sendError(503, "Error while saving product review" + e.getMessage()); } catch (Exception ignore) { } return null; } } @RequestMapping("/public/products/{store}") @ResponseBody public ReadableProductList getProducts(@PathVariable String store, HttpServletRequest request, HttpServletResponse response) throws Exception { *//** default routine **//* MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); if(merchantStore!=null) { if(!merchantStore.getCode().equals(store)) { merchantStore = null; } } if(merchantStore== null) { merchantStore = merchantStoreService.getByCode(store); } if(merchantStore==null) { LOGGER.error("Merchant store is null for code " + store); response.sendError(503, "Merchant store is null for code " + store); return null; } Language l = merchantStore.getDefaultLanguage(); String lang = l.getCode(); if(!StringUtils.isBlank(request.getParameter(Constants.LANG))) { lang = request.getParameter(Constants.LANG); } *//** end default routine **//* return this.getProducts(0, 10000, store, lang, null, null, request, response); }*/ /** * API for getting a product * @param id * @param lang * ?lang=fr|en * @param request * @param response * @return ReadableProduct * @throws Exception * * /api/v1/product/123 */ @RequestMapping(value = "/products/{id}", method=RequestMethod.GET) @ResponseBody public ReadableProduct get(@PathVariable final Long id, @RequestParam(value = "lang", required=false) String lang, HttpServletRequest request, HttpServletResponse response) throws Exception { MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE); Language language = languageUtils.getRESTLanguage(request, merchantStore); ReadableProduct product = productFacade.getProduct(merchantStore, id, language); if(product==null) { response.sendError(404, "Product not fount for id " + id); return null; } return product; } /** * Filtering product lists based on product attributes * ?category=1 * &manufacturer=2 * &type=... * &lang=en|fr NOT REQUIRED, will use request language * &start=0 NOT REQUIRED, can be used for pagination * &count=10 NOT REQUIRED, can be used to limit item count * @param model * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/products", method=RequestMethod.GET) @ResponseBody public ReadableProductList getFiltered( @RequestParam(value = "lang", required=false) String lang, @RequestParam(value = "category", required=false) Long category, @RequestParam(value = "manufacturer", required=false) Long manufacturer, @RequestParam(value = "status", required=false) String status, @RequestParam(value = "owner", required=false) Long owner, @RequestParam(value = "start", required=false) Integer start, @RequestParam(value = "count", required=false) Integer count, HttpServletRequest request, HttpServletResponse response) throws Exception { ProductCriteria criteria = new ProductCriteria(); if(!StringUtils.isBlank(lang)) { criteria.setLanguage(lang); } if(!StringUtils.isBlank(status)) { criteria.setStatus(status); } if(category != null) { List<Long> categoryIds = new ArrayList<Long>(); categoryIds.add(category); criteria.setCategoryIds(categoryIds); } if(manufacturer != null) { criteria.setManufacturerId(manufacturer); } if(owner != null) { criteria.setOwnerId(owner); } if(start != null) { criteria.setStartIndex(start); } if(count != null) { criteria.setMaxCount(count); } //TODO //RENTAL add filter by owner //REPOSITORY to use the new filters try { MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE); Language language = languageUtils.getRESTLanguage(request, merchantStore); ReadableProductList productList = productFacade.getProductListsByCriterias(merchantStore, language, criteria); return productList; } catch(Exception e) { LOGGER.error("Error while filtering products product",e); try { response.sendError(503, "Error while filtering products " + e.getMessage()); } catch (Exception ignore) { } return null; } } @ResponseStatus(HttpStatus.OK) @RequestMapping( value={"/private/products/{productId}/category/{categoryId}","/auth/products/{productId}/category/{categoryId}"}, method=RequestMethod.DELETE) public @ResponseBody ReadableProduct removeProductFromCategory(@PathVariable Long productId, @PathVariable Long categoryId, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE); Language language = languageUtils.getRESTLanguage(request, merchantStore); //get the product Product product = productService.getById(productId); Category category = categoryService.getById(categoryId); ReadableProduct readableProduct = productFacade.removeProductFromCategory(category, product, language); return readableProduct; } catch (Exception e) { LOGGER.error("Error while removing product from category",e); try { response.sendError(503, "Error while removing product from category " + e.getMessage()); } catch (Exception ignore) { } return null; } } @ResponseStatus(HttpStatus.OK) @RequestMapping( value={"/private/products/{id}","/auth/products/{id}"}, method=RequestMethod.PUT) public @ResponseBody PersistableProduct update(@PathVariable Long id, @Valid @RequestBody PersistableProduct product, HttpServletRequest request, HttpServletResponse response) throws Exception { try { MerchantStore merchantStore = storeFacade.getByCode(com.salesmanager.core.business.constants.Constants.DEFAULT_STORE); productFacade.saveProduct(merchantStore, product, merchantStore.getDefaultLanguage()); return product; } catch (Exception e) { LOGGER.error("Error while updating product",e); try { response.sendError(503, "Error while updating product " + e.getMessage()); } catch (Exception ignore) { } return null; } } }
32.02385
236
0.736249
bd04052207e54df6102bf648a76a380053a7f157
1,253
package org.usfirst.frc.team2706.robot.controls; import org.usfirst.frc.team2706.robot.EJoystickButton; import edu.wpi.first.wpilibj.Joystick; /** * Button that activates when a trigger is pressed */ public class TriggerButtonJoystick extends EJoystickButton { private final Joystick joystick; private final int axis; private final double deadzone; /** * Creates a the button for an axis on a joystick * * @param joystick The joystick the axis is on * @param axis The axis to act as a button */ public TriggerButtonJoystick(Joystick joystick, int axis) { this(joystick, axis, 0.1); } /** * Creates a the button for an axis on a joystick * * @param joystick The joystick the axis is on * @param axis The axis to act as a button * @param */ public TriggerButtonJoystick(Joystick joystick, int axis, double deadzone) { super(joystick, axis); this.joystick = joystick; this.axis = axis; this.deadzone = deadzone; } @Override public boolean get() { if (joystick.getRawAxis(axis) < deadzone && joystick.getRawAxis(axis) > -deadzone) { return false; } return true; } }
25.571429
92
0.64166
63596bdde9a28028669890b0aafa0e363617e8ad
6,562
/* * Copyright 2016-2019 Tim Boudreau, Frédéric Yvon Vinet * * 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.nemesis.antlr.v4.netbeans.v8.grammar.file.experimental.toolext; import org.antlr.runtime.Token; import org.antlr.v4.Tool; import org.antlr.v4.codegen.CodeGenerator; import org.antlr.v4.tool.ErrorType; import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.ast.GrammarAST; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.tools.StandardLocation; import static javax.tools.StandardLocation.CLASS_OUTPUT; import static javax.tools.StandardLocation.SOURCE_OUTPUT; import org.nemesis.jfs.JFSFileObject; public class AlternateTokenVocabParser { protected final Grammar g; private final MemoryTool tool; public AlternateTokenVocabParser(Grammar g, MemoryTool tool) { this.g = g; this.tool = tool; } /** * Load a vocab file {@code <vocabName>.tokens} and return mapping. */ public Map<String, Integer> load() { Map<String, Integer> tokens = new LinkedHashMap<String, Integer>(); Path filePath = importedFilePath(); int maxTokenType = -1; BufferedReader br = null; Tool tool = g.tool; String vocabName = g.getOptionString("tokenVocab"); try { JFSFileObject fullFile = getImportedVocabFile(); Pattern tokenDefPattern = Pattern.compile("([^\n]+?)[ \\t]*?=[ \\t]*?([0-9]+)"); br = new BufferedReader(fullFile.openReader(true), fullFile.length()); String tokenDef = br.readLine(); int lineNum = 1; while (tokenDef != null) { Matcher matcher = tokenDefPattern.matcher(tokenDef); if (matcher.find()) { String tokenID = matcher.group(1); String tokenTypeS = matcher.group(2); int tokenType; try { tokenType = Integer.valueOf(tokenTypeS); } catch (NumberFormatException nfe) { tool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION, " bad token type: " + tokenTypeS, lineNum); tokenType = Token.INVALID_TOKEN_TYPE; } tool.log("grammar", "import " + tokenID + "=" + tokenType); tokens.put(tokenID, tokenType); maxTokenType = Math.max(maxTokenType, tokenType); lineNum++; } else { if (tokenDef.length() > 0) { // ignore blank lines tool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION, " bad token def: " + tokenDef, lineNum); } } tokenDef = br.readLine(); } } catch (FileNotFoundException fnfe) { GrammarAST inTree = g.ast.getOptionAST("tokenVocab"); String inTreeValue = inTree.getToken().getText(); if (vocabName.equals(inTreeValue)) { tool.errMgr.grammarError(ErrorType.CANNOT_FIND_TOKENS_FILE_REFD_IN_GRAMMAR, g.fileName, inTree.getToken(), filePath); } else { // must be from -D option on cmd-line not token in tree tool.errMgr.toolError(ErrorType.CANNOT_FIND_TOKENS_FILE_GIVEN_ON_CMDLINE, filePath, g.name); } } catch (Exception e) { tool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE, e, filePath, e.getMessage()); } finally { try { if (br != null) { br.close(); } } catch (IOException ioe) { tool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE, ioe, filePath, ioe.getMessage()); } } return tokens; } private Path importedFilePath() { Path result = Paths.get(g.getOptionString("tokenVocab") + CodeGenerator.VOCAB_FILE_EXTENSION); if (g.tool.libDirectory != null) { result = Paths.get(g.tool.libDirectory).resolve(result); } if (result.startsWith(".")) { result = tool.resolveRelativePath(result.getFileName()); } return result; } /** * Return a File descriptor for vocab file. Look in library or in -o output * path. antlr -o foo T.g4 U.g4 where U needs T.tokens won't work unless we * look in foo too. If we do not find the file in the lib directory then * must assume that the .tokens file is going to be generated as part of * this build and we have defined .tokens files so that they ALWAYS are * generated in the base output directory, which means the current directory * for the command line tool if there was no output directory specified. */ public JFSFileObject getImportedVocabFile() throws FileNotFoundException { Path path = importedFilePath(); JFSFileObject fo = tool.jfs().get(StandardLocation.SOURCE_PATH, path); if (fo == null) { fo = tool.jfs().get(SOURCE_OUTPUT, path); } if (fo == null) { fo = tool.jfs().get(CLASS_OUTPUT, path); } if (fo == null) { throw new FileNotFoundException(path.toString()); } return fo; } }
40.506173
102
0.579092
37e257b4bf807a37d375cda56e16715731fcfb02
3,989
/** * This class is generated by jOOQ */ package generated.tables; /** * This class is generated by jOOQ. */ @javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" }, comments = "This class is generated by jOOQ") @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Names extends org.jooq.impl.TableImpl<generated.tables.records.NamesRecord> { private static final long serialVersionUID = 58103960; /** * The singleton instance of <code>protectme.names</code> */ public static final generated.tables.Names NAMES = new generated.tables.Names(); /** * The class holding records for this type */ @Override public java.lang.Class<generated.tables.records.NamesRecord> getRecordType() { return generated.tables.records.NamesRecord.class; } /** * The column <code>protectme.names.NameID</code>. */ public final org.jooq.TableField<generated.tables.records.NamesRecord, java.lang.Integer> NAMEID = createField("NameID", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>protectme.names.FirstName</code>. */ public final org.jooq.TableField<generated.tables.records.NamesRecord, java.lang.String> FIRSTNAME = createField("FirstName", org.jooq.impl.SQLDataType.VARCHAR.length(50).nullable(false).defaulted(true), this, ""); /** * The column <code>protectme.names.OtherNames</code>. */ public final org.jooq.TableField<generated.tables.records.NamesRecord, java.lang.String> OTHERNAMES = createField("OtherNames", org.jooq.impl.SQLDataType.VARCHAR.length(50).nullable(false).defaulted(true), this, ""); /** * The column <code>protectme.names.MobileNumber</code>. */ public final org.jooq.TableField<generated.tables.records.NamesRecord, java.lang.String> MOBILENUMBER = createField("MobileNumber", org.jooq.impl.SQLDataType.VARCHAR.length(50).nullable(false).defaulted(true), this, ""); /** * The column <code>protectme.names.CompanyID</code>. */ public final org.jooq.TableField<generated.tables.records.NamesRecord, java.lang.Integer> COMPANYID = createField("CompanyID", org.jooq.impl.SQLDataType.INTEGER, this, ""); /** * The column <code>protectme.names.PictureID</code>. */ public final org.jooq.TableField<generated.tables.records.NamesRecord, java.lang.Integer> PICTUREID = createField("PictureID", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaulted(true), this, ""); /** * Create a <code>protectme.names</code> table reference */ public Names() { this("names", null); } /** * Create an aliased <code>protectme.names</code> table reference */ public Names(java.lang.String alias) { this(alias, generated.tables.Names.NAMES); } private Names(java.lang.String alias, org.jooq.Table<generated.tables.records.NamesRecord> aliased) { this(alias, aliased, null); } private Names(java.lang.String alias, org.jooq.Table<generated.tables.records.NamesRecord> aliased, org.jooq.Field<?>[] parameters) { super(alias, generated.Protectme.PROTECTME, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public org.jooq.Identity<generated.tables.records.NamesRecord, java.lang.Integer> getIdentity() { return generated.Keys.IDENTITY_NAMES; } /** * {@inheritDoc} */ @Override public org.jooq.UniqueKey<generated.tables.records.NamesRecord> getPrimaryKey() { return generated.Keys.KEY_NAMES_PRIMARY; } /** * {@inheritDoc} */ @Override public java.util.List<org.jooq.UniqueKey<generated.tables.records.NamesRecord>> getKeys() { return java.util.Arrays.<org.jooq.UniqueKey<generated.tables.records.NamesRecord>>asList(generated.Keys.KEY_NAMES_PRIMARY); } /** * {@inheritDoc} */ @Override public generated.tables.Names as(java.lang.String alias) { return new generated.tables.Names(alias, this); } /** * Rename this table */ public generated.tables.Names rename(java.lang.String name) { return new generated.tables.Names(name, null); } }
33.241667
221
0.72374
f5f7c0d5df698e5d0bb0c38c41dd465a72440acb
6,116
package com.example.d_learn; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.AnimationDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; public class signup2 extends AppCompatActivity { ImageView back,forward; // TextView signin; String[] depart; Spinner dept; ArrayAdapter<String> aa; EditText email,phone; int index; private RelativeLayout constraintLayout; private AnimationDrawable animationDrawable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS ); setContentView(R.layout.activity_signup2); getSupportActionBar().hide(); if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) { setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true); } if (Build.VERSION.SDK_INT >= 19) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } //make fully Android Transparent Status bar if (Build.VERSION.SDK_INT >= 21) { setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false); getWindow().setStatusBarColor(Color.TRANSPARENT); } final String fname=getIntent().getStringExtra("fname"); final String lname=getIntent().getStringExtra("lname"); final String dob=getIntent().getStringExtra("dob"); final String genderindex=getIntent().getStringExtra("genderindex"); email=findViewById(R.id.editText11); phone=findViewById(R.id.editText10); back=findViewById(R.id.imageView9); forward=findViewById(R.id.imageView10); dept=findViewById(R.id.spinner3); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); depart=getResources().getStringArray(R.array.departments); aa=new ArrayAdapter<String>(this, R.layout.spinner_xml,depart); aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); dept.setAdapter(aa); dept.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub index = arg0.getSelectedItemPosition(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // init constraintLayout constraintLayout = (RelativeLayout) findViewById(R.id.constraintlayout); // initializing animation drawable by getting background from constraint layout animationDrawable = (AnimationDrawable) constraintLayout.getBackground(); // setting enter fade animation duration to 5 seconds animationDrawable.setEnterFadeDuration(2500); // setting exit fade animation duration to 2 seconds animationDrawable.setExitFadeDuration(2500); forward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if ((email.getText().toString().equals("")) || (phone.getText().toString().equals("")) || (index == 0)) Toast.makeText(signup2.this, "Enter valid data", Toast.LENGTH_SHORT).show(); if(!email.getText().toString().contains("@")||!email.getText().toString().contains(".com")) { Toast.makeText(signup2.this, "Enter valid email", Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(getApplicationContext(), signup3.class); i.putExtra("fname",fname); i.putExtra("lname",lname); i.putExtra("dob",dob); i.putExtra("email",email.getText().toString()); i.putExtra("phone",phone.getText().toString()); i.putExtra("deptindex",String.valueOf(index)); i.putExtra("genderindex",genderindex); startActivity(i); } } }); } protected void onResume() { super.onResume(); if (animationDrawable != null && !animationDrawable.isRunning()) { // start the animation animationDrawable.start(); } } // @Override protected void onPause() { super.onPause(); if (animationDrawable != null && animationDrawable.isRunning()) { // stop the animation animationDrawable.stop(); } } public static void setWindowFlag(Activity activity, final int bits, boolean on) { Window win = activity.getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } }
34.359551
150
0.631622
4602fbab8222baf3436a12667ea15871b0fc0037
651
package com.hanhan.controller.employee; import com.hanhan.bean.Employee; import com.hanhan.service.employee.EmployeeService; 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.ResponseBody; import java.util.List; @Controller @RequestMapping("employee") public class EmployeeController { @Autowired EmployeeService employeeService; @RequestMapping("get_data") @ResponseBody public List<Employee> getData(){ return employeeService.getData(); } }
28.304348
62
0.795699
aea202786851a56607976c2cac8fad691c595022
2,499
package org.schors.merch.controllers; import lombok.SneakyThrows; import org.schors.merch.Storage; import org.schors.merch.data.Child; import org.schors.merch.data.Gender; import org.slyrack.telegrambots.ModelAndView; import org.slyrack.telegrambots.StatefulModelAndView; import org.slyrack.telegrambots.annotations.Command; import org.slyrack.telegrambots.annotations.Controller; import org.slyrack.telegrambots.annotations.HasText; import org.slyrack.telegrambots.annotations.SessionAtr; import org.slyrack.telegrambots.flags.TextTarget; import org.slyrack.telegrambots.flags.UpdateType; import org.slyrack.telegrambots.session.Session; import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.bots.AbsSender; @Controller public class ChildController { private final Storage storage; public ChildController(Storage storage) { this.storage = storage; } @Command(value = UpdateType.MESSAGE) @HasText(textTarget = TextTarget.MESSAGE_TEXT, equals = "/add") public ModelAndView addChild(Session session, @SessionAtr("user") User user) { Child child = new Child(); child.setUsername(user.getUserName()); session.setAttribute("child", child); return new StatefulModelAndView("add-power", "add-child"); } @Command(value = UpdateType.MESSAGE, state = "add-power") public ModelAndView addPower(@SessionAtr("child") Child child, final Update update) { child.setPower(Integer.parseInt(update.getMessage().getText())); return new StatefulModelAndView("add-gender", "add-gender"); } @SneakyThrows @Command(value = UpdateType.CALLBACK_QUERY, state = "add-gender") public ModelAndView addGender(final AbsSender absSender, @SessionAtr("child") Child child, @SessionAtr("user") User user, final Update update) { absSender.execute(AnswerCallbackQuery.builder() .callbackQueryId(update.getCallbackQuery().getId()) .build()); child.setGender(Gender.valueOf(update.getCallbackQuery().getData())); storage.addPlayerChild(user.getUserName(), child); return new StatefulModelAndView("main", "show-children"); } }
42.355932
96
0.697879
ab5bbb4a7a66a5f2688c558706ce4bd6769444b3
1,690
package com.personal.oyl.event.sample.order; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * @author OuYang Liang */ public class Order { private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); private Long id; private Long userId; private Date orderTime; private Integer orderAmount; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Date getOrderTime() { return null == orderTime ? null : (Date) orderTime.clone(); } public void setOrderTime(Date orderTime) { this.orderTime = (null == orderTime ? null : (Date) orderTime.clone()); } public Integer getOrderAmount() { return orderAmount; } public void setOrderAmount(Integer orderAmount) { this.orderAmount = orderAmount; } public String json() { return gson.toJson(this); } public static Order fromJson(String json) { return gson.fromJson(json, Order.class); } public static void main(String[] args) { Order order = new Order(); order.setId(1l); order.setUserId(21l); order.setOrderTime(new Date()); order.setOrderAmount(100); String json = order.json(); Order order2 = Order.fromJson(json); String json2 = order2.json(); System.out.println(json); System.out.println(json2); } }
22.236842
101
0.597633
3fabbec9b143eceab9af24f7f44e5a0645592a96
2,001
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.sql.Date; import java.util.Set; /* * 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. */ /** * * @author luckyjustin */ public class Dates { private static Connection connection; private static PreparedStatement getDatesQuery; private static ResultSet result; public static ArrayList<Date> getAllDates() { connection = DBConnection.getConnection(); ArrayList<Date> dates = new ArrayList<>(); try { getDatesQuery = connection.prepareStatement("select date from dates order by date"); result = getDatesQuery.executeQuery(); while(result.next()) { dates.add(result.getDate(1)); } } catch(SQLException sqlException) { sqlException.printStackTrace(); } return dates; } // public static void addDate() { // // } public static void main(String[] argv) { ArrayList<Date> res = Dates.getAllDates(); Set<String> set = ReservationQueries.getRoomsReservedByDate(res.get(0)); // ArrayList<RoomEntry> rooms= RoomQueries.getAllPossibleRooms(); // System.out.println(res); // System.out.println(set); // for (RoomEntry room : rooms) { // System.out.println(room.getName()); // System.out.println(room.getSeats()); // } // ReservationQueries.addReservationEntry("Iggy", res.get(1), 12); ArrayList<WaitlistEntry> waitlist = WaitlistQueries.getAllWaitList(); for (WaitlistEntry entry : waitlist) { System.out.println(entry.getFaculty() + entry.getDate() + entry.getSeats() + entry.getTimestamp()); } } }
31.761905
111
0.630185
b06896427f473521e948ad1b7308150ab9422236
1,632
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.plsql.ast; import org.apache.commons.io.IOUtils; import org.junit.Test; import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst; public class WhereClauseTest extends AbstractPLSQLParserTst { @Test public void testFunctionCall() throws Exception { String code = IOUtils.toString(this.getClass().getResourceAsStream("WhereClauseFunctionCall.pls")); ASTInput input = parsePLSQL(code); } @Test public void testLikeCondition() throws Exception { String code = IOUtils.toString(this.getClass().getResourceAsStream("WhereClauseLike.pls")); ASTInput input = parsePLSQL(code); } @Test public void testNullCondition() throws Exception { String code = IOUtils.toString(this.getClass().getResourceAsStream("WhereClauseIsNull.pls")); ASTInput input = parsePLSQL(code); } @Test public void testBetweenCondition() throws Exception { String code = IOUtils.toString(this.getClass().getResourceAsStream("WhereClauseBetween.pls")); ASTInput input = parsePLSQL(code); } @Test public void testInCondition() throws Exception { String code = IOUtils.toString(this.getClass().getResourceAsStream("WhereClauseIn.pls")); ASTInput input = parsePLSQL(code); } @Test public void testIsOfTypeCondition() throws Exception { String code = IOUtils.toString(this.getClass().getResourceAsStream("WhereClauseIsOfType.pls")); ASTInput input = parsePLSQL(code); } }
32.64
107
0.708333
82cbd3496ee6f8a7b79b0c2da5b81394ec1231c0
559
package core.aws.task.s3; import core.aws.env.Context; import core.aws.resource.s3.Bucket; import core.aws.workflow.Action; import core.aws.workflow.Task; /** * @author neo */ @Action("desc-s3") public class DescribeBucketTask extends Task<Bucket> { public DescribeBucketTask(Bucket bucket) { super(bucket); } @Override public void execute(Context context) throws Exception { String key = "s3/" + resource.id; context.output(key, String.format("status=%s, bucketName=%s", resource.status, resource.name)); } }
24.304348
103
0.68873
f07535770a0833e0f3720d539150135c20e3dad5
1,515
package org.baeldung.springcassandra.model; import org.springframework.data.cassandra.core.mapping.PrimaryKey; import org.springframework.data.cassandra.core.mapping.Table; import java.util.Objects; import java.util.UUID; @Table public class Car { @PrimaryKey private UUID id; private String make; private String model; private int year; public Car(UUID id, String make, String model, int year) { this.id = id; this.make = make; this.model = model; this.year = year; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Car car = (Car) o; return year == car.year && Objects.equals(id, car.id) && Objects.equals(make, car.make) && Objects.equals(model, car.model); } @Override public int hashCode() { return Objects.hash(id, make, model, year); } }
19.423077
132
0.570297
e8944e074b994d65234a18eb1c5ef722af4e8609
6,643
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.graalvm.vm.posix.api.linux; import java.io.IOException; import java.lang.management.ManagementFactory; import java.nio.file.Files; import java.nio.file.Paths; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.graalvm.vm.posix.api.Errno; import org.graalvm.vm.posix.api.Posix; import org.graalvm.vm.posix.api.PosixException; import org.graalvm.vm.posix.api.PosixPointer; public class Linux { private final Futex futex = new Futex(); private static final ThreadLocal<PosixPointer> clear_child_tid = new ThreadLocal<>(); private static final ThreadLocal<PosixPointer> robust_list = new ThreadLocal<>(); private static final SecureRandom rng = new SecureRandom(); static class Line { public final String name; public final long value; Line(String line) { String[] tmp = line.split(":"); long scale = 1024; name = tmp[0].trim(); tmp = tmp[1].trim().split(" "); value = Long.parseLong(tmp[0].trim()) * scale; if (tmp.length > 1 && !tmp[1].trim().equals("kB")) { throw new AssertionError("unknown unit"); } } String name() { return name; } long value() { return value; } } public int sysinfo(Sysinfo info) throws PosixException { if (info == null) { throw new PosixException(Errno.EFAULT); } try { String uptime = new String(Files.readAllBytes(Paths.get("/proc/uptime"))); info.uptime = Long.parseUnsignedLong(uptime.substring(0, uptime.indexOf('.'))); } catch (IOException e) { info.uptime = ManagementFactory.getRuntimeMXBean().getUptime(); } info.loads = new long[3]; String loadavg; try { loadavg = new String(Files.readAllBytes(Paths.get("/proc/loadavg"))); } catch (IOException e) { loadavg = "0.00 0.00 0.00 0/0 0"; } String[] parts = loadavg.split(" "); info.loads[0] = Sysinfo.load(parts[0]); info.loads[1] = Sysinfo.load(parts[1]); info.loads[2] = Sysinfo.load(parts[2]); info.procs = (short) Integer.parseInt(parts[3].split("/")[1]); info.totalhigh = 0; info.freehigh = 0; info.mem_unit = 1; Map<String, Long> memory; try { memory = Files.readAllLines(Paths.get("/proc/meminfo")).stream().map(Line::new).collect(Collectors.toMap(Line::name, Line::value)); } catch (IOException e) { memory = new HashMap<>(); memory.put("MemTotal", 0L); memory.put("MemFree", 0L); memory.put("MemAvailable", 0L); memory.put("Buffers", 0L); memory.put("Cached", 0L); memory.put("SwapTotal", 0L); memory.put("SwapFree", 0L); memory.put("Shmem", 0L); } info.totalram = memory.get("MemTotal"); info.freeram = memory.get("MemFree"); info.sharedram = memory.get("Shmem"); info.bufferram = memory.get("Buffers"); info.totalswap = memory.get("SwapTotal"); info.freeswap = memory.get("SwapFree"); return 0; } public int futex(PosixPointer uaddr, int futex_op, int val, PosixPointer timeout, PosixPointer uaddr2, int val3) throws PosixException { return futex.futex(uaddr, futex_op, val, timeout, uaddr2, val3); } public PosixPointer getClearChildTid() { return clear_child_tid.get(); } public long set_tid_address(PosixPointer tidptr) { clear_child_tid.set(tidptr); return Posix.getTid(); } public long set_robust_list(PosixPointer head, long len) throws PosixException { if (len != 24) { throw new PosixException(Errno.EINVAL); } robust_list.set(head); return 0; } public long getrandom(PosixPointer buf, long buflen, int flags) throws PosixException { if ((flags & ~(Random.GRND_NONBLOCK | Random.GRND_RANDOM)) != 0) { throw new PosixException(Errno.EINVAL); } PosixPointer ptr = buf; int i; for (i = 0; i < buflen - 8; i += 8) { ptr.setI64(rng.nextLong()); ptr = ptr.add(8); } byte[] b = new byte[1]; for (; i < buflen; i++) { rng.nextBytes(b); ptr.setI8(b[0]); ptr = ptr.add(1); } return buflen; } }
36.300546
143
0.63089
a81817f34bccf40ad635e912e7a4e7d70a4f113e
1,006
package com.biykcode.lesson8.controller; import com.biykcode.lesson8.entity.Person; import com.biykcode.lesson8.service.CacheService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class CacheController { @Autowired private CacheService cacheService; @GetMapping("/put") public Person put(@RequestParam("name") String name, @RequestParam("address") String address, @RequestParam("age") Integer age) { return cacheService.save(new Person(null, name, age, address)); } @GetMapping("/cacheable") public Person cacheable(@RequestParam("id") Long id) { return cacheService.findOne(id); } @GetMapping("/evit") public String evit(@RequestParam("id") Long id) { cacheService.remove(id); return "success"; } }
30.484848
133
0.733598
077c720f2b4ab215a311659c8b9b08e12cbd1bb2
1,430
package com.smt.kata.code; /**************************************************************************** * <b>Title</b>: PolybiusSquare.java * <b>Project</b>: SMT-Kata * <b>Description: </b> The Polybius Square cipher is a simple substitution cipher * that makes use of a 5x5 square grid. The letters A-Z are written into the grid, * with "I" and "J" typically sharing a slot (as there are 26 letters and only 25 slots). 1 2 3 4 5 1 A B C D E 2 F G H I/J K 3 L M N O P 4 Q R S T U 5 V W X Y Z * To encipher a message, each letter is merely replaced by its row and column numbers in the grid. * Create a function that takes a plaintext or ciphertext message, and returns the corresponding ciphertext or plaintext. * As "I" and "J" share a slot, both are enciphered into 24, but deciphered only into "I" (see third and fourth test). * <b>Copyright:</b> Copyright (c) 2021 * <b>Company:</b> Silicon Mountain Technologies * * @author James Camire * @version 3.0 * @since Jan 5, 2021 * @updates: ****************************************************************************/ public class PolybiusSquare { /** * Encodes a sentence into its polybius values * @param term * @return */ public String polybiusEncode(String term){ return term; } /** * Decodes the polybius back to a string * @param code * @return */ public String decodeValue(String code){ return code; } }
29.183673
121
0.604196
3619920a5d4399a1dec4a7ca743fcf04b5bd6c7f
10,818
/******************************************************************************* * Copyright 2013 Ednovo d/b/a Gooru. All rights reserved. * * http://www.goorulearning.org/ * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ package org.ednovo.gooru.client.mvp.player; import java.util.Date; import org.ednovo.gooru.client.PlaceTokens; import org.ednovo.gooru.client.gin.AppClientFactory; import org.ednovo.gooru.client.gin.BasePopupViewWithHandlers; import org.ednovo.gooru.client.mvp.search.event.SetHeaderEvent; import org.ednovo.gooru.client.mvp.search.event.UpdateSearchResultMetaDataEvent; import org.ednovo.gooru.client.mvp.shelf.event.RefreshUserShelfCollectionsEvent; import org.ednovo.gooru.client.mvp.socialshare.SocialShareView; import org.ednovo.gooru.client.uc.AlertContentUc; import org.ednovo.gooru.client.uc.BrowserAgent; import org.ednovo.gooru.client.uc.ShareViewUc; import org.ednovo.gooru.shared.model.social.SocialShareDo; import org.ednovo.gooru.shared.model.user.UserDo; import org.ednovo.gooru.shared.util.MessageProperties; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.proxy.PlaceRequest; /** * @author Search Team * */ public class CollectionPlayView extends BasePopupViewWithHandlers<CollectionPlayUiHandlers> implements IsCollectionPlayView,MessageProperties { //private CollectionOverviewPopupImpl gooruCollectionPlayer; private CollectionPlayWidget gooruCollectionPlayer; ShareViewUc shareContainer; HTMLPanel ftmPanel; Document doc = Document.get(); private static final String OOPS = GL0061; String reloadUrl = null; private PlaceRequest previousRequest = null; long nowLong; Date now; boolean isIncrementedCollection; private String gooruOid; String countview=null; String contentid=null; boolean updateview=false; HandlerRegistration playerCloseHandler; /** * Class constructor , Assign styles for overview popup * * @param eventBus * {@link EventBus} */ @Inject public CollectionPlayView(EventBus eventBus) { super(eventBus); isIncrementedCollection=false; now = new Date(); nowLong = now.getTime(); nowLong = nowLong + (1000 * 60 * 60 * 4); /*nowLong = nowLong + (1000 * 60 * 30);*/ now.setTime(nowLong); //gooruCollectionPlayer = new CollectionOverviewPopupImpl(); shareContainer=new ShareViewUc("", ""); ftmPanel=new HTMLPanel(""); gooruCollectionPlayer = new CollectionPlayWidget(); gooruCollectionPlayer.setGlassEnabled(true); // gooruCollectionPlayer.getElement().setAttribute("style", "min-height:100%; min-width:100%;"); gooruCollectionPlayer.getElement().getStyle().setZIndex(99999); String device = BrowserAgent.returnFormFactorView(); if (device.equalsIgnoreCase("desktop")){ gooruCollectionPlayer.getElement().getStyle().setWidth(100, Unit.PCT); gooruCollectionPlayer.getElement().getStyle().setHeight(100, Unit.PCT); }else{ gooruCollectionPlayer.getElement().getStyle().setWidth(1200, Unit.PX); gooruCollectionPlayer.getElement().getStyle().setHeight(755, Unit.PX); } setAutoHideOnNavigationEventEnabled(true); gooruCollectionPlayer.getAddNewCollectionLabel().addClickHandler(new OnNewCollectionClick()); //reloadUrl = Window.Location.getHref(); try{ doc.getElementById("headerMainPanel").getStyle().setZIndex(0); doc.getElementById("goToClasicInnerPanel").getStyle().setZIndex(0); }catch(Exception e){ } } @Override public void updateViewCount(String count, String contentId, String whatToUpdate) { if(count!=null||count!=""){ updateview=true; this.countview=count; this.contentid=contentId; } } @Override public void setData(final String gooruOid, String token,boolean isEmbededCollection,boolean isShared) { isIncrementedCollection=true; this.gooruOid = gooruOid; hideFromPopup(false); doc.getElementById("uvTab").getStyle().setDisplay(Display.NONE); EventBus bus=AppClientFactory.getEventBus(); try{ doc.getElementById("headerMainPanel").getStyle().setZIndex(0); doc.getElementById("goToClasicInnerPanel").getStyle().setZIndex(0); }catch(Exception e){ } String loggedInGooruUserId=AppClientFactory.isAnonymous()?"ANONYMOUS":AppClientFactory.loggedInUser.getGooruUId(); gooruCollectionPlayer.setData(gooruOid, token, getSettings() .getRestEndPoint(),getSettings().getDocViewerPoint(), AppClientFactory.isAnonymous(), AppClientFactory .getLoggedInUser().getSettings().getHomeEndPoint() + "/",getSettings().getApiKeyPoint(),bus,isEmbededCollection,loggedInGooruUserId,isShared); gooruCollectionPlayer.isUserLoggedIn(AppClientFactory.isAnonymous(),loggedInGooruUserId, AppClientFactory.getLoggedInUser().getEmailId(), AppClientFactory.getLoggedInUser().getUsername()); if(playerCloseHandler!=null) { playerCloseHandler.removeHandler(); } playerCloseHandler = gooruCollectionPlayer.getCollectionPlayerCloseButton().addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent e) { gooruCollectionPlayer.stopCloseButtonDataLogEvents(); if(updateview){ if(countview!=null||countview!=""){ try{ AppClientFactory.fireEvent(new UpdateSearchResultMetaDataEvent(countview, contentid, "views")); } catch(NumberFormatException ex){ } catch(Exception exc){ } } updateview=false; } try{ Element ifrmaeElement=Document.get().getElementById("collectionWebresourceContainer"); if(ifrmaeElement!=null){ ifrmaeElement.setAttribute("src", ""); } }catch(Exception exception){ } hideFromPopup(true); hide(); try{ doc.getElementById("headerMainPanel").getStyle().clearZIndex(); doc.getElementById("goToClasicInnerPanel").getStyle().clearZIndex(); }catch(Exception ex){ } doc.getElementById("uvTab").getStyle() .setDisplay(Display.BLOCK); if (AppClientFactory.isAnonymous() && gooruCollectionPlayer.getUserDo() != null) { if (AppClientFactory.isAnonymous() && gooruCollectionPlayer.getUserDo().getUsername() != null && gooruCollectionPlayer.getUserDo().getPassword() != null) { AppClientFactory.getInjector().getAppService().signin(gooruCollectionPlayer.getUserDo().getEmailId(),gooruCollectionPlayer.getUserDo().getPassword(),new AsyncCallback<UserDo>() { @Override public void onSuccess(UserDo result) { AppClientFactory.setLoggedInUser(result); // refresh page AppClientFactory.fireEvent(new SetHeaderEvent(result)); //redirect(reloadUrl); AppClientFactory.fireEvent(new RefreshUserShelfCollectionsEvent()); } @Override public void onFailure( Throwable caught) { new AlertContentUc(OOPS,caught.getMessage()); } }); } } if (gooruCollectionPlayer.getIsResourceOrCollectionAdded()) { //redirect(reloadUrl); AppClientFactory.fireEvent(new RefreshUserShelfCollectionsEvent()); } // //AppClientFactory.fireEvent(new GetSearchKeyWordEvent()); // } }); reloadUrl = Window.Location.getHref(); } @Override public void setMobileData(String gooruOid, String token) { } @Override public Widget asWidget() { return gooruCollectionPlayer; } @Override protected String getDefaultView() { return PlaceTokens.HOME; } native void redirect(String url) /*-{ $wnd.location = url; $wnd.location.reload(); }-*/; @Override public void setUserLoginDetails(String sessionToken,String gooruUserId) { gooruCollectionPlayer.setSession(sessionToken); gooruCollectionPlayer.isUserLoggedIn(false,gooruUserId, AppClientFactory.getLoggedInUser().getEmailId(), AppClientFactory.getLoggedInUser().getUsername()); gooruCollectionPlayer.showCollectionLikesDisLikes(); } private class OnNewCollectionClick implements ClickHandler{ @Override public void onClick(ClickEvent event) { getUiHandlers().displayNewCollectionPopupView(event.getRelativeElement().getAttribute("resourceId")); } } @Override public void refreshShelfCollectionInPlay(String collectionId) { gooruCollectionPlayer.showResourceAddedSuccessMessage(collectionId); gooruCollectionPlayer.refreshShelfCollectionList(); } public void ftmWidget(Widget w) { shareContainer.add(w); } @Override public void addShareWidgetInPlay(String link,String rawUrl, String title, String desc, String shortenUrl, String type, String shareType) { SocialShareDo shareDo = new SocialShareDo(); shareDo.setBitlylink(link); shareDo.setRawUrl(rawUrl); shareDo.setTitle(title); shareDo.setDescription(desc); shareDo.setThumbnailurl(shortenUrl); shareDo.setCategoryType(type); shareDo.setOnlyIcon(false); shareDo.setShareType(shareType); shareDo.setDecodeRawUrl(link); SocialShareView socialView=new SocialShareView(shareDo); gooruCollectionPlayer.setFTMWidget(socialView); } }
35.821192
190
0.728046
0003ac62145626b6ba213321e5ae8151dac425e0
1,903
package com.adam.test; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author adam * contact: luminghi@hotmail.com * date: 2021/1/8 14:29 * version: 1.0.0 */ public class Q500 { public static void main(String[] args) { String[] words = new String[]{"qz", "wq", "asdddafadsfa", "adfadfadfdassfawde"}; Solution solution = new Solution(); String[] result = solution.findWords(words); for (String str : result) { System.out.println(str); } } static class Solution { public String[] findWords(String[] words) { String s1 = "qwertyuiopQWERTYUIOP"; String s2 = "asdfghjklASDFGHJKL"; String s3 = "zxcvbnmZXCVBNM"; List<String> list = new ArrayList<>(); for (String str : words) { boolean bool1 = false; boolean bool2 = false; boolean bool3 = false; boolean bool = true; for (char c : str.toCharArray()) { if (bool1 && bool2 || bool2 && bool3 || bool1 && bool3) { bool = false; break; } if (s1.indexOf(c) != -1) { bool1 = true; } if (s2.indexOf(c) != -1) { bool2 = true; } if (s3.indexOf(c) != -1) { bool3 = true; } } if (bool1 && bool2 || bool2 && bool3 || bool1 && bool3) { bool = false; } if (bool) { list.add(str); } } return list.toArray(new String[0]); } } }
31.716667
89
0.413032
146507622a5fd72678f47fbc9627e4f84b0f3309
370
package cn.afterturn.gen.core.util; import cn.afterturn.gen.config.properties.GunsProperties; /** * 验证码工具类 */ public class KaptchaUtil { /** * 获取验证码开关 * * @author stylefeng * @Date 2017/5/23 22:34 */ public static Boolean getKaptchaOnOff() { return SpringContextHolder.getBean(GunsProperties.class).getKaptchaOpen(); } }
19.473684
82
0.656757
6bd4a8c6bc35e8267c31cebacc9f9255da8e7b91
9,372
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tw.go.plugin; import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.request.GoApiRequest; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.GoApiResponse; import com.tw.go.plugin.util.JSONUtils; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.*; public class EmailNotificationPluginImplUnitTest { @Mock private GoApplicationAccessor goApplicationAccessor; @Mock private SessionWrapper mockSession; @Mock private Transport mockTransport; @Mock private SessionFactory mockSessionFactory; private Map<String, Object> settingsResponseMap; private Map<String, Object> stateChangeResponseMap; private EmailNotificationPluginImpl emailNotificationPlugin; @Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); when(mockSession.getTransport()).thenReturn(mockTransport); when(mockSessionFactory.getInstance(any(Properties.class))).thenReturn(mockSession); when(mockSessionFactory.getInstance(any(Properties.class), any(Authenticator.class))).thenReturn(mockSession); emailNotificationPlugin = new EmailNotificationPluginImpl(); emailNotificationPlugin.initializeGoApplicationAccessor(goApplicationAccessor); emailNotificationPlugin.setSessionFactory(mockSessionFactory); } @Before public void setupDefaultSettingResponse() { settingsResponseMap = new HashMap<>(); settingsResponseMap.put("smtp_host", "test-smtp-host"); settingsResponseMap.put("smtp_port", "25"); settingsResponseMap.put("is_tls", "0"); settingsResponseMap.put("sender_email_id", "test-smtp-sender"); settingsResponseMap.put("sender_password", "test-smtp-password"); settingsResponseMap.put("smtp_username", "test-smtp-username"); settingsResponseMap.put("receiver_email_id", "test-smtp-receiver"); } @Before public void setupDefaultStateChangeResponseMap() { Map<String, Object> stageResponseMap = new HashMap<>(); stageResponseMap.put("name", "test-stage-name"); stageResponseMap.put("counter", "test-counter"); stageResponseMap.put("state", "test-state"); stageResponseMap.put("result", "test-result"); stageResponseMap.put("last-transition-time", "test-last-transition-time"); stageResponseMap.put("create-time", "test-last-transition-time"); Map<String, Object> pipelineMap = new HashMap<>(); pipelineMap.put("stage", stageResponseMap); pipelineMap.put("name", "test-pipeline-name"); pipelineMap.put("counter", "test-pipeline-counter"); stateChangeResponseMap = new HashMap<>(); stateChangeResponseMap.put("pipeline", pipelineMap); } @Test public void testStageNotificationRequestsSettings() { GoApiResponse settingsResponse = testSettingsResponse(); when(goApplicationAccessor.submit(eq(testSettingsRequest()))).thenReturn(settingsResponse); GoPluginApiRequest requestFromServer = testStageChangeRequestFromServer(); emailNotificationPlugin.handle(requestFromServer); final ArgumentCaptor<GoApiRequest> settingsRequestCaptor = ArgumentCaptor.forClass(GoApiRequest.class); verify(goApplicationAccessor).submit(settingsRequestCaptor.capture()); final GoApiRequest actualSettingsRequest = settingsRequestCaptor.getValue(); assertEquals(testSettingsRequest().api(), actualSettingsRequest.api()); assertEquals(testSettingsRequest().apiVersion(), actualSettingsRequest.apiVersion()); GoPluginIdentifier actualGoPluginIdentifier = actualSettingsRequest.pluginIdentifier(); assertNotNull(actualGoPluginIdentifier); assertEquals(testSettingsRequest().pluginIdentifier().getExtension(), actualGoPluginIdentifier.getExtension()); assertEquals(testSettingsRequest().pluginIdentifier().getSupportedExtensionVersions(), actualGoPluginIdentifier.getSupportedExtensionVersions()); assertEquals(testSettingsRequest().requestBody(), actualSettingsRequest.requestBody()); assertEquals(testSettingsRequest().requestHeaders(), actualSettingsRequest.requestHeaders()); assertEquals(testSettingsRequest().requestParameters(), actualSettingsRequest.requestParameters()); } @Test public void testASingleEmailAddressSendsEmail() throws Exception { settingsResponseMap.put("receiver_email_id", "test-email@test.co.uk"); GoApiResponse settingsResponse = testSettingsResponse(); when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse); doCallRealMethod().when(mockSession).createMessage(anyString(), anyString(), anyString(), anyString()); GoPluginApiRequest requestFromServer = testStageChangeRequestFromServer(); emailNotificationPlugin.handle(requestFromServer); verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("test-email@test.co.uk")})); verify(mockTransport, times(1)).connect(eq("test-smtp-host"), eq(25), eq("test-smtp-username"), eq("test-smtp-password")); verify(mockTransport, times(1)).close(); verifyNoMoreInteractions(mockTransport); } @Test public void testMultipleEmailAddressSendsEmail() throws Exception { settingsResponseMap.put("receiver_email_id", "test-email@test.co.uk, test-email-2@test.co.uk"); GoApiResponse settingsResponse = testSettingsResponse(); when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse); doCallRealMethod().when(mockSession).createMessage(anyString(), anyString(), anyString(), anyString()); GoPluginApiRequest requestFromServer = testStageChangeRequestFromServer(); emailNotificationPlugin.handle(requestFromServer); verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("test-email@test.co.uk")})); verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("test-email-2@test.co.uk")})); verify(mockTransport, times(2)).connect(eq("test-smtp-host"), eq(25), eq("test-smtp-username"), eq("test-smtp-password")); verify(mockTransport, times(2)).close(); verifyNoMoreInteractions(mockTransport); } private GoPluginApiRequest testStageChangeRequestFromServer() { GoPluginApiRequest requestFromGoServer = mock(GoPluginApiRequest.class); when(requestFromGoServer.requestName()).thenReturn("stage-status"); when(requestFromGoServer.requestBody()).thenReturn(JSONUtils.toJSON(stateChangeResponseMap)); return requestFromGoServer; } private static GoApiRequest testSettingsRequest() { final Map<String, Object> requestMap = new HashMap<>(); requestMap.put("plugin-id", "email.notifier"); final String responseBody = JSONUtils.toJSON(requestMap); return new GoApiRequest() { @Override public String api() { return "go.processor.plugin-settings.get"; } @Override public String apiVersion() { return "1.0"; } @Override public GoPluginIdentifier pluginIdentifier() { return new GoPluginIdentifier("notification", Collections.singletonList("1.0")); } @Override public Map<String, String> requestParameters() { return null; } @Override public Map<String, String> requestHeaders() { return null; } @Override public String requestBody() { return responseBody; } }; } private GoApiResponse testSettingsResponse() { GoApiResponse settingsResponse = mock(GoApiResponse.class); when(settingsResponse.responseBody()).thenReturn(JSONUtils.toJSON(settingsResponseMap)); return settingsResponse; } }
38.253061
153
0.714895
2a63c430d936837d21aceee2a65e59f3fe51c1ac
1,002
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement.generated; import com.azure.core.util.Context; /** Samples for ApiManagementService GetDomainOwnershipIdentifier. */ public final class ApiManagementServiceGetDomainOwnershipIdentifierSamples { /* * x-ms-original-file: specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementServiceGetDomainOwnershipIdentifier.json */ /** * Sample code: ApiManagementServiceGetDomainOwnershipIdentifier. * * @param manager Entry point to ApiManagementManager. */ public static void apiManagementServiceGetDomainOwnershipIdentifier( com.azure.resourcemanager.apimanagement.ApiManagementManager manager) { manager.apiManagementServices().getDomainOwnershipIdentifierWithResponse(Context.NONE); } }
41.75
176
0.787425
7bbeb66fcd40e5fbbab26787caca5a625bea3db4
2,183
package com.projecta.mondrianserver.mondrian; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; import java.util.WeakHashMap; import org.olap4j.OlapConnection; /** * Dynamic proxy for connections to prevent cacheing of connections by Saiku */ public class ConnectionProxy implements InvocationHandler { private OlapConnection connection; private static Map<ConnectionProxy, Boolean> instances = new WeakHashMap<ConnectionProxy, Boolean>(); private ConnectionProxy() { } /** * Creates a new dynamic proxy instance for olap connections */ public static OlapConnection getProxyInstance() { ConnectionProxy proxy = new ConnectionProxy(); synchronized (ConnectionProxy.class) { instances.put(proxy, true); } return (OlapConnection) Proxy.newProxyInstance( OlapConnection.class.getClassLoader(), new Class[] { OlapConnection.class }, proxy); } /** * Whenever a method on the proxy is called, we dynamically create a new * connection, or use the existing one. */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { OlapConnection con = null; synchronized (this) { if (connection == null) { connection = MondrianConnector.getOlapConnection(); } con = connection; } return method.invoke(con, args); } /** * Closes all outstanding connections for every proxy instance */ public static synchronized void closeAllConnections() { for (ConnectionProxy proxy : instances.keySet()) { if (proxy != null) { synchronized (proxy) { try { if (proxy.connection != null) { proxy.connection.close(); } } catch (Throwable e) { } proxy.connection = null; } } } } }
26.301205
105
0.585891
18ea2915f26321abb584a6b3e0d99c9e1e493e50
788
package org.yxs.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.yxs.config.propertiey.BlogProperties1; @SpringBootApplication @EnableConfigurationProperties({BlogProperties1.class}) public class ConfigApplication { public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); // SpringApplication application = new SpringApplication(ConfigApplication.class); // 关闭banner // application.setBannerMode(Banner.Mode.OFF); //禁止项目的配置被命令行修改 // application.setAddCommandLineProperties(false); // application.run(args); } }
30.307692
89
0.769036
44135a175b38c8c6bab6abcdbe0e5fd9d32017fb
7,305
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/security/privateca/v1/resources.proto package com.google.cloud.security.privateca.v1; public interface CertificateExtensionConstraintsOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.security.privateca.v1.CertificateExtensionConstraints) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Optional. A set of named X.509 extensions. Will be combined with * [additional_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.additional_extensions] to determine the full set of X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.CertificateExtensionConstraints.KnownCertificateExtension known_extensions = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return A list containing the knownExtensions. */ java.util.List< com.google.cloud.security.privateca.v1.CertificateExtensionConstraints .KnownCertificateExtension> getKnownExtensionsList(); /** * * * <pre> * Optional. A set of named X.509 extensions. Will be combined with * [additional_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.additional_extensions] to determine the full set of X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.CertificateExtensionConstraints.KnownCertificateExtension known_extensions = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The count of knownExtensions. */ int getKnownExtensionsCount(); /** * * * <pre> * Optional. A set of named X.509 extensions. Will be combined with * [additional_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.additional_extensions] to determine the full set of X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.CertificateExtensionConstraints.KnownCertificateExtension known_extensions = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the element to return. * @return The knownExtensions at the given index. */ com.google.cloud.security.privateca.v1.CertificateExtensionConstraints.KnownCertificateExtension getKnownExtensions(int index); /** * * * <pre> * Optional. A set of named X.509 extensions. Will be combined with * [additional_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.additional_extensions] to determine the full set of X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.CertificateExtensionConstraints.KnownCertificateExtension known_extensions = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return A list containing the enum numeric values on the wire for knownExtensions. */ java.util.List<java.lang.Integer> getKnownExtensionsValueList(); /** * * * <pre> * Optional. A set of named X.509 extensions. Will be combined with * [additional_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.additional_extensions] to determine the full set of X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.CertificateExtensionConstraints.KnownCertificateExtension known_extensions = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the value to return. * @return The enum numeric value on the wire of knownExtensions at the given index. */ int getKnownExtensionsValue(int index); /** * * * <pre> * Optional. A set of [ObjectIds][google.cloud.security.privateca.v1.ObjectId] identifying custom X.509 extensions. * Will be combined with [known_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.known_extensions] to determine the full set of * X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.ObjectId additional_extensions = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ java.util.List<com.google.cloud.security.privateca.v1.ObjectId> getAdditionalExtensionsList(); /** * * * <pre> * Optional. A set of [ObjectIds][google.cloud.security.privateca.v1.ObjectId] identifying custom X.509 extensions. * Will be combined with [known_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.known_extensions] to determine the full set of * X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.ObjectId additional_extensions = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ com.google.cloud.security.privateca.v1.ObjectId getAdditionalExtensions(int index); /** * * * <pre> * Optional. A set of [ObjectIds][google.cloud.security.privateca.v1.ObjectId] identifying custom X.509 extensions. * Will be combined with [known_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.known_extensions] to determine the full set of * X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.ObjectId additional_extensions = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ int getAdditionalExtensionsCount(); /** * * * <pre> * Optional. A set of [ObjectIds][google.cloud.security.privateca.v1.ObjectId] identifying custom X.509 extensions. * Will be combined with [known_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.known_extensions] to determine the full set of * X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.ObjectId additional_extensions = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ java.util.List<? extends com.google.cloud.security.privateca.v1.ObjectIdOrBuilder> getAdditionalExtensionsOrBuilderList(); /** * * * <pre> * Optional. A set of [ObjectIds][google.cloud.security.privateca.v1.ObjectId] identifying custom X.509 extensions. * Will be combined with [known_extensions][google.cloud.security.privateca.v1.CertificateExtensionConstraints.known_extensions] to determine the full set of * X.509 extensions. * </pre> * * <code> * repeated .google.cloud.security.privateca.v1.ObjectId additional_extensions = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ com.google.cloud.security.privateca.v1.ObjectIdOrBuilder getAdditionalExtensionsOrBuilder( int index); }
40.359116
171
0.727721
b696a1ba19367037eca1de3614c56658acb48422
2,312
package com.interview.leetcode.contests._new_weekely.contest192; import java.util.ArrayList; import java.util.List; public class BrowserHIstory { private int index = 0; private List<String> list = new ArrayList<>(); public BrowserHIstory( String homepage ) { list.add(homepage); } public static void main( String[] args ) { BrowserHIstory browserHistory = new BrowserHIstory("leetcode.com"); browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com" browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com" browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com" System.out.println(browserHistory.back(1)); // You are in "youtube.com", move back to "facebook.com" return "facebook.com" System.out.println(browserHistory.back(1)); // You are in "facebook.com", move back to "google.com" return "google.com" System.out.println(browserHistory.forward(1)); // You are in "google.com", move forward to "facebook.com" return "facebook.com" browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com" browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps. browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com" browserHistory.back(7); } public void visit( String url ) { //THis code will execute when we visit "linkedin.com" //we are at index = 2 = facebook.com //below code removes youtube.com from history, bcz it is forward history /* while (index != list.size() - 1) list.remove(list.size() - 1);*/ //or this code also works.. list.subList(index + 1, list.size()).clear(); list.add(url); index++; } public String back( int steps ) { index = Math.max(index - steps, 0); return list.get(index); } public String forward( int steps ) { index = Math.min(index + steps, list.size() - 1); return list.get(index); } }
37.901639
159
0.609429
27c3c77cff083f9b7bea2bc3c73591b60f67a6d9
138
package com.jk.mvpdemo.mvp2.base; public interface IBasePresenter<V extends IBaseView> { void attach(V view); void detach(); }
15.333333
54
0.710145
c83cd3cdae50dc2fd6bba89cc6b9811efd1f7e75
2,108
package com.example.xcs.xcsdemo.rx.api; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Xcs on 2018-04-02. */ public class NetWork { private static DrunbiApi drunbiApi; private static GankApi gankApi; private static OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder(); private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create(); public static CallAdapter.Factory rxJavaCallAdapterFactory = RxJava2CallAdapterFactory.create(); public static HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); public static DrunbiApi getDrunbiApi(){ if (drunbiApi == null){ httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient.addInterceptor(httpLoggingInterceptor); Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient.build()) .baseUrl("http://www.zhuangbi.info/") .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(rxJavaCallAdapterFactory) .build(); drunbiApi = retrofit.create(DrunbiApi.class); } return drunbiApi; } public static GankApi getGankApi(){ if (gankApi == null) { httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient.addInterceptor(httpLoggingInterceptor); Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient.build()) .baseUrl("http://gank.io/api/") .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(rxJavaCallAdapterFactory) .build(); gankApi = retrofit.create(GankApi.class); } return gankApi; } }
39.773585
100
0.675047
be74e82abb5942b3f3b0de85b679792358968144
1,620
package airMap; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.net.MalformedURLException; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; public class MenuView extends JMenu { private static final long serialVersionUID = 1L; private JPanel parentPanel; // FIXME see if can find a way to not always cast private ActionListener mapView = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JMenuItem item = (JMenuItem) e.getSource(); String view = (String) item.getText(); try { if (parentPanel instanceof NavigationMap) { ((NavigationMap) parentPanel).updateView(view); } else if (parentPanel instanceof CenterMap) { ((CenterMap) parentPanel).updateView(view); } } catch (MalformedURLException e1) { e1.printStackTrace(); } } }; public MenuView(JPanel parentPanel) { setText("View"); setToolTipText("MapPanel View"); Font font = new Font("Arial", Font.PLAIN, 12); setFont(font.deriveFont(14f)); this.parentPanel = parentPanel; String[] viewNames = { "Satellite", "Roadmap", "Hybrid", "Terrain" }; int[] mnemonics = { KeyEvent.VK_S, KeyEvent.VK_R, KeyEvent.VK_H, KeyEvent.VK_T }; JMenuItem[] views = new JMenuItem[viewNames.length]; for (int i = 0; i < views.length; i++) { views[i] = new JMenuItem(viewNames[i]); views[i].setMnemonic(mnemonics[i]); views[i].addActionListener(mapView); views[i].setFont(font); add(views[i]); } addActionListener(mapView); } }
26.129032
83
0.704321
14cff78c566b8b0c950323a69fc55c8eafd1d8fa
8,540
package com.jdit.quizio.activity; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.jdit.quizio.R; import com.jdit.quizio.Constant; import com.jdit.quizio.helper.Session; import com.jdit.quizio.helper.Utils; import com.jdit.quizio.model.Level; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import java.util.ArrayList; import java.util.List; public class LevelActivity extends AppCompatActivity { public Toolbar toolbar; LevelListAdapter adapter; public static String fromQue; private static int levelNo = 1; List<Level> levelList; RecyclerView recyclerView; public TextView tvAlert; public ProgressBar progressBar; public RelativeLayout layout; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_level); layout = findViewById(R.id.layout); toolbar = findViewById(R.id.toolBar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.select_level); getSupportActionBar().setDisplayHomeAsUpEnabled(true); AdView mAdView = findViewById(R.id.banner_AdView); mAdView.loadAd(new AdRequest.Builder().build()); invalidateOptionsMenu(); progressBar = findViewById(R.id.progressBar); recyclerView = findViewById(R.id.recyclerView); tvAlert = findViewById(R.id.tvAlert); recyclerView.setLayoutManager(new LinearLayoutManager(LevelActivity.this)); levelNo = MainActivity.dbHelper.GetLevelById(Constant.CATE_ID, Constant.SUB_CAT_ID); fromQue = getIntent().getStringExtra("fromQue"); levelList = new ArrayList<>(); for (int i = 0; i < Constant.TotalLevel; i++) { Level level = new Level(); level.setLevelNo(levelNo); level.setLevel("" + (i + 1)); levelList.add(level); } if (levelList.size() == 0) { tvAlert.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); } else { getData(); } } private void getData() { if (Utils.isNetworkAvailable(LevelActivity.this)) { adapter = new LevelListAdapter(LevelActivity.this, levelList); recyclerView.setAdapter(adapter); } else { setSnackBar(); } } public void setSnackBar() { Snackbar snackbar = Snackbar .make(layout, getString(R.string.msg_no_internet), Snackbar.LENGTH_INDEFINITE) .setAction(getString(R.string.retry), new View.OnClickListener() { @Override public void onClick(View view) { getData(); } }); snackbar.setActionTextColor(Color.RED); snackbar.show(); } public class LevelListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public Activity activity; private List<Level> levelList; public LevelListAdapter(Activity activity, List<Level> levelList) { this.levelList = levelList; this.activity = activity; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.level_lyt, parent, false); return new LevelViewHolder(view); } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { LevelViewHolder viewHolder = (LevelViewHolder) holder; levelNo = MainActivity.dbHelper.GetLevelById(Constant.CATE_ID, Constant.SUB_CAT_ID); Level level = levelList.get(position); viewHolder.levelNo.setText(getString(R.string.level_txt) + level.getLevel()); if (levelNo >= position + 1) viewHolder.lock.setImageResource(R.drawable.unlock); else viewHolder.lock.setImageResource(R.drawable.lock); if (position >= (levelNo - 1)) { viewHolder.lock.setColorFilter(ContextCompat.getColor(activity, R.color.colorPrimaryDark)); } else { viewHolder.lock.setColorFilter(ContextCompat.getColor(activity, R.color.lock_gray)); viewHolder.levelNo.setTextColor(ContextCompat.getColor(activity, R.color.lock_gray)); } viewHolder.relativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (Session.getSoundEnableDisable(activity)) { Utils.backSoundonclick(activity); } if (Session.getVibration(activity)) { Utils.vibrate(activity, Utils.VIBRATION_DURATION); } Utils.RequestlevelNo = position + 1; if (levelNo >= position + 1) { Intent intent = new Intent(LevelActivity.this, PlayActivity.class); intent.putExtra("fromQue", fromQue); startActivity(intent); } else { Toast.makeText(activity, getString(R.string.level_locked), Toast.LENGTH_SHORT).show(); } } }); } @Override public int getItemCount() { return levelList.size(); } @Override public int getItemViewType(int position) { return position; } public class LevelViewHolder extends RecyclerView.ViewHolder { ImageView lock; RelativeLayout relativeLayout; TextView levelNo; public LevelViewHolder(View itemView) { super(itemView); lock = itemView.findViewById(R.id.lock); levelNo = itemView.findViewById(R.id.level_no); relativeLayout = itemView.findViewById(R.id.relativeLayout); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.bookmark).setVisible(false); menu.findItem(R.id.report).setVisible(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.setting: Utils.CheckVibrateOrSound(LevelActivity.this); Intent playQuiz = new Intent(LevelActivity.this, SettingActivity.class); startActivity(playQuiz); overridePendingTransition(R.anim.open_next, R.anim.close_next); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { super.onResume(); if (adapter != null) { adapter.notifyDataSetChanged(); } } }
35.435685
111
0.609133
bd119947a811e9b6002b6fcde442e7ee6a5a64e1
1,908
/* * 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. * * Copyright 2019-2019 the original author or authors. */ package org.quickperf.junit4; import org.junit.internal.runners.model.ReflectiveCallable; import org.junit.runners.model.FrameworkMethod; import org.quickperf.TestExecutionContext; import org.quickperf.perfrecording.PerformanceRecording; import java.lang.reflect.Method; public class QuickPerfMethod extends FrameworkMethod { private final Method method; private final TestExecutionContext testExecutionContext; private final PerformanceRecording performanceRecording = PerformanceRecording.INSTANCE; public QuickPerfMethod(Method method , TestExecutionContext testExecutionContext) { super(method); this.method = method; this.testExecutionContext = testExecutionContext; } public Object invokeExplosively(final Object target, final Object... params) throws Throwable { return new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { performanceRecording.start(testExecutionContext); try { return method.invoke(target, params); } finally { performanceRecording.stop(testExecutionContext); } } }.run(); } }
35.333333
118
0.698637
f4a1db21182db6e8bd9fc30735bacec172b1db53
432
package com.company.dao.idao; import java.util.List; import com.company.dao.pojo.Emp; public interface EmpDao extends BaseDao<Emp, Integer> { //List<Emp> findByName(String ename) throws Exception; public List<Emp> findEmps(); public boolean saveEmp(Emp e); public boolean delEmp(Integer empno); public boolean updateEmp(Emp e,Integer empno); public Emp jqfindEmp(Integer empno); public List<Emp> mhfindEmp(String ename); }
28.8
55
0.770833
700b2fe82ee72d89f302d5c0d887829ac49279d4
24,534
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.systemtest.utils.kafkaUtils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import io.fabric8.kubernetes.api.model.Pod; import io.strimzi.api.kafka.model.Kafka; import io.strimzi.api.kafka.model.KafkaResources; import io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListener; import io.strimzi.api.kafka.model.status.Condition; import io.strimzi.api.kafka.model.status.KafkaStatus; import io.strimzi.api.kafka.model.status.ListenerStatus; import io.strimzi.kafka.config.model.ConfigModel; import io.strimzi.kafka.config.model.ConfigModels; import io.strimzi.kafka.config.model.Scope; import io.strimzi.systemtest.Constants; import io.strimzi.systemtest.resources.ResourceManager; import io.strimzi.systemtest.resources.ResourceOperation; import io.strimzi.systemtest.resources.crd.KafkaResource; import io.strimzi.systemtest.utils.TestKafkaVersion; import io.strimzi.systemtest.utils.kubeUtils.controllers.DeploymentUtils; import io.strimzi.systemtest.utils.kubeUtils.controllers.StatefulSetUtils; import io.strimzi.test.TestUtils; import io.strimzi.test.k8s.exceptions.KubeClusterException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.time.Duration; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.regex.Pattern; import java.util.stream.Collectors; import static io.strimzi.api.kafka.model.KafkaClusterSpec.FORBIDDEN_PREFIXES; import static io.strimzi.api.kafka.model.KafkaClusterSpec.FORBIDDEN_PREFIX_EXCEPTIONS; import static io.strimzi.api.kafka.model.KafkaResources.kafkaStatefulSetName; import static io.strimzi.api.kafka.model.KafkaResources.zookeeperStatefulSetName; import static io.strimzi.systemtest.enums.CustomResourceStatus.NotReady; import static io.strimzi.systemtest.enums.CustomResourceStatus.Ready; import static io.strimzi.test.TestUtils.indent; import static io.strimzi.test.TestUtils.waitFor; import static io.strimzi.test.k8s.KubeClusterResource.cmdKubeClient; import static io.strimzi.test.k8s.KubeClusterResource.kubeClient; public class KafkaUtils { private static final Logger LOGGER = LogManager.getLogger(KafkaUtils.class); private static final long DELETION_TIMEOUT = ResourceOperation.getTimeoutForResourceDeletion(); private KafkaUtils() {} public static boolean waitForKafkaReady(String namespaceName, String clusterName) { return waitForKafkaStatus(namespaceName, clusterName, Ready); } public static boolean waitForKafkaReady(String clusterName) { return waitForKafkaStatus(kubeClient().getNamespace(), clusterName, Ready); } public static boolean waitForKafkaNotReady(String namespaceName, String clusterName) { return waitForKafkaStatus(namespaceName, clusterName, NotReady); } public static boolean waitForKafkaNotReady(String clusterName) { return waitForKafkaStatus(kubeClient().getNamespace(), clusterName, NotReady); } public static boolean waitForKafkaStatus(String clusterName, Enum<?> state) { return waitForKafkaStatus(kubeClient().getNamespace(), clusterName, state); } public static boolean waitForKafkaStatus(String namespaceName, String clusterName, Enum<?> state) { Kafka kafka = KafkaResource.kafkaClient().inNamespace(namespaceName).withName(clusterName).get(); return ResourceManager.waitForResourceStatus(KafkaResource.kafkaClient(), kafka, state); } /** * Waits for the Kafka Status to be updated after changed. It checks the generation and observed generation to * ensure the status is up to date. * * @param namespaceName Namespace name * @param clusterName Name of the Kafka cluster which should be checked */ public static void waitForKafkaStatusUpdate(String namespaceName, String clusterName) { LOGGER.info("Waiting for Kafka status to be updated"); TestUtils.waitFor("KafkaStatus update", Constants.GLOBAL_POLL_INTERVAL, Constants.GLOBAL_STATUS_TIMEOUT, () -> { Kafka k = KafkaResource.kafkaClient().inNamespace(namespaceName).withName(clusterName).get(); return k.getMetadata().getGeneration() == k.getStatus().getObservedGeneration(); }); } public static void waitForKafkaStatusUpdate(String clusterName) { waitForKafkaStatusUpdate(kubeClient().getNamespace(), clusterName); } public static void waitUntilKafkaStatusConditionContainsMessage(String clusterName, String namespace, String message, long timeout) { TestUtils.waitFor("Kafka Status with message [" + message + "]", Constants.GLOBAL_POLL_INTERVAL, timeout, () -> { List<Condition> conditions = KafkaResource.kafkaClient().inNamespace(namespace).withName(clusterName).get().getStatus().getConditions(); for (Condition condition : conditions) { String conditionMessage = condition.getMessage(); if (conditionMessage.matches(message)) { return true; } } return false; }); } public static void waitUntilKafkaStatusConditionContainsMessage(String clusterName, String namespace, String message) { waitUntilKafkaStatusConditionContainsMessage(clusterName, namespace, message, Constants.GLOBAL_STATUS_TIMEOUT); } public static void waitForZkMntr(String namespaceName, String clusterName, Pattern pattern, int... podIndexes) { long timeoutMs = 120_000L; long pollMs = 1_000L; for (int podIndex : podIndexes) { String zookeeperPod = KafkaResources.zookeeperPodName(clusterName, podIndex); String zookeeperPort = String.valueOf(12181); waitFor("mntr", pollMs, timeoutMs, () -> { try { String output = cmdKubeClient(namespaceName).execInPod(zookeeperPod, "/bin/bash", "-c", "echo mntr | nc localhost " + zookeeperPort).out(); if (pattern.matcher(output).find()) { return true; } } catch (KubeClusterException e) { LOGGER.trace("Exception while waiting for ZK to become leader/follower, ignoring", e); } return false; }, () -> LOGGER.info("zookeeper `mntr` output at the point of timeout does not match {}:{}{}", pattern.pattern(), System.lineSeparator(), indent(cmdKubeClient(namespaceName).execInPod(zookeeperPod, "/bin/bash", "-c", "echo mntr | nc localhost " + zookeeperPort).out())) ); } } public static void waitForZkMntr(String clusterName, Pattern pattern, int... podIndexes) { waitForZkMntr(kubeClient().getNamespace(), clusterName, pattern, podIndexes); } public static String getKafkaStatusCertificates(String listenerType, String namespace, String clusterName) { String certs = ""; List<ListenerStatus> kafkaListeners = KafkaResource.kafkaClient().inNamespace(namespace).withName(clusterName).get().getStatus().getListeners(); for (ListenerStatus listener : kafkaListeners) { if (listener.getType().equals(listenerType)) certs = listener.getCertificates().toString(); } certs = certs.substring(1, certs.length() - 1); return certs; } public static String getKafkaSecretCertificates(String namespaceName, String secretName, String certType) { String secretCerts = ""; secretCerts = kubeClient(namespaceName).getSecret(namespaceName, secretName).getData().get(certType); byte[] decodedBytes = Base64.getDecoder().decode(secretCerts); secretCerts = new String(decodedBytes, Charset.defaultCharset()); return secretCerts; } public static String getKafkaSecretCertificates(String secretName, String certType) { return getKafkaSecretCertificates(kubeClient().getNamespace(), secretName, certType); } @SuppressWarnings("unchecked") public static void waitForClusterStability(String namespaceName, String clusterName) { LOGGER.info("Waiting for cluster stability"); Map<String, String>[] zkPods = new Map[1]; Map<String, String>[] kafkaPods = new Map[1]; Map<String, String>[] eoPods = new Map[1]; int[] count = {0}; zkPods[0] = StatefulSetUtils.ssSnapshot(namespaceName, zookeeperStatefulSetName(clusterName)); kafkaPods[0] = StatefulSetUtils.ssSnapshot(namespaceName, kafkaStatefulSetName(clusterName)); eoPods[0] = DeploymentUtils.depSnapshot(namespaceName, KafkaResources.entityOperatorDeploymentName(clusterName)); TestUtils.waitFor("Cluster stable and ready", Constants.GLOBAL_POLL_INTERVAL, Constants.TIMEOUT_FOR_CLUSTER_STABLE, () -> { Map<String, String> zkSnapshot = StatefulSetUtils.ssSnapshot(namespaceName, zookeeperStatefulSetName(clusterName)); Map<String, String> kafkaSnaptop = StatefulSetUtils.ssSnapshot(namespaceName, kafkaStatefulSetName(clusterName)); Map<String, String> eoSnapshot = DeploymentUtils.depSnapshot(namespaceName, KafkaResources.entityOperatorDeploymentName(clusterName)); boolean zkSameAsLast = zkSnapshot.equals(zkPods[0]); boolean kafkaSameAsLast = kafkaSnaptop.equals(kafkaPods[0]); boolean eoSameAsLast = eoSnapshot.equals(eoPods[0]); if (!zkSameAsLast) { LOGGER.info("ZK Cluster not stable"); } if (!kafkaSameAsLast) { LOGGER.info("Kafka Cluster not stable"); } if (!eoSameAsLast) { LOGGER.info("EO not stable"); } if (zkSameAsLast && kafkaSameAsLast && eoSameAsLast) { int c = count[0]++; LOGGER.info("All stable for {} polls", c); return c > 60; } zkPods[0] = zkSnapshot; kafkaPods[0] = kafkaSnaptop; count[0] = 0; return false; }); } public static void waitForClusterStability(String clusterName) { waitForClusterStability(kubeClient().getNamespace(), clusterName); } /** * Method which, update/replace Kafka configuration * @param clusterName name of the cluster where Kafka resource can be found * @param brokerConfigName key of specific property * @param value value of specific property */ public static void updateSpecificConfiguration(String clusterName, String brokerConfigName, Object value) { KafkaResource.replaceKafkaResource(clusterName, kafka -> { LOGGER.info("Kafka config before updating '{}'", kafka.getSpec().getKafka().getConfig().toString()); Map<String, Object> config = kafka.getSpec().getKafka().getConfig(); config.put(brokerConfigName, value); kafka.getSpec().getKafka().setConfig(config); LOGGER.info("Kafka config after updating '{}'", kafka.getSpec().getKafka().getConfig().toString()); }); } /** * Method which, extends the @link updateConfiguration(String clusterName, KafkaConfiguration kafkaConfiguration, Object value) method * with stability and ensures after update of Kafka resource there will be not rolling update * @param clusterName name of the cluster where Kafka resource can be found * @param brokerConfigName key of specific property * @param value value of specific property */ public static void updateConfigurationWithStabilityWait(String clusterName, String brokerConfigName, Object value) { updateSpecificConfiguration(clusterName, brokerConfigName, value); waitForClusterStability(clusterName); } /** * Verifies that updated configuration was successfully changed inside Kafka CR * @param brokerConfigName key of specific property * @param value value of specific property */ public static boolean verifyCrDynamicConfiguration(String clusterName, String brokerConfigName, Object value) { LOGGER.info("Dynamic Configuration in Kafka CR is {}={} and excepted is {}={}", brokerConfigName, KafkaResource.kafkaClient().inNamespace(kubeClient().getNamespace()).withName(clusterName).get().getSpec().getKafka().getConfig().get(brokerConfigName), brokerConfigName, value); return KafkaResource.kafkaClient().inNamespace(kubeClient().getNamespace()).withName(clusterName).get().getSpec().getKafka().getConfig().get(brokerConfigName).equals(value); } /** * Verifies that updated configuration was successfully changed inside Kafka pods * @param kafkaPodNamePrefix prefix of Kafka pods * @param brokerConfigName key of specific property * @param value value of specific property * @return * true = if specific property match the excepted property * false = if specific property doesn't match the excepted property */ public static boolean verifyPodDynamicConfiguration(String kafkaPodNamePrefix, String brokerConfigName, Object value) { List<Pod> kafkaPods = kubeClient().listPodsByPrefixInName(kafkaPodNamePrefix); for (Pod pod : kafkaPods) { TestUtils.waitFor("Wait until dyn.configuration is changed", Constants.GLOBAL_POLL_INTERVAL, Constants.RECONCILIATION_INTERVAL + Duration.ofSeconds(10).toMillis(), () -> { String result = cmdKubeClient().execInPod(pod.getMetadata().getName(), "/bin/bash", "-c", "bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --describe").out(); LOGGER.debug("This dyn.configuration {} inside the Kafka pod {}", result, pod.getMetadata().getName()); if (!result.contains(brokerConfigName + "=" + value)) { LOGGER.error("Kafka Pod {} doesn't contain {} with value {}", pod.getMetadata().getName(), brokerConfigName, value); LOGGER.error("Kafka configuration {}", result); return false; } return true; }); } return true; } /** * Loads all kafka config parameters supported by the given {@code kafkaVersion}, as generated by #KafkaConfigModelGenerator in config-model-generator. * @param kafkaVersion specific kafka version * @return all supported kafka properties */ public static Map<String, ConfigModel> readConfigModel(String kafkaVersion) { String name = TestUtils.USER_PATH + "/../cluster-operator/src/main/resources/kafka-" + kafkaVersion + "-config-model.json"; try { try (InputStream in = new FileInputStream(name)) { ConfigModels configModels = new ObjectMapper().readValue(in, ConfigModels.class); if (!kafkaVersion.equals(configModels.getVersion())) { throw new RuntimeException("Incorrect version"); } return configModels.getConfigs(); } } catch (IOException e) { throw new RuntimeException("Error reading from classpath resource " + name, e); } } /** * Return dynamic Kafka configs supported by the the given version of Kafka. * @param kafkaVersion specific kafka version * @return all dynamic properties for specific kafka version */ @SuppressWarnings({"checkstyle:CyclomaticComplexity", "checkstyle:BooleanExpressionComplexity", "unchecked"}) public static Map<String, ConfigModel> getDynamicConfigurationProperties(String kafkaVersion) { Map<String, ConfigModel> configs = KafkaUtils.readConfigModel(kafkaVersion); LOGGER.info("This is configs {}", configs.toString()); LOGGER.info("This is all kafka configs with size {}", configs.size()); Map<String, ConfigModel> dynamicConfigs = configs .entrySet() .stream() .filter(a -> { String[] prefixKey = a.getKey().split("\\."); // filter all which is Scope = ClusterWide or PerBroker boolean isClusterWideOrPerBroker = a.getValue().getScope() == Scope.CLUSTER_WIDE || a.getValue().getScope() == Scope.PER_BROKER; if (prefixKey[0].equals("ssl") || prefixKey[0].equals("sasl") || prefixKey[0].equals("advertised") || prefixKey[0].equals("listeners") || prefixKey[0].equals("listener")) { return isClusterWideOrPerBroker && !FORBIDDEN_PREFIXES.contains(prefixKey[0]); } return isClusterWideOrPerBroker; }) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); LOGGER.info("This is dynamic-configs size {}", dynamicConfigs.size()); Map<String, ConfigModel> forbiddenExceptionsConfigs = configs .entrySet() .stream() .filter(a -> FORBIDDEN_PREFIX_EXCEPTIONS.contains(a.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); LOGGER.info("This is size of forbidden-exception-configs size {}", forbiddenExceptionsConfigs.size()); Map<String, ConfigModel> dynamicConfigsWithExceptions = new HashMap<>(); dynamicConfigsWithExceptions.putAll(dynamicConfigs); dynamicConfigsWithExceptions.putAll(forbiddenExceptionsConfigs); LOGGER.info("This is dynamic-configs with forbidden-exception-configs size {}", dynamicConfigsWithExceptions.size()); dynamicConfigsWithExceptions.forEach((key, value) -> LOGGER.info(key + " -> " + value)); return dynamicConfigsWithExceptions; } /** * Generated random name for the Kafka resource based on prefix * @param clusterName name prefix * @return name with prefix and random salt */ public static String generateRandomNameOfKafka(String clusterName) { return clusterName + "-" + new Random().nextInt(Integer.MAX_VALUE); } public static String getVersionFromKafkaPodLibs(String kafkaPodName) { String command = "ls libs | grep -Po 'kafka_\\d+.\\d+-\\K(\\d+.\\d+.\\d+)(?=.*jar)' | head -1 | cut -d \"-\" -f2"; return cmdKubeClient().execInPodContainer( kafkaPodName, "kafka", "/bin/bash", "-c", command ).out().trim(); } public static void waitForKafkaDeletion(String namespaceName, String kafkaClusterName) { LOGGER.info("Waiting for deletion of Kafka:{}", kafkaClusterName); TestUtils.waitFor("Kafka deletion " + kafkaClusterName, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, DELETION_TIMEOUT, () -> { if (KafkaResource.kafkaClient().inNamespace(namespaceName).withName(kafkaClusterName).get() == null && kubeClient(namespaceName).getStatefulSet(namespaceName, KafkaResources.kafkaStatefulSetName(kafkaClusterName)) == null && kubeClient(namespaceName).getStatefulSet(namespaceName, KafkaResources.zookeeperStatefulSetName(kafkaClusterName)) == null && kubeClient(namespaceName).getDeployment(namespaceName, KafkaResources.entityOperatorDeploymentName(kafkaClusterName)) == null) { return true; } else { cmdKubeClient(namespaceName).deleteByName(Kafka.RESOURCE_KIND, kafkaClusterName); return false; } }, () -> LOGGER.info(KafkaResource.kafkaClient().inNamespace(namespaceName).withName(kafkaClusterName).get())); } public static void waitForKafkaDeletion(String kafkaClusterName) { waitForKafkaDeletion(kubeClient().getNamespace(), kafkaClusterName); } public static String getKafkaTlsListenerCaCertName(String namespace, String clusterName, String listenerName) { List<GenericKafkaListener> listeners = KafkaResource.kafkaClient().inNamespace(namespace).withName(clusterName).get().getSpec().getKafka().getListeners().newOrConverted(); GenericKafkaListener tlsListener = listenerName == null || listenerName.isEmpty() ? listeners.stream().filter(listener -> Constants.TLS_LISTENER_DEFAULT_NAME.equals(listener.getName())).findFirst().orElseThrow(RuntimeException::new) : listeners.stream().filter(listener -> listenerName.equals(listener.getName())).findFirst().orElseThrow(RuntimeException::new); return tlsListener.getConfiguration() == null ? KafkaResources.clusterCaCertificateSecretName(clusterName) : tlsListener.getConfiguration().getBrokerCertChainAndKey().getSecretName(); } public static String getKafkaExternalListenerCaCertName(String namespace, String clusterName, String listenerName) { List<GenericKafkaListener> listeners = KafkaResource.kafkaClient().inNamespace(namespace).withName(clusterName).get().getSpec().getKafka().getListeners().newOrConverted(); GenericKafkaListener external = listenerName == null || listenerName.isEmpty() ? listeners.stream().filter(listener -> Constants.EXTERNAL_LISTENER_DEFAULT_NAME.equals(listener.getName())).findFirst().orElseThrow(RuntimeException::new) : listeners.stream().filter(listener -> listenerName.equals(listener.getName())).findFirst().orElseThrow(RuntimeException::new); if (external.getConfiguration() == null) { return KafkaResources.clusterCaCertificateSecretName(clusterName); } else { if (external.getConfiguration().getBrokerCertChainAndKey() != null) { return external.getConfiguration().getBrokerCertChainAndKey().getSecretName(); } else { return KafkaResources.clusterCaCertificateSecretName(clusterName); } } } public static KafkaStatus getKafkaStatus(String clusterName, String namespace) { return KafkaResource.kafkaClient().inNamespace(namespace).withName(clusterName).get().getStatus(); } public static String changeOrRemoveKafkaVersion(File file, String version) { return changeOrRemoveKafkaConfiguration(file, version, null, null); } public static String changeOrRemoveKafkaConfiguration(File file, String version, String logMessageFormat, String interBrokerProtocol) { YAMLMapper mapper = new YAMLMapper(); try { JsonNode node = mapper.readTree(file); ObjectNode kafkaNode = (ObjectNode) node.at("/spec/kafka"); if (version == null) { kafkaNode.remove("version"); ((ObjectNode) kafkaNode.get("config")).remove("log.message.format.version"); ((ObjectNode) kafkaNode.get("config")).remove("inter.broker.protocol.version"); } else if (!version.equals("")) { kafkaNode.put("version", version); ((ObjectNode) kafkaNode.get("config")).put("log.message.format.version", TestKafkaVersion.getSpecificVersion(version).messageVersion()); ((ObjectNode) kafkaNode.get("config")).put("inter.broker.protocol.version", TestKafkaVersion.getSpecificVersion(version).protocolVersion()); } if (logMessageFormat != null) { ((ObjectNode) kafkaNode.get("config")).put("log.message.format.version", logMessageFormat); } if (interBrokerProtocol != null) { ((ObjectNode) kafkaNode.get("config")).put("inter.broker.protocol.version", interBrokerProtocol); } return mapper.writeValueAsString(node); } catch (IOException e) { throw new RuntimeException(e); } } }
51.1125
223
0.677916
07dfe72980753da18f8f4bd1633592c66d620337
178
package org.aesy.musicbrainz.client; import org.aesy.musicbrainz.entity.Series; public interface MusicBrainzSeriesBrowseRequest extends MusicBrainzBrowseRequest<Series> {}
25.428571
47
0.837079
f091aa270e0e39fcd0422c5ffcd728d38d789415
267
package com.base.paginate.interfaces; import com.base.paginate.viewholder.PageViewHolder; /** * 多种布局条目点击事件 * * @param <T> */ public interface OnMultiItemClickListeners<T> { void onItemClick(PageViewHolder viewHolder, T data, int position, int viewType); }
19.071429
84
0.749064
915ec9a39655ba0a84b533254e98e138f45327ab
4,617
package net.minecraft.entity.ai; import net.minecraft.block.Block; import net.minecraft.block.BlockCrops; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.ai.EntityAIMoveToBlock; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.world.World; public class EntityAIHarvestFarmland extends EntityAIMoveToBlock { private final EntityVillager field_179504_c; private boolean field_179502_d; private boolean field_179503_e; private int field_179501_f; private static final String __OBFID = "CL_00002253"; public EntityAIHarvestFarmland(EntityVillager p_i45889_1_, double p_i45889_2_) { super(p_i45889_1_, p_i45889_2_, 16); this.field_179504_c = p_i45889_1_; } public boolean func_75250_a() { if(this.field_179496_a <= 0) { if(!this.field_179504_c.field_70170_p.func_82736_K().func_82766_b("mobGriefing")) { return false; } this.field_179501_f = -1; this.field_179502_d = this.field_179504_c.func_175556_cs(); this.field_179503_e = this.field_179504_c.func_175557_cr(); } return super.func_75250_a(); } public boolean func_75253_b() { return this.field_179501_f >= 0 && super.func_75253_b(); } public void func_75249_e() { super.func_75249_e(); } public void func_75251_c() { super.func_75251_c(); } public void func_75246_d() { super.func_75246_d(); this.field_179504_c.func_70671_ap().func_75650_a((double)this.field_179494_b.func_177958_n() + 0.5D, (double)(this.field_179494_b.func_177956_o() + 1), (double)this.field_179494_b.func_177952_p() + 0.5D, 10.0F, (float)this.field_179504_c.func_70646_bf()); if(this.func_179487_f()) { World var1 = this.field_179504_c.field_70170_p; BlockPos var2 = this.field_179494_b.func_177984_a(); IBlockState var3 = var1.func_180495_p(var2); Block var4 = var3.func_177230_c(); if(this.field_179501_f == 0 && var4 instanceof BlockCrops && ((Integer)var3.func_177229_b(BlockCrops.field_176488_a)).intValue() == 7) { var1.func_175655_b(var2, true); } else if(this.field_179501_f == 1 && var4 == Blocks.field_150350_a) { InventoryBasic var5 = this.field_179504_c.func_175551_co(); for(int var6 = 0; var6 < var5.func_70302_i_(); ++var6) { ItemStack var7 = var5.func_70301_a(var6); boolean var8 = false; if(var7 != null) { if(var7.func_77973_b() == Items.field_151014_N) { var1.func_180501_a(var2, Blocks.field_150464_aj.func_176223_P(), 3); var8 = true; } else if(var7.func_77973_b() == Items.field_151174_bG) { var1.func_180501_a(var2, Blocks.field_150469_bN.func_176223_P(), 3); var8 = true; } else if(var7.func_77973_b() == Items.field_151172_bF) { var1.func_180501_a(var2, Blocks.field_150459_bM.func_176223_P(), 3); var8 = true; } } if(var8) { --var7.field_77994_a; if(var7.field_77994_a <= 0) { var5.func_70299_a(var6, (ItemStack)null); } break; } } } this.field_179501_f = -1; this.field_179496_a = 10; } } protected boolean func_179488_a(World p_179488_1_, BlockPos p_179488_2_) { Block var3 = p_179488_1_.func_180495_p(p_179488_2_).func_177230_c(); if(var3 == Blocks.field_150458_ak) { p_179488_2_ = p_179488_2_.func_177984_a(); IBlockState var4 = p_179488_1_.func_180495_p(p_179488_2_); var3 = var4.func_177230_c(); if(var3 instanceof BlockCrops && ((Integer)var4.func_177229_b(BlockCrops.field_176488_a)).intValue() == 7 && this.field_179503_e && (this.field_179501_f == 0 || this.field_179501_f < 0)) { this.field_179501_f = 0; return true; } if(var3 == Blocks.field_150350_a && this.field_179502_d && (this.field_179501_f == 1 || this.field_179501_f < 0)) { this.field_179501_f = 1; return true; } } return false; } }
38.475
262
0.620966
80d6dc4a11333ca18752a4d5eb1c52b3bbf97ed3
547
/** * Spring's repackaging of {@code org.objectweb.asm.*} (for internal use only). * <p>This repackaging technique avoids any potential conflicts with * dependencies on ASM at the application level or from other third-party * libraries and frameworks. * <p>As this repackaging happens at the classfile level, sources and Javadoc * are not available here. See the original ObjectWeb * <a href="http://asm.ow2.org/asm223/javadoc/user">ASM 2.2.3 Javadoc</a> * for details when working with these classes. */ package org.springframework.asm;
45.583333
79
0.751371
117d6545df484c4c0c1525977ad2e49c3f8d3463
2,576
package com.jeeplus.blog.controller.dto; import java.sql.Timestamp; /** * @author:yuzp17311 * @version:v1.0 * @date: 2017-02-23 19:55. */ public class BlogMsgBoardDTO { private String id; private String websiteid; private String msgText; private BlogUserDTO msgSendUser; private BlogUserDTO msgAt; private String msgRoot; private Timestamp msgDatetime; private String msgFlag; private Integer msgLike; private Integer msgCount; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getWebsiteid() { return websiteid; } public void setWebsiteid(String websiteid) { this.websiteid = websiteid; } public String getMsgText() { return msgText; } public void setMsgText(String msgText) { this.msgText = msgText; } public BlogUserDTO getMsgSendUser() { return msgSendUser; } public void setMsgSendUser(BlogUserDTO msgSendUser) { this.msgSendUser = msgSendUser; } public BlogUserDTO getMsgAt() { return msgAt; } public void setMsgAt(BlogUserDTO msgAt) { this.msgAt = msgAt; } public String getMsgRoot() { return msgRoot; } public void setMsgRoot(String msgRoot) { this.msgRoot = msgRoot; } public Timestamp getMsgDatetime() { return msgDatetime; } public void setMsgDatetime(Timestamp msgDatetime) { this.msgDatetime = msgDatetime; } public String getMsgFlag() { return msgFlag; } public void setMsgFlag(String msgFlag) { this.msgFlag = msgFlag; } public Integer getMsgLike() { return msgLike; } public void setMsgLike(Integer msgLike) { this.msgLike = msgLike; } public Integer getMsgCount() { return msgCount; } public void setMsgCount(Integer msgCount) { this.msgCount = msgCount; } @Override public String toString() { return "BlogMsgBoardDTO{" + "id='" + id + '\'' + ", websiteid='" + websiteid + '\'' + ", msgText='" + msgText + '\'' + ", msgSendUser=" + msgSendUser + ", msgAt=" + msgAt + ", msgRoot='" + msgRoot + '\'' + ", msgDatetime=" + msgDatetime + ", msgFlag='" + msgFlag + '\'' + ", msgLike=" + msgLike + ", msgCount=" + msgCount + '}'; } }
21.647059
57
0.564053
845ad55fea0b38ac208ed436bf17fc3aa83f850b
1,711
/* * 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.geode.management.internal; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; /** * Membership operations for Geode JMX managers. */ public interface ManagerMembership { /** * This method will be invoked from MembershipListener which is registered when the member becomes * a Management node. */ void addMember(InternalDistributedMember member); /** * This method will be invoked from MembershipListener which is registered when the member becomes * a Management node. */ void removeMember(DistributedMember member, boolean crashed); /** * This method will be invoked from MembershipListener which is registered when the member becomes * a Management node. */ void suspectMember(DistributedMember member, InternalDistributedMember whoSuspected, String reason); }
38.886364
100
0.769141
7fdf83b56397743275a6245af10487a2d83a406f
906
class Database { private final String F_Name; private final String S_Name; private final int Year_o_B; private int WorkTime = 0; private static float MaxWorkTime = 1; public String getF_Name() { return F_Name; } public String getS_Name() { return S_Name; } public int getYear_o_B() { return Year_o_B; } public int getWorkTime() { return WorkTime; } public Database(String F_Name, String S_Name, int Year_o_B) { this.F_Name = F_Name; this.S_Name = S_Name; this.Year_o_B = Year_o_B; } public boolean MoreMoney(float MoreMoney){ if (this.WorkTime + MoreMoney > MaxWorkTime) return false; this.WorkTime += MoreMoney; return true; } public static void setMaxWorkTime(float MaxWorkTime) { Database.MaxWorkTime = MaxWorkTime; } }
22.097561
65
0.613687
ec508fc7e972e6acf9fd696e8dd6c6286482d285
2,723
package com.caryatri.caryatri.Services; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.ContextWrapper; import android.net.Uri; import android.os.Build; import com.caryatri.caryatri.R; public class NotificationHelper extends ContextWrapper { private static final String SHOP_CHANNEL_ID = "com.caryatri.caryatri.CarYatri"; private static final String SHOP_CHANNEL_NAME = "CarYatri"; private NotificationManager notificationManager; public NotificationHelper(Context base) { super(base); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel(); } @TargetApi(Build.VERSION_CODES.O) private void createChannel() { NotificationChannel shopChannel = new NotificationChannel(SHOP_CHANNEL_ID, SHOP_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); shopChannel.enableLights(false); shopChannel.enableVibration(true); shopChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); getManager().createNotificationChannel(shopChannel); } public NotificationManager getManager() { if (notificationManager == null) notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); return notificationManager; } @TargetApi(Build.VERSION_CODES.O) public Notification.Builder getCarYatriNotificationWithout(String title, String message, Uri soundUri) { return new Notification.Builder(getApplicationContext(), SHOP_CHANNEL_ID) .setContentTitle(title) .setContentText(message) .setSmallIcon(R.mipmap.ic_launcher) .setSound(soundUri) .setAutoCancel(true); } @TargetApi(Build.VERSION_CODES.O) public Notification.Builder getCarYatriNotificationWith(String title, String message, Uri soundUri, PendingIntent pendingIntent) { return new Notification.Builder(getApplicationContext(), SHOP_CHANNEL_ID) .setContentTitle(title) .setContentText(message) .setSmallIcon(R.mipmap.ic_launcher) .setSound(soundUri) .setAutoCancel(true) .setFullScreenIntent(pendingIntent, true); } }
35.828947
104
0.647815
103c436ef01a49a102c24659d114d6c996cc8ea1
4,110
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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.jasig.portlet.ClassifiedsPortlet.web; import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.portlet.ClassifiedsPortlet.domain.CategoryEditor; import org.jasig.portlet.ClassifiedsPortlet.domain.SubmitCategoryFormValidator; import org.springframework.validation.BindingResult; import org.jasig.portlet.ClassifiedsPortlet.domain.Heading; import org.jasig.portlet.ClassifiedsPortlet.service.HeadingService; import org.jasig.portlet.ClassifiedsPortlet.domain.Category; import org.jasig.portlet.ClassifiedsPortlet.service.CategoryService; import org.springframework.web.portlet.bind.PortletRequestDataBinder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.support.SessionStatus; import org.jasig.portlet.ClassifiedsPortlet.domain.SubmitHeadingFormValidator; @Controller @RequestMapping("EDIT") public class SubmitHeadingFormController { private static Log log = LogFactory.getLog(SubmitHeadingFormController.class); @Autowired private HeadingService headingService; @Autowired private CategoryService categoryService = null; @RequestMapping(params="action=addHeading") public String setupForm( @RequestParam(value="id", required=false) Long id, Model model, PortletRequest request) { Heading heading = new Heading(); if (!model.containsAttribute("heading")) { if (id != null) { List<Heading> headingList = this.headingService.getHeading(id); heading = (Heading) headingList.get(0); } model.addAttribute("heading", heading); } return "submitHeadingForm"; } //converting strings from drop down list in form to Category class @InitBinder public void initBinder(PortletRequest request, PortletRequestDataBinder binder) throws Exception{ binder.registerCustomEditor(Category.class, new CategoryEditor(categoryService)); } @ModelAttribute("categories") public List <Category> getCategories() { return categoryService.getCategories(); } @RequestMapping(params="action=addHeading") protected void processFormSubmission( @ModelAttribute("heading") Heading heading, BindingResult result, SessionStatus status, ActionRequest request, ActionResponse response, Model model) throws PortletException { new SubmitHeadingFormValidator().validate(heading, result); if (result.hasErrors()) { response.setRenderParameter("action", "addHeading"); return; } if (!result.hasErrors() && heading != null){ if (log.isDebugEnabled()) log.debug("No errors in form"); headingService.processHeading(heading); status.setComplete(); response.setRenderParameter("action", "editHeadings"); } } }
31.615385
101
0.775182