blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
697347b301c3349c5c884757ae03ac6c270abc2b
Java
luoximin1990/Country-Love-Api
/src/main/java/com/marykay/country/love/repository/CountryRepository.java
UTF-8
365
1.867188
2
[]
no_license
package com.marykay.country.love.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.marykay.country.love.model.Country; @Repository public interface CountryRepository extends JpaRepository<Country, Integer> { List<Country> findByCityId(long cityId); }
true
c70caffdb313c59d812104d0d6e1b4acb6ce885a
Java
nogovitsyndmitriy/BookingService
/src/dao/CreditCardDao.java
UTF-8
205
1.984375
2
[]
no_license
package dao; import entity.CreditCard; import java.sql.SQLException; import java.util.List; public interface CreditCardDao extends DAO<CreditCard> { List<CreditCard> getAll() throws SQLException; }
true
6633bde2fb47b3c0e6c991ddc968701f7fbb8a53
Java
unisung/java1
/ch07/src/verify/ch06/Child.java
UHC
348
3.0625
3
[]
no_license
package verify.ch06; public class Child extends Parent{ private String name; public Child(){ this("ȫ浿");//Child(name) ȣ// System.out.println("Child() call");//4 } public Child(String name){//3 //super();// this.name=name; System.out.println("Child(String name) call"); } }
true
7e5e525bd258315d208298fbd9ecd19ee5ed45bf
Java
1914116/Level-1
/src/Graphics/Calculator.java
UTF-8
1,615
3.328125
3
[]
no_license
package Graphics; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator implements ActionListener { JFrame calculator = new JFrame(); JPanel calc = new JPanel(); JButton add = new JButton(); JButton sub = new JButton(); JButton div = new JButton(); JButton mul = new JButton(); JTextField x = new JTextField(); JTextField y = new JTextField(); JLabel ans = new JLabel(); public static void main(String[] args) { // TODO Auto-generated method stub Calculator c = new Calculator(); c.showCalculator(); } void showCalculator(){ calculator.add(calc); calc.add(x); calc.add(add); calc.add(sub); calc.add(div); calc.add(mul); calc.add(y); calc.add(ans); add.setText("Addition"); sub.setText("Subtract"); mul.setText("Multiply"); div.setText("divide"); calculator.setVisible(true); calculator.setSize(500, 150); x.setPreferredSize(new Dimension(50,25)); y.setPreferredSize(new Dimension(50,25)); add.addActionListener(this); sub.addActionListener(this); div.addActionListener(this); mul.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==add){ String a = x.getText(); String b = y.getText(); int c =Integer.parseInt(b); int d = Integer.parseInt(a); int f = c + d; } else if(e.getSource()==sub){ } else if(e.getSource()==div){ } else if(e.getSource()==mul){ } } }
true
fd182c3a5f5183792a4d72850eb1341a75245536
Java
OMMEENA/DataStructure-Algo
/src/main/java/annotation/CustomAnnotation.java
UTF-8
1,969
3.484375
3
[]
no_license
package annotation; // The annotations they don't have any variables called Marker Annotations import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //We need 2 predefine Meta annotation @Target(ElementType.TYPE) // Type says scope is class level @Retention(RetentionPolicy.RUNTIME) // Runtime says scope is RunTime @interface SmartDevice { int Id() default 0; // field in annotation with the default values String name() default "VG"; //1 way to specify the default values } @SmartDevice//(Id = 0, name = "Dell") we can specify the default values here as well class Device { int id; String name; public Device(int id, String name) { this.id = id; this.name = name; } } //1 retention Annotation @Retention(RetentionPolicy.RUNTIME) //till when this annotation exists @interface CustomRetention{ String name() default "retention"; } class CustomRetentionTest{ @CustomRetention(name = "Print data") public void printData(){ } } //Deprecated Annotation class CustomDeprecated { @Deprecated public void Display() { System.out.println("Deprecated Annotation test Method()"); } public static void main(String args[]) { CustomDeprecated Dep = new CustomDeprecated(); Dep.Display(); } } public class CustomAnnotation { public static void main(String[] args) { Device device = new Device(1, "Test"); System.out.println(device.name); //TO fetch the Values of the annotations like 0, and VG we need to follow some steps //Use reflection to get the value Class c = device.getClass(); Annotation an = c.getAnnotation(SmartDevice.class); SmartDevice smartDevice = (SmartDevice) an; System.out.println(smartDevice.Id() + " "+ smartDevice.name()); } }
true
bdf2e7786185913e61b44474b1e4118323fc3398
Java
rexlManu/Schickhardschule
/src/de/rexlmanu/vplanapi/misc/Days.java
UTF-8
1,022
2.71875
3
[ "MIT" ]
permissive
package de.rexlmanu.vplanapi.misc; import java.net.MalformedURLException; import java.net.URL; public enum Days { MONDAY("Montag", toUrl("https://www.schickhardtschule.de/susvertretung/montag.html")), TUESDAY("Dienstag", toUrl("https://www.schickhardtschule.de/susvertretung/dienstag.html")), WEDNESSDAY("Mittwoch", toUrl("https://www.schickhardtschule.de/susvertretung/mittwoch.html")), THURSDAY("Donnerstag", toUrl("https://www.schickhardtschule.de/susvertretung/donnerstag.html")), FRIDAY("Freitag", toUrl("https://www.schickhardtschule.de/susvertretung/freitag.html")); private String name; private URL url; Days(String name, URL url) { this.name = name; this.url = url; } public String getName() { return name; } public URL getUrl() { return url; } private static URL toUrl(String url){ try { return new URL(url); } catch (MalformedURLException e) { return null; } } }
true
980f7fc321dd3482a53a2d2580c8bbc43428b43b
Java
MorningSage/Mekanism-Fabric
/src/main/java/mekanism/client/jei/BaseRecipeCategory.java
UTF-8
5,678
1.984375
2
[ "MIT" ]
permissive
package mekanism.client.jei; import net.minecraft.client.util.math.MatrixStack; import it.unimi.dsi.fastutil.longs.Long2ObjectFunction; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import java.util.List; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import mekanism.api.annotations.NonNull; import mekanism.api.chemical.ChemicalStack; import mekanism.api.providers.IBaseProvider; import mekanism.client.gui.IGuiWrapper; import mekanism.client.gui.element.GuiTexturedElement; import mekanism.client.gui.element.gauge.GaugeOverlay; import mezz.jei.api.gui.ITickTimer; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.ingredient.IGuiIngredientGroup; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.recipe.category.IRecipeCategory; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; public abstract class BaseRecipeCategory<RECIPE> implements IRecipeCategory<RECIPE>, IGuiWrapper { protected final ITickTimer timer; protected final int xOffset; protected final int yOffset; protected final IDrawable fluidOverlayLarge; protected final IDrawable fluidOverlaySmall; protected final IDrawable fluidOverlaySmallMed; protected final Set<GuiTexturedElement> guiElements = new ObjectOpenHashSet<>(); private final ResourceLocation id; private final ITextComponent component; private final IDrawable background; @Nullable protected IDrawable icon; protected BaseRecipeCategory(IGuiHelper helper, IBaseProvider provider, int xOffset, int yOffset, int width, int height) { this(helper, provider.getRegistryName(), provider.getTextComponent(), xOffset, yOffset, width, height); } protected BaseRecipeCategory(IGuiHelper helper, ResourceLocation id, ITextComponent component, int xOffset, int yOffset, int width, int height) { this.id = id; this.component = component; //TODO: Only make a timer for ones we need it this.timer = helper.createTickTimer(20, 20, false); this.fluidOverlayLarge = createDrawable(helper, GaugeOverlay.STANDARD); this.fluidOverlaySmall = createDrawable(helper, GaugeOverlay.SMALL); this.fluidOverlaySmallMed = createDrawable(helper, GaugeOverlay.SMALL_MED); this.xOffset = xOffset; this.yOffset = yOffset; this.background = new NOOPDrawable(width, height); addGuiElements(); } private IDrawable createDrawable(IGuiHelper helper, GaugeOverlay gaugeOverlay) { return helper.drawableBuilder(gaugeOverlay.getBarOverlay(), 0, 0, gaugeOverlay.getWidth(), gaugeOverlay.getHeight()) .setTextureSize(gaugeOverlay.getWidth(), gaugeOverlay.getHeight()) .build(); } @Override public int getLeft() { return -xOffset; } @Override public int getTop() { return -yOffset; } @Override public int getWidth() { return background.getWidth(); } @Override public int getHeight() { return background.getHeight(); } @Override public ResourceLocation getUid() { return id; } @Override public String getTitle() { return component.getString(); } @Override public void draw(RECIPE recipe, MatrixStack matrix, double mouseX, double mouseY) { guiElements.forEach(e -> e.render(matrix, (int) mouseX, (int) mouseY, 0)); guiElements.forEach(e -> e.drawBackground(matrix, (int) mouseX, (int) mouseY, 0)); } @Override public ItemRenderer getItemRenderer() { return Minecraft.getInstance().getItemRenderer(); } @Override public FontRenderer getFont() { return Minecraft.getInstance().fontRenderer; } protected void addGuiElements() { } @Override public IDrawable getBackground() { return background; } @Override public IDrawable getIcon() { //Note: Even though we usually return null form here, this is allowed even though annotations imply it isn't supposed to be return icon; } protected <STACK extends ChemicalStack<?>> void initChemical(IGuiIngredientGroup<STACK> group, int slot, boolean input, int x, int y, int width, int height, @Nonnull List<STACK> stacks) { initChemical(group, slot, input, x, y, width, height, stacks, max -> new ChemicalStackRenderer<>(max, width, height)); } protected <STACK extends ChemicalStack<?>> void initChemical(IGuiIngredientGroup<STACK> group, int slot, boolean input, int x, int y, int width, int height, @Nonnull List<STACK> stacks, boolean overlay) { initChemical(group, slot, input, x, y, width, height, stacks, max -> new ChemicalStackRenderer<>(max, false, width, height, overlay ? height > 50 ? fluidOverlayLarge : (height == 46 ? fluidOverlaySmallMed : fluidOverlaySmall) : null)); } private <STACK extends ChemicalStack<?>> void initChemical(IGuiIngredientGroup<@NonNull STACK> group, int slot, boolean input, int x, int y, int width, int height, @Nonnull List<STACK> stacks, Long2ObjectFunction<ChemicalStackRenderer<STACK>> rendererSupplier) { if (!stacks.isEmpty()) { long max = stacks.stream().mapToLong(ChemicalStack::getAmount).filter(stack -> stack >= 0).max().orElse(0); group.init(slot, input, rendererSupplier.apply(max), x, y, width, height, 0, 0); group.set(slot, stacks); } } }
true
6d4b566f7fc419351b57692a4beafcd4c7090c42
Java
linksunshine/baseline
/baseline-server/src/main/java/com/linksunshine/baseline/server/web/service/impl/PermissionServiceImpl.java
UTF-8
3,876
2.046875
2
[]
no_license
package com.linksunshine.baseline.server.web.service.impl; import com.github.pagehelper.PageHelper; import com.linksunshine.baseline.server.web.core.orika.OrikaBeanMapper; import com.linksunshine.baseline.server.web.dao.PermissionMapper; import com.linksunshine.baseline.server.web.dto.PermissionDTO; import com.linksunshine.baseline.server.web.model.Permission; import com.linksunshine.baseline.server.web.service.PermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tk.mybatis.mapper.entity.Example; import java.util.Date; import java.util.List; import java.util.UUID; /** * Created by ucmed on 2017/4/1. */ @Service("permissionService") public class PermissionServiceImpl implements PermissionService { @Autowired private OrikaBeanMapper orikaBeanMapper; @Autowired private PermissionMapper permissionMapper; public int insert(PermissionDTO permissionDTO) { Permission permission = orikaBeanMapper.map(permissionDTO, Permission.class); permission.setPermissionId(UUID.randomUUID().toString()); permission.setCreatedby("admin"); permission.setCreatedon(new Date()); permission.setModifiedby("admin"); permission.setModifiedon(new Date()); permission.setDeletionState("0"); return permissionMapper.insertSelective(permission); } public int count() { Permission permission = new Permission(); permission.setDeletionState("0"); return permissionMapper.selectCount(permission); } public List<PermissionDTO> loadList(int pageNo, int pageSize) { PageHelper.startPage(pageNo, pageSize); Permission permission = new Permission(); permission.setDeletionState("0"); Example example = new Example(Permission.class); example.setOrderByClause("createdon desc");//注意用的是类中的属性,不是数据库中的属性 example.createCriteria().andEqualTo(permission); return orikaBeanMapper.mapAsList(permissionMapper.selectByExample(example), PermissionDTO.class); } public int countSearch(String searchKey) { Example example = new Example(Permission.class); example.setOrderByClause("createdon desc");//注意用的是类中的属性,不是数据库中的属性 example.createCriteria() .andCondition("permission_name like '%" + searchKey + "%'") .andEqualTo("deletionState", "0"); return permissionMapper.selectCountByExample(example); } public List<PermissionDTO> search(int pageNo, int pageSize, String searchKey) { PageHelper.startPage(pageNo, pageSize); Example example = new Example(Permission.class); example.setOrderByClause("createdon desc");//注意用的是类中的属性,不是数据库中的属性 example.createCriteria() .andCondition("permission_name like '%" + searchKey + "%'") .andEqualTo("deletionState", "0"); return orikaBeanMapper.mapAsList(permissionMapper.selectByExample(example), PermissionDTO.class); } public List<PermissionDTO> loadList() { Permission permission = new Permission(); permission.setDeletionState("0"); Example example = new Example(Permission.class); example.setOrderByClause("createdon desc");//注意用的是类中的属性,不是数据库中的属性 example.createCriteria().andEqualTo(permission); return orikaBeanMapper.mapAsList(permissionMapper.selectByExample(example), PermissionDTO.class); } public int updatePermission(PermissionDTO permissionDTO) { permissionDTO.setModifiedon(new Date()); return permissionMapper.updateByPrimaryKeySelective(orikaBeanMapper.map(permissionDTO, Permission.class)); } }
true
75105212a037481123a9bad2852c0fe81085ef9e
Java
hwedwin/spring-boot-starters-project
/spring-boot-monitor/monitor-spring-boot-autoconfigure/src/main/java/in/hocg/boot/monitor/autoconfiguration/MonitorAutoConfiguration.java
UTF-8
1,402
1.820313
2
[ "Apache-2.0" ]
permissive
package in.hocg.boot.monitor.autoconfiguration; import in.hocg.boot.monitor.autoconfiguration.properties.MonitorProperties; import io.micrometer.core.instrument.MeterRegistry; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** * Created by hocgin on 2020/8/15 * email: hocgin@gmail.com * * @author hocgin */ @Configuration @ConditionalOnProperty(prefix = MonitorProperties.PREFIX, name = "enabled", matchIfMissing = true) @EnableConfigurationProperties(MonitorProperties.class) @RequiredArgsConstructor(onConstructor = @__(@Lazy)) public class MonitorAutoConfiguration { @Value("${spring.application.name:unknown}") private String applicationName; @Value("${spring.profiles.active:unknown}") private String profileActive; @Bean public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() { return registry -> registry.config().commonTags("application", applicationName + "-" + profileActive); } }
true
8917987c1cb8db81765562954c71046804c1507b
Java
NPEX-Ltd/NPlib
/src/np/library/testing/tests/NodeListIterator.java
UTF-8
715
2.609375
3
[]
no_license
package np.library.testing.tests; import java.util.Iterator; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class NodeListIterator implements Iterable<Node> { private NodeIterator iterator; public NodeListIterator(NodeList list) { super(); this.iterator = new NodeIterator(list); } @Override public Iterator<Node> iterator() { return iterator; } public static class NodeIterator implements Iterator<Node> { NodeList list; int ptr = 0; public NodeIterator(NodeList list) { super(); this.list = list; } @Override public boolean hasNext() { return ptr > list.getLength(); } @Override public Node next() { return list.item(ptr++); } } }
true
714040c1986d53ae34151a11cb5f02c1815eb0a4
Java
iamVaibhavPatil/GetMyRoomie
/src/com/roomie/web/dao/entity/RoomMateList.java
UTF-8
4,547
2
2
[]
no_license
package com.roomie.web.dao.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.apache.commons.lang3.StringUtils; @Entity @Table(name = "ROOM_MATE_LIST") public class RoomMateList { @Id @Column(name="ROOM_MATE_ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long roomMateId; @Column(name="USER_EMAIL") private String userEmail; @Column(name="LOOKIN_IN_CITY") private String lookingInCity; @Column(name="LOOKIN_FOR_AREA") private String lookingforArea; @Column(name="PROFILE_HEADLINE") private String profileHeadLine; @Column(name="RENTING_FOR_MONTHS") private String rentingForMonth; @Column(name="MONTHLY_BUDGET") private String monthlyBudget; @Column(name="MOVE_IN_DATE") private String moveInDate; @Column(name="MATE_GENDER") private String mateGender; @Column(name="MATE_OCCUPATION") private String mateOccupation; @Column(name="MATE_PETS_ALLOWED") private String matePetsAllowed; @Column(name="MATE_SMOKING_ALLOWED") private String mateSmokingAllowed; @Column(name="MATE_DRINKING_ALLOWED") private String mateDrinkingAllowed; @Column(name="MATE_PREFER_TOLIVE_WITH") private String matePreferToLiveWith; @Column(name="MATE_LIST_STATUS") private String mateListStatus; @Column(name="MATE_LIST_CREATED_DATE") private String mateListCreatedDate; @Column(name="MATE_LIST_MODIFIED_DATE") private String mateListModifiedDate; public RoomMateList(){ } public Long getRoomMateId() { return roomMateId; } public void setRoomMateId(Long roomMateId) { this.roomMateId = roomMateId; } public String getUserEmail() { return StringUtils.upperCase(userEmail); } public void setUserEmail(String userEmail) { this.userEmail = StringUtils.upperCase(userEmail); } public String getLookingInCity() { return lookingInCity; } public void setLookingInCity(String lookingInCity) { this.lookingInCity = lookingInCity; } public String getLookingforArea() { return lookingforArea; } public void setLookingforArea(String lookingforArea) { this.lookingforArea = lookingforArea; } public String getProfileHeadLine() { return profileHeadLine; } public void setProfileHeadLine(String profileHeadLine) { this.profileHeadLine = profileHeadLine; } public String getRentingForMonth() { return rentingForMonth; } public void setRentingForMonth(String rentingForMonth) { this.rentingForMonth = rentingForMonth; } public String getMonthlyBudget() { return monthlyBudget; } public void setMonthlyBudget(String monthlyBudget) { this.monthlyBudget = monthlyBudget; } public String getMoveInDate() { return moveInDate; } public void setMoveInDate(String moveInDate) { this.moveInDate = moveInDate; } public String getMateGender() { return mateGender; } public void setMateGender(String mateGender) { this.mateGender = mateGender; } public String getMateOccupation() { return mateOccupation; } public void setMateOccupation(String mateOccupation) { this.mateOccupation = mateOccupation; } public String getMatePetsAllowed() { return matePetsAllowed; } public void setMatePetsAllowed(String matePetsAllowed) { this.matePetsAllowed = matePetsAllowed; } public String getMateSmokingAllowed() { return mateSmokingAllowed; } public void setMateSmokingAllowed(String mateSmokingAllowed) { this.mateSmokingAllowed = mateSmokingAllowed; } public String getMateDrinkingAllowed() { return mateDrinkingAllowed; } public void setMateDrinkingAllowed(String mateDrinkingAllowed) { this.mateDrinkingAllowed = mateDrinkingAllowed; } public String getMatePreferToLiveWith() { return matePreferToLiveWith; } public void setMatePreferToLiveWith(String matePreferToLiveWith) { this.matePreferToLiveWith = matePreferToLiveWith; } public String getMateListStatus() { return mateListStatus; } public void setMateListStatus(String mateListStatus) { this.mateListStatus = mateListStatus; } public String getMateListCreatedDate() { return mateListCreatedDate; } public void setMateListCreatedDate(String mateListCreatedDate) { this.mateListCreatedDate = mateListCreatedDate; } public String getMateListModifiedDate() { return mateListModifiedDate; } public void setMateListModifiedDate(String mateListModifiedDate) { this.mateListModifiedDate = mateListModifiedDate; } }
true
34c6c713f7e394c626255020cd96b9056d21538e
Java
LosDeSiempre420/mypocketeamMongo
/src/test/java/com/losdesiempre/mypocketeam/AbstractMovementControllerTest.java
UTF-8
3,041
2.15625
2
[]
no_license
package com.losdesiempre.mypocketeam; import com.fasterxml.jackson.databind.ObjectMapper; import com.losdesiempre.mypocketeam.controller.MovimientoController; import com.losdesiempre.mypocketeam.domain.Movement; import com.losdesiempre.mypocketeam.service.MovementService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.springframework.boot.test.json.JacksonTester; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class AbstractMovementControllerTest { private MockMvc mockMvc; @Mock private MovementService movementService; private JacksonTester<Movement> jsonMovement; @InjectMocks MovimientoController movimientoController; @BeforeEach void setup(){ JacksonTester.initFields(this,new ObjectMapper()); mockMvc = MockMvcBuilders.standaloneSetup(movimientoController).build(); } @Test void getByNombreSeEjecutaYNombreExisteDebeRetornarMovimiento() throws Exception { //given Movement move= new Movement(); move.setId(1); move.setName("Absorb"); move.setType("Grass"); move.setCategory("Special"); move.setPower(20); move.setAccuracy(100); move.setPp(25); move.setEffect("User recovers half the HP inflicted on opponent."); given(movementService.findByName("Absorb")).willReturn(move); //when MockHttpServletResponse response = mockMvc.perform(get("/api/pocketo/moves/Absorb") .accept(MediaType.APPLICATION_JSON)) .andReturn() .getResponse(); //Then assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(response.getContentAsString()).isEqualTo( jsonMovement.write(move).getJson() ); } @Test void getByNombreSeEjecutaYNombreNoExisteDebeRetornar404() throws Exception { given(movementService.findByName("Absorb")).willReturn(null); //when MockHttpServletResponse response = mockMvc.perform(get("/api/pocketo/moves/Absorb") .accept(MediaType.APPLICATION_JSON)) .andReturn() .getResponse(); //Then assertThat(response.getStatus()).isEqualTo(404); } }
true
2e890837ccba74f81eca61c667251a230424eae9
Java
bopzjy/Tetris
/src/tetris/common/TheMagicBegin.java
UTF-8
736
2.296875
2
[]
no_license
package tetris.common; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import tetris.net.Server_test; import tetris.ui.activity.LoadActivity; public class TheMagicBegin { public static void main(String[] args) { if(!isPortUsing("127.0.0.1", 9999)){ Server_test.main(null); }else{ GlobalConstants.CLIENT_PORT = 1112; } LoadActivity.main(null); } public static boolean isPortUsing(String host,int port){ boolean flag = false; try { InetAddress theAddress = InetAddress.getByName(host); new Socket(theAddress,port); flag = true; } catch (Exception e) {} return flag; } }
true
bf1228846bddfbff7aab1e224144045b13824041
Java
danyfel80/icy-bigimage
/BigImageTools/src/main/java/plugins/danyfel80/bigimage/io/SaveBigImage.java
UTF-8
3,661
2.140625
2
[ "MIT" ]
permissive
package plugins.danyfel80.bigimage.io; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.PathMatcher; import algorithms.danyfel80.io.sequence.large.LargeSequenceExporter; import algorithms.danyfel80.io.sequence.large.LargeSequenceExporterException; import algorithms.danyfel80.io.sequence.tileprovider.IcyBufferedImageTileProvider; import icy.common.listener.DetailedProgressListener; import icy.sequence.MetaDataUtil; import icy.sequence.Sequence; import icy.system.IcyHandledException; import loci.formats.ome.OMEXMLMetadata; import plugins.adufour.blocks.lang.Block; import plugins.adufour.blocks.util.VarList; import plugins.adufour.ezplug.EzPlug; import plugins.adufour.ezplug.EzStoppable; import plugins.adufour.ezplug.EzVarFile; import plugins.adufour.ezplug.EzVarSequence; /** * This class allows to save a big image using tiles. * * @author Daniel Felipe Gonzalez Obando */ public class SaveBigImage extends EzPlug implements EzStoppable, Block { private EzVarSequence sequenceVar; private EzVarFile fileVar; private Sequence sequence; private Path filePath; private OMEXMLMetadata metadata; private DetailedProgressListener progressListener; @Override protected void initialize() { sequenceVar = new EzVarSequence("Sequence"); fileVar = new EzVarFile("File", null); addEzComponent(sequenceVar); addEzComponent(fileVar); } @Override public void declareInput(VarList inputMap) { sequenceVar = new EzVarSequence("Sequence"); fileVar = new EzVarFile("File", null); inputMap.add(sequenceVar.name, sequenceVar.getVariable()); inputMap.add(fileVar.name, fileVar.getVariable()); } @Override public void declareOutput(VarList outputMap) { } @Override protected void execute() { getParameters(); exportSequence(); } private void getParameters() { sequence = sequenceVar.getValue(true); filePath = fileVar.getValue(true).toPath(); PathMatcher extensionMatcher = FileSystems.getDefault().getPathMatcher("glob:*.ome.tiff"); if (!extensionMatcher.matches(filePath.getFileName())) { filePath = filePath.resolveSibling(filePath.getFileName() + ".ome.tiff"); } } private void exportSequence() { try (LargeSequenceExporter exporter = new LargeSequenceExporter()) { createMetadata(); exporter.setOutputImageMetadata(metadata); exporter.setOutputFilePath(filePath); exporter.setTileProvider(new IcyBufferedImageTileProvider(sequence.getFirstImage())); if (!isHeadLess()) exporter.addProgressListener(getProgressListener()); exporter.write(); } catch (Exception e) { e.printStackTrace(); throw new IcyHandledException(e); } finally { } } private void createMetadata() throws LargeSequenceExporterException { metadata = LargeSequenceExporter.createMetadata(sequence.getSizeX(), sequence.getSizeY(), sequence.getSizeC(), sequence.getDataType_()); MetaDataUtil.setName(metadata, 0, sequence.getName()); MetaDataUtil.setPixelSizeX(metadata, 0, sequence.getPixelSizeX()); MetaDataUtil.setPixelSizeY(metadata, 0, sequence.getPixelSizeY()); for (int channel = 0; channel < sequence.getSizeC(); channel++) { MetaDataUtil.setPositionX(metadata, 0, 0, 0, channel, sequence.getPositionX()); MetaDataUtil.setPositionY(metadata, 0, 0, 0, channel, sequence.getPositionY()); } } private DetailedProgressListener getProgressListener() { if (progressListener == null) { progressListener = (double progress, String message, Object data) -> { this.getUI().setProgressBarMessage(message); this.getUI().setProgressBarValue(progress); return false; }; } return progressListener; } @Override public void clean() { } }
true
6772cc05c4aa99e699dbf90d427892b5e529406d
Java
Mernoa/Obligatorio1
/src/Obligatorio/Ficha.java
UTF-8
958
2.59375
3
[]
no_license
package Obligatorio; public class Ficha { private String id; private String color; private int valor; private int posicionFila; private int posicionColumna; public Ficha(String id, int valor, int jugador) { this.id = id; this.valor = valor; this.color = color; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getColor() { return this.color; } public void setColor(String color) { this.color = color; } public int getValor() { return valor; } public void setValor(int valor) { this.valor = valor; } public int getPosicionFila() { return posicionFila; } public void setFila(int posicionFila) { this.posicionFila = posicionFila; } public int getColumna() { return posicionColumna; } public void setColumna(int posicionColumna) { this.posicionColumna = posicionColumna; } @Override public String toString() { return id; } }
true
09e88fd1d4771e34569fec42c0a516d3b3bc1e2b
Java
MarkNBroadhead/MinecraftModManager
/src/main/java/app/ModUpdater.java
UTF-8
1,343
2.890625
3
[ "MIT" ]
permissive
package app; import java.io.IOException; public class ModUpdater { public static void updateMods() throws RuntimeException { updateGitRepo(); try { if (!Utils.isMinecraftRunning()) { Utils.deleteOldMods(); Utils.addNewMods(); } else { throw Log.logAndReturnException("Cannot update mods while Minecraft is running. Please shut down Minecraft to continue"); } } catch (IOException ex) { throw Log.logAndReturnException("Issue updating mods", ex); } } private static void updateGitRepo() { if (!Git.modRepoExists()) { try { Git.cloneModRepo(); } catch (IOException ex) { throw Log.logAndReturnException("Cannot clone mod repo", ex); } catch (InterruptedException ex) { throw Log.logAndReturnException("Repository clone interrupted", ex); } } else { try { Git.fetchNewestMods(); } catch (IOException ex) { throw Log.logAndReturnException("Cannot update mod repo", ex); } catch (InterruptedException ex) { throw Log.logAndReturnException("Repository update interrupted", ex); } } } }
true
512571d017bb0e8756dcded7384d85ea6a599456
Java
gailo22/myproject
/src/main/java/myproject/clientserver/FileServer.java
UTF-8
2,100
2.921875
3
[]
no_license
package myproject.clientserver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Paths; public class FileServer { private static void run(ServerSocket socket, File rootDir) throws IOException { while (true) { Socket s = socket.accept(); new Thread(() -> { InputStream in = null; OutputStream out = null; try { in = s.getInputStream(); out = s.getOutputStream(); InputStreamReader reader = new InputStreamReader(in); BufferedReader buffered = new BufferedReader(reader); // String line = buffered.readLine(); // assert line != null; // assert line.startsWith("GET"); // // String path = line.split(" ")[1]; // File fullPath = new File(rootDir, path); PrintWriter printer = new PrintWriter(out); printer.write("hello from server"); // if (fullPath.isFile()) { // printer.write("HTTP/1.0 200 OK\r\n"); // printer.write("\r\n"); // printer.write("\r\n"); // printer.write(new String(Files.readAllBytes(fullPath.toPath())) + "\r\n"); // } else { // printer.write("HTTP/1.0 404 Not Found\r\n"); // printer.write("\r\n"); // printer.write("\r\n"); // } printer.close(); } catch (IOException io) { io.printStackTrace(); throw new RuntimeException(io); } finally { try { in.close(); } catch (Exception e) {} try { out.close(); } catch (Exception e) {} } }).start(); } } public static void main(String[] args) { try { ServerSocket socket = new ServerSocket(8888); socket.setReuseAddress(true); System.out.println("Server started at port: " + socket.getLocalPort()); FileServer.run(socket, Paths.get("D:\\tmp").toFile()); } catch (IOException e) { e.printStackTrace(); } } }
true
d1d3f66f245ef07ce2add114031ecd93a6add738
Java
yue-wen/doc2graph
/couchbase-neo4j-connector/src/main/java/com/couchbase/client/neo4j/conf/Neo4jSyncConfManager.java
UTF-8
1,288
1.773438
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/** * Copyright (c) 2017 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.couchbase.client.neo4j.conf; /** * Expose neo4j-sync configuration * * @author Omar Rampado * */ public interface Neo4jSyncConfManager { /** * couchbase.hostname * @return */ String getCouchbaseHostname(); /** * couchbase.bucket * @return */ String getCouchbaseBucket(); /** * neo4j.hostname * @return */ String getNeo4jHostname(); /** * neo4j.username * @return */ String getNeo4jUsername(); /** * neo4j.password * @return */ String getNeo4jPassword(); }
true
5be8c5a1c38762ee91187ffc33a3d9499d9a7811
Java
vanillasky/dsma
/src/main/java/kr/co/datastreams/dsma/model/CharType.java
UTF-8
373
2.359375
2
[]
no_license
package kr.co.datastreams.dsma.model; /** * * User: shkim * Date: 13. 7. 22 * Time: 오후 12:57 * */ public enum CharType { SPACE(0), HANGUL(1), HANJA(2), ALPHABET(3), NUMBER(4), SYMBOL(5), COMBINED(6), EMOTICON(7), ETC(8), FILTERED(100) ; private int value; private CharType(int i) { value = i; } }
true
a23ad3f70fa953c7650f554a573e174f827b0eab
Java
yks095/SolvingProb
/src/chapter/ch1/Q27.java
UTF-8
942
3.28125
3
[]
no_license
package chapter.ch1; import java.util.Arrays; import java.util.Random; public class Q27 { public static void main(String[] args) { int[] N = new int[9]; int[] score = new int[9]; Random random = new Random(); for(int i = 0; i < N.length; i++) { N[i] = random.nextInt(10); } Arrays.sort(N); for(int i = 0; i < N.length/2; i++) { int temp = N[i]; N[i] = N[N.length - 1- i]; N[N.length - 1- i] = temp; } score[0] = 1; for(int i = 1; i < N.length; i++) { if(N[i] < N[i - 1]) score[i] = score[i - 1] + 1; else if(N[i] == N[i - 1]) { score[i] = score[i - 1]; continue; } } System.out.println("배열 : " + Arrays.toString(N)); System.out.println("순위 : " + Arrays.toString(score)); } }
true
3c22007684843a9f9e5db8ef8a454eb045aad5f9
Java
MRROOX/TheUltimateMicroServicesTemplate
/Stegeriluminacion/micro-auth/src/main/java/micro/auth/services/interfaces/ACrud.java
UTF-8
2,792
2.359375
2
[ "Apache-2.0" ]
permissive
package micro.auth.services.interfaces; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import dto.main.Respuesta; import steger.excepciones.controladas.ErrorInternoControlado; @Scope(proxyMode = ScopedProxyMode.INTERFACES) @Transactional public abstract class ACrud<T extends Serializable> { @PersistenceContext EntityManager entityManager; @SuppressWarnings("unchecked") private Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; Logger logger = LoggerFactory.getLogger(clazz); public Respuesta<T> obtener(final Long id) { final Respuesta<T> respuesta = new Respuesta<T>(); T objeto = entityManager.find(clazz, id); respuesta.setCodigo(200); respuesta.setCodigoHttp(200); respuesta.setCuerpo(objeto); respuesta.setEstado(true); respuesta.setMensaje("obtenido"); return respuesta; } @SuppressWarnings("unchecked") public Respuesta<List<T>> obtenerTodos() { final Respuesta<List<T>> respuesta = new Respuesta<List<T>>(); try { List<T> datos = entityManager.createQuery("from " + clazz.getName()).getResultList(); respuesta.setCodigo(200); respuesta.setCodigoHttp(200); respuesta.setCuerpo(datos); respuesta.setEstado(true); respuesta.setMensaje("obtenidos"); return respuesta; } catch (Exception ex) { return ErrorInternoControlado.error(ex.getMessage()); } } public Respuesta<T> crear(final T objeto) { final Respuesta<T> respuesta = new Respuesta<T>(); entityManager.persist(objeto); entityManager.flush(); respuesta.setCodigo(200); respuesta.setCodigoHttp(200); respuesta.setCuerpo(objeto); respuesta.setEstado(true); respuesta.setMensaje("creado"); return respuesta; } public Respuesta<T> actualizar(final T objeto) { final Respuesta<T> respuesta = new Respuesta<T>(); entityManager.merge(objeto); entityManager.flush(); respuesta.setCodigo(200); respuesta.setCodigoHttp(200); respuesta.setCuerpo(objeto); respuesta.setEstado(true); respuesta.setMensaje("actualizado"); return respuesta; } public Respuesta<Boolean> eliminar(final long id) { final Respuesta<Boolean> respuesta = new Respuesta<Boolean>(); T objeto = entityManager.find(clazz, id); entityManager.remove(objeto); respuesta.setCodigo(200); respuesta.setCodigoHttp(200); respuesta.setCuerpo(true); respuesta.setEstado(true); respuesta.setMensaje("eliminado"); return respuesta; } }
true
cfcac93c501fc668cba12743efc02b6547cc1311
Java
safayat/MyTemplate
/src/main/java/com/dtr/oas/config/WebAppConfig.java
UTF-8
1,942
1.96875
2
[]
no_license
package com.dtr.oas.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.text.DateFormat; import java.text.SimpleDateFormat; @Configuration @EnableWebMvc @EnableScheduling @ComponentScan("com.dtr.oas") public class WebAppConfig extends WebMvcConfigurerAdapter { /* @Bean public UrlBasedViewResolver setupViewResolver() { UrlBasedViewResolver resolver = new UrlBasedViewResolver(); resolver.setPrefix(""); resolver.setSuffix(".html"); resolver.setViewClass(JstlView.class); return resolver; } */ @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } // Maps resources path to webapp/resources public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations( "/resources/"); } // Provides internationalization of messages @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource source = new ResourceBundleMessageSource(); source.setBasename("messages"); return source; } @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); final DateFormat df = new SimpleDateFormat("yyyy-mm-dd"); mapper.setDateFormat(df); return mapper; } }
true
6849d58fc8da9786880757c8ee231a732a702b19
Java
ntmanh2112/sem2-112011
/Users/Nguyen Thanh Huy/Distributed Computing in Java/Assingment1/src/view/_14UpdatePharmacy.java
UTF-8
3,606
2.75
3
[]
no_license
package view; import java.awt.Container; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class _14UpdatePharmacy extends JFrame { public JLabel lblName, lblCountry, lblManufacturer, lblFormula, lblUsing, lblUnit, lblStatus, lblQuantity, lblPrice; public JComboBox cbbName, cbbCountry, cbbUnit, cbbStatus; public JTextField txtManufacturer, txtFormula, txtUsing, txtQuantity, txtPrice; public JButton btnUpdate, btnCancel; public _14UpdatePharmacy() { setDefaultCloseOperation(EXIT_ON_CLOSE); initComponents(); } private void initComponents() { Container c = this.getContentPane(); this.setTitle("Update Pharmacy"); this.setSize(600, 600); this.setLayout(null); //NAME lblName = new JLabel("Name: "); lblName.setSize(150, 20); lblName.setLocation(50, 100); c.add(lblName); cbbName = new JComboBox(); cbbName.setSize(300, 25); cbbName.setLocation(150, 100); c.add(cbbName); //COUNTRY lblCountry = new JLabel("Country: "); lblCountry.setSize(150, 20); lblCountry.setLocation(50, 150); c.add(lblCountry); cbbCountry = new JComboBox(); cbbCountry.setSize(300, 25); cbbCountry.setLocation(150, 150); c.add(cbbCountry); //MANUFACTURER lblManufacturer = new JLabel("Manufacturer: "); lblManufacturer.setSize(150, 20); lblManufacturer.setLocation(50, 200); c.add(lblManufacturer); txtManufacturer = new JTextField(); txtManufacturer.setSize(300, 25); txtManufacturer.setLocation(150, 200); c.add(txtManufacturer); //FOMULA lblFormula = new JLabel("Formula: "); lblFormula.setSize(150, 20); lblFormula.setLocation(50, 250); c.add(lblFormula); txtFormula = new JTextField(); txtFormula.setSize(300, 25); txtFormula.setLocation(150, 250); c.add(txtFormula); //USING lblUsing = new JLabel("Using: "); lblUsing.setSize(150, 20); lblUsing.setLocation(50, 300); c.add(lblUsing); txtUsing = new JTextField(); txtUsing.setSize(300, 25); txtUsing.setLocation(150, 300); c.add(txtUsing); //UNIT lblUnit = new JLabel("Unit: "); lblUnit.setSize(150, 20); lblUnit.setLocation(50, 350); c.add(lblUnit); cbbUnit = new JComboBox(); cbbUnit.setSize(100, 25); cbbUnit.setLocation(150, 350); c.add(cbbUnit); //STATUS lblStatus = new JLabel("Status: "); lblStatus.setSize(150, 20); lblStatus.setLocation(300, 350); c.add(lblStatus); cbbStatus = new JComboBox(); cbbStatus.setSize(100, 25); cbbStatus.setLocation(350, 350); c.add(cbbStatus); //UNIT lblQuantity = new JLabel("Quantity: "); lblQuantity.setSize(150, 20); lblQuantity.setLocation(50, 400); c.add(lblQuantity); txtQuantity = new JTextField(); txtQuantity.setSize(100, 25); txtQuantity.setLocation(150, 400); c.add(txtQuantity); //PRICE lblPrice = new JLabel("Price: "); lblPrice.setSize(150, 20); lblPrice.setLocation(300, 400); c.add(lblPrice); txtPrice = new JTextField(); txtPrice.setSize(100, 25); txtPrice.setLocation(350, 400); c.add(txtPrice); //BUTTONS btnUpdate = new JButton("Update"); btnUpdate.setSize(100, 25); btnUpdate.setLocation(190, 450); c.add(btnUpdate); btnCancel = new JButton("Cancel"); btnCancel.setSize(100, 25); btnCancel.setLocation(310, 450); c.add(btnCancel); this.setVisible(true); } public static void main(String[] args) { new _14UpdatePharmacy(); } }
true
741c022fa94d225fb9eedff9ad8dcb1490b704c1
Java
KashaRavi/leetcode
/hackerrank/src/main/java/twoRobots/solution.java
UTF-8
2,317
3.0625
3
[]
no_license
package twoRobots; import java.util.Scanner; /** * @author rkasha */ public class solution { public static class Path{ int a; int b; Path(int a, int b) { this.a = a; this.b = b; } } public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc = new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++){ int m=sc.nextInt(); int n = sc.nextInt(); Path[] queries = new Path[n]; for(int j=0;j<n;j++){ int a = sc.nextInt(); int b = sc.nextInt(); queries[j] = new Path(a,b); } int minDist = Integer.MAX_VALUE; for(int k = 1; k<n;k++){ int r1Dist = Math.abs(queries[0].b-queries[0].a); int r1Node = queries[0].b; int prevb = queries[0].b; for(int l=1;l<k;l++){ r1Dist +=Math.abs(prevb-queries[l].a)+Math.abs(queries[l].b-queries[l].a); prevb = queries[l].b; r1Node=prevb; } int totalDist = r1Dist + Math.abs(queries[k].b-queries[k].a); int r2Node = queries[k].b; for(int p = k+1;p<n;p++){ if(Math.abs(queries[p].a -r1Node) <= Math.abs(queries[p].a -r2Node)){ totalDist += Math.abs(queries[p].a -r1Node); totalDist += Math.abs(queries[p].a -queries[p].b); r1Node = queries[p].b; } else { totalDist += Math.abs(queries[p].a -r2Node); totalDist += Math.abs(queries[p].a -queries[p].b); r2Node = queries[p].b; } } System.out.println("k= "+k+"dist="+totalDist); if(minDist > totalDist ){ minDist = totalDist; } } System.out.println(minDist); } } }
true
d528fa175ce5d6fb82f42147105b59c43faf0c43
Java
iafboy/WeiXin
/src/com/popolongStudio/app/util/MessageConvertHandler.java
UTF-8
5,298
2.3125
2
[]
no_license
package com.popolongStudio.app.util; import java.lang.reflect.Field; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.popolongStudio.app.common.ReturnCodeContent; import com.popolongStudio.app.module.ImageObj; import com.popolongStudio.app.module.LocationObj; import com.popolongStudio.app.module.PushObj; import com.popolongStudio.app.module.TextObj; import com.popolongStudio.app.module.VoiceObj; public class MessageConvertHandler { public boolean DEBUG = false; public PushObj ConvertPushMSG(String input) { Document doc = null; try { doc = DocumentHelper.parseText(input); } catch (Exception e) { if (DEBUG) e.printStackTrace(); } if (doc != null) { PushObj instance = CreatePushMsgInstance(doc); if (instance != null) return instance; } return null; } private PushObj CreatePushMsgInstance(Document doc) { Element root = doc.getRootElement(); if ("xml".equalsIgnoreCase(root.getName())) { Iterator Emts = root.elementIterator(); String MsgTypeValue = null; while (Emts.hasNext()) { if ((Emts != null)) { Element tagEmt = (Element) Emts.next(); if ("MsgType".equalsIgnoreCase(tagEmt.getName())) { MsgTypeValue = tagEmt.getText(); break; } } } if (MsgTypeValue != null && !"".equals(MsgTypeValue.trim())) { if ("text".equalsIgnoreCase(MsgTypeValue.trim().toLowerCase())) { return setValueInToObject(TextObj.class, doc); } else if ("voice".equalsIgnoreCase(MsgTypeValue.trim() .toLowerCase())) { return setValueInToObject(VoiceObj.class, doc); } else if ("image".equalsIgnoreCase(MsgTypeValue.trim() .toLowerCase())) { return setValueInToObject(ImageObj.class, doc); } else if ("location".equalsIgnoreCase(MsgTypeValue.trim() .toLowerCase())) { return setValueInToObject(LocationObj.class, doc); } else { return null; } } } return null; } private PushObj setValueInToObject(Class objClass, Document doc) { Element root = doc.getRootElement(); PushObj result = null; if (TextObj.class.getName().equals(objClass.getName())) { TextObj testObj = new TextObj(); testObj.setMsgType(ReturnCodeContent.ObjType.TEXT); testObj.setToUserName(getDocValue(root, "ToUserName")); testObj.setFromUserName(getDocValue(root, "FromUserName")); testObj.setCreateTime(new Long(getDocValue(root, "CreateTime"))); testObj.setMsgId(new Long(getDocValue(root, "MsgId"))); testObj.setContent(new StringBuffer(getDocValue(root, "Content"))); result = testObj; } else if (VoiceObj.class.getName().equals(objClass.getName())) { VoiceObj testObj = new VoiceObj(); testObj.setMsgType(ReturnCodeContent.ObjType.VOICE); testObj.setToUserName(getDocValue(root, "ToUserName")); testObj.setFromUserName(getDocValue(root, "FromUserName")); testObj.setCreateTime(new Long(getDocValue(root, "CreateTime"))); testObj.setMsgId(new Long(getDocValue(root, "MsgId"))); testObj.setFormat(getDocValue(root, "Format")); testObj.setMediaId(getDocValue(root, "MediaId")); result = testObj; } else if (ImageObj.class.getName().equals(objClass.getName())) { ImageObj testObj = new ImageObj(); testObj.setMsgType(ReturnCodeContent.ObjType.IMAGE); testObj.setToUserName(getDocValue(root, "ToUserName")); testObj.setFromUserName(getDocValue(root, "FromUserName")); testObj.setCreateTime(new Long(getDocValue(root, "CreateTime"))); testObj.setMsgId(new Long(getDocValue(root, "MsgId"))); testObj.setPicUrl(getDocValue(root, "PicUrl")); testObj.setMediaId(getDocValue(root, "MediaId")); result = testObj; } else if (LocationObj.class.getName().equals(objClass.getName())) { LocationObj testObj = new LocationObj(); testObj.setMsgType(ReturnCodeContent.ObjType.LOCATION); testObj.setToUserName(getDocValue(root, "ToUserName")); testObj.setFromUserName(getDocValue(root, "FromUserName")); testObj.setCreateTime(new Long(getDocValue(root, "CreateTime"))); testObj.setMsgId(new Long(getDocValue(root, "MsgId"))); testObj.setLabel(getDocValue(root, "Label")); testObj.setLocation_X(new Float(getDocValue(root, "Location_X"))); testObj.setLocation_Y(new Float(getDocValue(root, "Location_Y"))); testObj.setScale(new Integer(getDocValue(root, "Scale"))); result = testObj; } /* * Object obj=objClass.newInstance(); Field[] fields = * objClass.getDeclaredFields(); for (Field field : fields) { String * fieldText = root.elementText(field.getName()); * field.setAccessible(true); field.set(obj, fieldText); } */ return result; } private String getDocValue(Element root, String tag) { String result = null; if ("xml".equalsIgnoreCase(root.getName())) { Iterator Emts = root.elementIterator(); while (Emts.hasNext()) { if ((Emts != null)) { Element tagEmt = (Element) Emts.next(); String tagName = tagEmt.getName(); if (tagName != null && !"".equals(tagName) && tag.equalsIgnoreCase(tagName)) { result = tagEmt.getText(); //System.out.println(tag + " : " + result); break; } } } } return result; } }
true
75ff96c2b91fe13290ea14a32c71db778aaacc84
Java
wpqepoep/Queenbee
/app/src/main/java/com/top/queenbee/qbdetail.java
UTF-8
7,839
2.109375
2
[]
no_license
package com.top.queenbee; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class qbdetail extends AppCompatActivity { EditText ed1,edwarm,edeclosion,edmating,edenter,edpart; TextView t1; String name1; Button btn1; qbdatabase db; public static int RESULT_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qbdetail); db = new qbdatabase(this); SQLiteDatabase qbdatabase = db.getWritableDatabase();//設定資料庫 Intent intent = getIntent(); //取得傳入的 Intent 物件 Bundle bundlename = intent.getExtras(); name1 = bundlename.getString("subject"); t1 = findViewById(R.id.t1); ed1 = findViewById(R.id.ed1); t1.setText(name1); edwarm = findViewById(R.id.edwarm); edeclosion = findViewById(R.id.edeclosion); edmating = findViewById(R.id.edmating); edenter = findViewById(R.id.edenter); edpart = findViewById(R.id.edpart); btn1 = findViewById(R.id.btn1); btn1.setOnClickListener(Lsave); } private Button.OnClickListener Lsave = new Button.OnClickListener(){ @Override public void onClick(View v) { long l = -1; if(edwarm.getText().length() == 0 && edeclosion.getText().length() == 0 && edmating.getText().length() == 0 && edenter.getText().length() == 0 && edpart.getText().length() == 0){//here Toast.makeText(getApplicationContext(),"請輸入日期",Toast.LENGTH_SHORT).show(); }else{ if (edwarm.getText().length() == 0 && (!(edeclosion.getText().length() == 0) || !(edmating.getText().length() == 0) || !(edenter.getText().length() == 0) || !(edpart.getText().length() == 0))){ Toast.makeText(getApplicationContext(),"請按照順程序輸入時間",Toast.LENGTH_SHORT).show(); }else if (edwarm.getText().length() == 0 || edeclosion.getText().length() == 0 && ( !(edmating.getText().length() == 0) || !(edenter.getText().length() == 0) || !(edpart.getText().length() == 0))){ Toast.makeText(getApplicationContext(),"請按照順程序輸入時間",Toast.LENGTH_SHORT).show(); }else if (!(edwarm.getText().length() == 0) && edeclosion.getText().length() == 0 && edmating.getText().length() == 0 && edenter.getText().length() == 0 && edpart.getText().length() == 0 ){ String t1 = edwarm.getText().toString(); Date date1 = null; SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd"); format1.setLenient(false); Log.d("mylog", "t1: "+t1); try { date1 = format1.parse(t1); insertData(); backToqb(); }catch (Exception e) { Toast.makeText(qbdetail.this,"輸入格式錯誤",Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }else if (edwarm.getText().length() == 0 || edeclosion.getText().length() == 0 || edmating.getText().length() == 0 && (!(edenter.getText().length() == 0) || !(edpart.getText().length() == 0))){ Toast.makeText(getApplicationContext(),"請按照順程序輸入時間",Toast.LENGTH_SHORT).show(); }else{ String t1 = edwarm.getText().toString(); String t2 = edeclosion.getText().toString(); String t3 = edmating.getText().toString(); String t4 = edenter.getText().toString(); String t5 = edpart.getText().toString(); Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); format.setLenient(false); try { if (!t1.equals("") && !t2.equals("") && t3.equals("")){ date1 = format.parse(t1); date2 = format.parse(t2); insertData(); backToqb(); }else if (!t1.equals("") && !t2.equals("") && !t3.equals("") && t4.equals("")){ date1 = format.parse(t1); date2 = format.parse(t2); date3 = format.parse(t3); Log.d("mylog", "date3: "+date3); insertData(); backToqb(); }else if (!t1.equals("") && !t2.equals("") && !t3.equals("") && !t4.equals("") && t5.equals("")){ date1 = format.parse(t1); date2 = format.parse(t2); date3 = format.parse(t3); date4 = format.parse(t4); insertData(); backToqb(); }else if (!t1.equals("") && !t2.equals("") && !t3.equals("") && !t4.equals("") && !t5.equals("")){ date1 = format.parse(t1); date2 = format.parse(t2); date3 = format.parse(t3); date4 = format.parse(t4); date5 = format.parse(t5); insertData(); backToqb(); } }catch(Exception e) { Toast.makeText(qbdetail.this, "輸入格式錯誤", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } } } }; public void insertData(){ long l = -1; Date date = new Date(); int d = Integer.parseInt((String) android.text.format.DateFormat.format("yyyyMMdd",date)); if (ed1.getText().length()==0){ Toast.makeText(getApplicationContext(),"請輸入名稱",Toast.LENGTH_SHORT).show(); }else{ l = db.insertData(ed1.getText().toString(),edwarm.getText().toString(),edeclosion.getText().toString(), edmating.getText().toString(),edmating.getText().toString(),edpart.getText().toString(),d,name1); Log.d("mylog", "l: "+l); if(l>=0){ Toast.makeText(getApplicationContext(),"紀錄成功",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "紀錄失敗", Toast.LENGTH_SHORT).show(); } } } public void backToqb() { Intent intent1 = new Intent(qbdetail.this,queenbee.class); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); setResult(RESULT_CODE,intent1); finish(); } }
true
965139d5c0676a26d759cb055159f5bce60c39f4
Java
micobery/Calendar4Test
/src/main/java/com/uniqmaster/calendar4test/dto/EmailNotifyEvent.java
UTF-8
530
2.015625
2
[]
no_license
package com.uniqmaster.calendar4test.dto; import com.uniqmaster.calendar4test.entity.Course; import com.uniqmaster.calendar4test.entity.Event; import lombok.Getter; import lombok.Setter; import org.springframework.context.ApplicationEvent; @Setter @Getter public class EmailNotifyEvent extends ApplicationEvent { private Course course; private Event event; public EmailNotifyEvent(Object source, Course course, Event event) { super(source); this.event = event; this.course = course; } }
true
231dd8663af29bccea6543eb289c9e9ea03a30e8
Java
walterll/Algorithm
/src/com/leetcode/Question4.java
UTF-8
2,222
3.734375
4
[]
no_license
package com.leetcode; import java.util.Arrays; /****************************** * There are two sorted arrays nums1 and nums2 of size m and n respectively. * Find the median of the two sorted arrays. The overall run time complexity * should be O(log (m+n)). * * Example 1: * nums1 = [1, 3] * nums2 = [2] * The median is 2.0 * * Example 2: * nums1 = [1, 2] * nums2 = [3, 4] * The median is (2 + 3)/2 = 2.5 * @author Walterll * */ public class Question4 { /************* * 第一版,未看清题意,使用java自带的快排 * 复杂度为(m+n)log(m+n),未达到要求 * 其实给的两组数组已经排序了 * @param nums1 * @param nums2 * @return */ // public double findMedianSortedArrays(int[] nums1, int[] nums2) { // double median = 0; // int size = nums1.length + nums2.length; // int[] num = new int[size]; // for (int i = 0; i < size; i++) { // if (i < nums1.length) // num[i] = nums1[i]; // else // num[i] = nums2[i - nums1.length]; // } // Arrays.sort(num); // if ((size % 2) == 0) // median = (double)(num[size / 2 - 1] + num[size / 2]) / 2; // else // median = num[(size) / 2]; // return median; // } public double findMedianSortedArrays(int[] nums1, int[] nums2) { int size = nums1.length + nums2.length; int midIndice = 0; //中位数下标 if ((size % 2) == 0) midIndice = size / 2 - 1; else midIndice = size / 2; int num1Indice, num2Indice = 0; double median = 0; return median; } private double findMedian(int[] nums1, int[] nums2, int midIndice, int num1Indice, int num2Indice) { if (???) return ??? ; if (nums1[num1Indice] > nums2[num2Indice]) findMedian(nums1, nums2, midIndice, num1Indice, (nums2.length - num2Indice) / 2); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] nums1 = new int[]{1,2,4,6,13}; int[] nums2 = new int[]{3,5,11,22}; Question4 q = new Question4(); System.out.println(q.findMedianSortedArrays(nums1, nums2)); } }
true
4a949d01802840e90b945080087550d7b088ec71
Java
DOMINATORS2021/KidZoneB
/src/main/java/tn/esprit/kidzone/repository/ReclamationRepository.java
UTF-8
299
1.53125
2
[]
no_license
package tn.esprit.kidzone.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import tn.esprit.kidzone.entity.Reclamation; @Repository public interface ReclamationRepository extends CrudRepository<Reclamation, Integer> { }
true
48175da2ea19c3619d39f063e62afec1741c691c
Java
rockdam/dogdog
/app/src/main/java/com/makeus/dogdog/src/HomeDogDog/MypageFragment/interfaces/MypageView.java
UTF-8
304
1.8125
2
[]
no_license
package com.makeus.dogdog.src.HomeDogDog.MypageFragment.interfaces; import com.makeus.dogdog.src.HomeDogDog.MypageFragment.models.MyPageRanking; import com.makeus.dogdog.src.HomeDogDog.MypageFragment.models.MyPageResponse; public interface MypageView { void refresh(MyPageRanking myPageRanking); }
true
3baf249978f747e3463cc812fa40d3a6d82e282b
Java
MatthieuDJ/api_training
/src/main/java/fr/esiea/ex4A/FakeTinder/MatchResponse.java
UTF-8
383
2.4375
2
[]
no_license
package fr.esiea.ex4A.FakeTinder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MatchResponse extends ArrayList<Match> { public MatchResponse(List<Match> matches){ super(); this.addAll(matches); } public MatchResponse(Match... matches){ super(); this.addAll(Arrays.asList(matches)); } }
true
35eb3b344dc9b31ad50e066e1e9546b5d5d63cbe
Java
LufanZhang/Leetcode
/src/google/IntegerToRoman.java
UTF-8
709
3.640625
4
[]
no_license
package google; public class IntegerToRoman { public String intToRoman(int num) { int[] values = {1,4,5,9,10,40,50,90,100,400,500,900,1000}; String[] romans = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"}; StringBuilder sb = new StringBuilder(); if(num <= 0){ return sb.toString(); } int start = values.length-1; while(start >= 0 && num > 0){ if(values[start] > num){ start--; continue; } else{ sb.append(romans[start]); num -= values[start]; } } return sb.toString(); } }
true
9e0ea71f5975932cd6c077341719229e49ff9b4d
Java
saphyron/randomstuff
/Java/Semester 1 usorteret/Lektion14/src/opgave1dobbelArray/Opgave1DobbelArray.java
UTF-8
2,072
3.609375
4
[]
no_license
package opgave1dobbelArray; public class Opgave1DobbelArray { public static void main(String[] args) { final int ROW = 8; final int COL = 8; int[][] values = new int[ROW][COL]; DobbelArray da = new DobbelArray(); //Udskriv values på tabel form da.udskrivArray(values); // TODO Opgave 1.1 lav ændringer i values så der står 5 på alle pladser for (int i =0; i < values.length; i++) { for (int j = 0; j < values[0].length; j++) { } } System.out.println(); System.out.println("Nedenfor skulle der stå 5 på alle pladser"); System.out.println(); da.udskrivArray(values); // TODO Opgave 1.2 lav ændringer i values så der står 2 i lige rækker og 3 i ulige System.out.println(); System.out.println("Nedenfor skulle der stå 2 og 3 på hver anden række"); System.out.println(); da.udskrivArray(values); // TODO Opgave 1.3 lav ændringer i values så der står 2 i lige søjler og 3 i ulige System.out.println(); System.out.println("Nedenfor skulle der stå 2 og 3 på hver anden søjle"); System.out.println(); da.udskrivArray(values); // TODO Opgave 1.4 lav ændringer i values så den har skiftende 0'er og 1'er som på et // skakbræt System.out.println(); System.out.println("Nedenfor skulle der stå 0 og 1 på alle pladser som på skakbræt"); System.out.println(); da.udskrivArray(values); // TODO Opgave 1.5 lav ændringer så alle elementer i nederste og øverste række samt første // og sidste søjle er 5 og resten skal være 2. System.out.println(); System.out.println("Nedenfor skulle der stå 5 i kanten og 2 ellers"); System.out.println(); da.udskrivArray(values); // TODO Opgave 1.6 beregn summen af alle tallene i values og udskriv denne. } }
true
e903b1e0ca96e0befd64e5740cf06ec83fcd0777
Java
TeamBiscochito/proyectofinal
/app/src/main/java/teambiscochito/toptrumpsgame/model/room/dao/CardDao.java
UTF-8
2,152
2.453125
2
[]
no_license
/* * Copyright (c) 2021. Team Biscochito. * * Licensed under the GNU General Public License v3.0 * * https://www.gnu.org/licenses/gpl-3.0.html * * Permissions of this strong copyleft license are conditioned on making available complete * source code of licensed works and modifications, which include larger works using a licensed * work, under the same license. Copyright and license notices must be preserved. Contributors * provide an express grant of patent rights. */ package teambiscochito.toptrumpsgame.model.room.dao; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import java.util.List; import teambiscochito.toptrumpsgame.model.room.pojo.Card; /** * <h2 align="center">Team Biscochito</h2><hr> * <p> * Interfaz room para la carta, donde generamos la tabla y las consultas pertinentes. */ @SuppressWarnings("UnusedReturnValue") // Comente la línea de arriba para ver los métodos que no usen su retorno de valor @Dao public interface CardDao { @Delete int delete(Card card); @Insert long insert(Card card); @Update void update(Card card); /** * @param id id de la carta para obtener la carta * * @return Get one card */ @Query("select * from card where id = :id") Card getById(long id); /** * @param name name of the card and we got the * * @return Get one card */ @Query("select id from card where name = :name") Long getIdByName(String name); /** * @param nombre nombre de la carta que queremos obtener * * @return Get the card with the name */ @Query("select * from card where name = :nombre") int getNameFromNameCarta(String nombre); /** * @return Get all cards */ @Query("select * from card") LiveData<List<Card>> getAll(); @Query("delete from card") void deleteAll(); @Query("delete from card where id = :id") void deleteById(long id); @Query("select * from card where name = :name") Card getCardByName(String name); }
true
245e9c76f41f9f49d0d7530747698e84809a5738
Java
gracet9182/Revamping-GreenLab
/app/src/main/java/com/example/green/RecylableItem.java
UTF-8
764
2.78125
3
[]
no_license
package com.example.green; public class RecylableItem { private String name; private String type; private boolean recylable; public RecylableItem(String name, String type, boolean recylable) { this.name = name; this.type = type; this.recylable = recylable; } public RecylableItem() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isRecylable() { return recylable; } public void setRecylable(boolean recylable) { this.recylable = recylable; } }
true
fb6dbb6a3f3e4bf0f144c9b8b4c7ba429cefb2cf
Java
abhishek09091/competitive-programming
/Company Wise Practice/Goldman Sachs/ugly-numbers-not-optimized.java
UTF-8
1,047
3.8125
4
[]
no_license
/*package whatever //do not write package name here */ /********* https://www.geeksforgeeks.org/ugly-numbers/ *********/ import java.util.*; import java.lang.*; import java.io.*; class GFG { public static int maxDivide(Integer a,Integer b){ while(a%b == 0){ a /=b; } return a; } public static boolean isUgly(Integer i){ i = maxDivide(i,2); i = maxDivide(i,3); i = maxDivide(i,5); return (i == 1) ? true : false; } public static int nthUgly(Integer n){ int count = 1; int i = 1; while(n > count){ i++; if(isUgly(i)){ count++; } } return i; } public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); Integer t = sc.nextInt(); while(t-- > 0){ Integer n = sc.nextInt(); System.out.println(nthUgly(n)); } sc.close(); } }
true
5a057717946f8243efecaade307bc54e2e12f119
Java
karl-liang/person
/cnicg-code-gui/src/main/java/com/sciov/cnicg/code/gui/view/CnicgProducer.java
UTF-8
20,312
2.046875
2
[]
no_license
package com.sciov.cnicg.code.gui.view; import java.awt.EventQueue; import javax.swing.JFrame; import java.awt.GridLayout; import javax.swing.JPanel; import java.awt.GridBagLayout; import javax.swing.JTree; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.Toolkit; import java.util.Date; import java.util.List; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sciov.cnicg.code.gui.entity.CodeDevice; import com.sciov.cnicg.code.gui.entity.WorkPositionJob; import com.sciov.cnicg.code.gui.service.ICodeDeviceService; import com.sciov.cnicg.code.gui.service.impl.CodeDeviceServiceImpl; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.JScrollPane; import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeSelectionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.SimpleDateFormat; import java.awt.Color; import java.awt.Dimension; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.border.SoftBevelBorder; import javax.swing.border.BevelBorder; import java.awt.FlowLayout; import javax.swing.BoxLayout; import java.awt.BorderLayout; import javax.swing.SwingConstants; import java.awt.Font; import javax.swing.UIManager; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.SystemColor; public class CnicgProducer { private Logger logger = LoggerFactory.getLogger(CnicgProducer.class); private JFrame frame; private JTextField allCountValueField; private JTextField normalValueField; private JTextField errCountValue; private JTree deviceTree; private JTextArea codeView; boolean startMonitor = false; ICodeDeviceService codeDeviceService = CodeDeviceServiceImpl.getCodeDeviceService(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public void appendCodeContent(String content) { if(startMonitor) { if(codeDeviceService.updateDeviceStatus(content)) { String deviceName = codeDeviceService.getDeviceName(content); String print = String.format("%s 收到扫码设备 %s 发送的内容: %s",sdf.format(new Date()),deviceName,content ); codeView.append(print+"\n"); codeView.setCaretPosition(codeView.getText().length()); refresh(); } } } public static CnicgProducer producerWindows; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { String deviceFile = ""; producerWindows = new CnicgProducer(deviceFile); producerWindows.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); new Thread(new Runnable() { @Override public void run() { while(true) { if(CnicgProducer.producerWindows!= null && CnicgProducer.producerWindows.frame.isVisible()) { CnicgProducer.producerWindows.appendCodeContent("A," + System.currentTimeMillis()+"\r\n"); } try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } /** * Create the application. */ public CnicgProducer(String deviceFile) { codeDeviceService.setDeviceFile(deviceFile); initialize(); } public static final String SELECT_EVENT_ADD = "+"; private JTextField deviceNameTextField; private JTextField deviceIptextField; private JTextField targetValuetextField; private JTextField statusTextField; private JTextField infotextField; /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setTitle("产线扫码"); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { System.exit(1); } }); frame.setBounds(100, 100, 567, 586); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] {0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 0}; gridBagLayout.rowHeights = new int[]{0, 0}; gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE}; frame.getContentPane().setLayout(gridBagLayout); JPanel deviceListPanel = new JPanel(); deviceListPanel.setBackground(SystemColor.info); deviceListPanel.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null)); GridBagConstraints gbc_deviceListPanel = new GridBagConstraints(); gbc_deviceListPanel.weighty = 100.0; gbc_deviceListPanel.weightx = 20.0; gbc_deviceListPanel.gridwidth = 3; gbc_deviceListPanel.insets = new Insets(0, 0, 0, 5); gbc_deviceListPanel.fill = GridBagConstraints.BOTH; gbc_deviceListPanel.gridx = 0; gbc_deviceListPanel.gridy = 0; frame.getContentPane().add(deviceListPanel, gbc_deviceListPanel); deviceListPanel.setLayout(new GridLayout(1, 1, 0, 0)); deviceTree = new JTree(); deviceTree.setForeground(SystemColor.info); deviceTree.setFont(new Font("宋体", Font.PLAIN, 22)); deviceTree.setBackground(SystemColor.info); DefaultTreeCellRenderer treeCellRender = new DefaultTreeCellRenderer(); treeCellRender.setTextNonSelectionColor(Color.GRAY); treeCellRender.setTextSelectionColor(Color.RED); treeCellRender.setBackgroundNonSelectionColor(SystemColor.info); deviceTree.setCellRenderer(treeCellRender); deviceTree.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if(e.getKeyChar() == (KeyEvent.VK_DELETE)) { if(deviceTree.getSelectionPath() != null) { codeDeviceService.deleteDevice(deviceTree.getSelectionPath().getLastPathComponent().toString()); refreshDeviceList(); } } } }); deviceTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { deviceSelectEventHandler(e); } }); refreshDeviceList(); deviceListPanel.add(deviceTree); JPanel mainPanel = new JPanel(); GridBagConstraints gbc_mainPanel = new GridBagConstraints(); gbc_mainPanel.weighty = 100.0; gbc_mainPanel.weightx = 60.0; gbc_mainPanel.gridwidth = 8; gbc_mainPanel.insets = new Insets(0, 0, 0, 5); gbc_mainPanel.fill = GridBagConstraints.BOTH; gbc_mainPanel.gridx = 3; gbc_mainPanel.gridy = 0; frame.getContentPane().add(mainPanel, gbc_mainPanel); GridBagLayout gbl_mainPanel = new GridBagLayout(); gbl_mainPanel.columnWidths = new int[]{241, 0}; gbl_mainPanel.rowHeights = new int[] {131, 131, 0}; gbl_mainPanel.columnWeights = new double[]{0.0, Double.MIN_VALUE}; gbl_mainPanel.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE}; mainPanel.setLayout(gbl_mainPanel); JPanel staticPanel = new JPanel(); GridBagConstraints gbc_staticPanel = new GridBagConstraints(); gbc_staticPanel.weighty = 20.0; gbc_staticPanel.weightx = 100.0; gbc_staticPanel.fill = GridBagConstraints.BOTH; gbc_staticPanel.insets = new Insets(0, 0, 5, 0); gbc_staticPanel.gridx = 0; gbc_staticPanel.gridy = 0; mainPanel.add(staticPanel, gbc_staticPanel); staticPanel.setLayout(new GridLayout(4, 2, 0, 0)); JPanel allCountLabelPanel = new JPanel(); allCountLabelPanel.setBackground(Color.ORANGE); staticPanel.add(allCountLabelPanel); allCountLabelPanel.setLayout(new GridLayout(0, 1, 0, 0)); JLabel allCountLabel_1 = new JLabel("总扫码数:"); allCountLabel_1.setFont(new Font("宋体", Font.PLAIN, 22)); allCountLabel_1.setBackground(Color.WHITE); allCountLabelPanel.add(allCountLabel_1); JPanel allCountValuePanel = new JPanel(); allCountValuePanel.setBackground(Color.WHITE); staticPanel.add(allCountValuePanel); allCountValuePanel.setLayout(new GridLayout(0, 1, 0, 0)); allCountValueField = new JTextField(); allCountValueField.setFont(new Font("宋体", Font.PLAIN, 22)); allCountValueField.setForeground(Color.BLACK); allCountValueField.setBackground(Color.ORANGE); allCountValueField.setText("0"); allCountValuePanel.add(allCountValueField); allCountValueField.setColumns(10); JPanel normalCountLabelPanel = new JPanel(); normalCountLabelPanel.setBackground(Color.ORANGE); staticPanel.add(normalCountLabelPanel); normalCountLabelPanel.setLayout(new GridLayout(0, 1, 0, 0)); JLabel normalLabel = new JLabel("正常码数:"); normalLabel.setFont(new Font("宋体", Font.PLAIN, 22)); normalCountLabelPanel.add(normalLabel); JPanel normalCountValuePanel = new JPanel(); staticPanel.add(normalCountValuePanel); normalCountValuePanel.setLayout(new GridLayout(0, 1, 0, 0)); normalValueField = new JTextField(); normalValueField.setFont(new Font("宋体", Font.PLAIN, 22)); normalValueField.setForeground(Color.BLACK); normalValueField.setBackground(Color.ORANGE); normalValueField.setText("0"); normalCountValuePanel.add(normalValueField); normalValueField.setColumns(10); JPanel errCountLabelPanel = new JPanel(); errCountLabelPanel.setBackground(Color.ORANGE); staticPanel.add(errCountLabelPanel); errCountLabelPanel.setLayout(new GridLayout(0, 1, 0, 0)); JLabel errLable = new JLabel("异常码数:"); errLable.setFont(new Font("宋体", Font.PLAIN, 22)); errCountLabelPanel.add(errLable); JPanel errCountValuePanel = new JPanel(); staticPanel.add(errCountValuePanel); errCountValuePanel.setLayout(new GridLayout(0, 1, 0, 0)); errCountValue = new JTextField(); errCountValue.setFont(new Font("宋体", Font.PLAIN, 22)); errCountValue.setBackground(Color.ORANGE); errCountValue.setText("0"); errCountValuePanel.add(errCountValue); errCountValue.setColumns(10); JPanel targetLabelPanel = new JPanel(); targetLabelPanel.setBackground(Color.ORANGE); staticPanel.add(targetLabelPanel); targetLabelPanel.setLayout(new GridLayout(1, 0, 0, 0)); JLabel lblNewLabel = new JLabel("目标码数:"); lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 22)); targetLabelPanel.add(lblNewLabel); JPanel targetValuePanel = new JPanel(); targetValuePanel.setBackground(Color.ORANGE); staticPanel.add(targetValuePanel); targetValuePanel.setLayout(new GridLayout(0, 1, 0, 0)); targetValuetextField = new JTextField(); targetValuetextField.setText("0"); targetValuetextField.setBackground(Color.ORANGE); targetValuetextField.setFont(new Font("宋体", Font.PLAIN, 22)); targetValuePanel.add(targetValuetextField); targetValuetextField.setColumns(10); JPanel CodeViewPanel = new JPanel(); CodeViewPanel.setToolTipText(""); GridBagConstraints gbc_CodeViewPanel = new GridBagConstraints(); gbc_CodeViewPanel.weighty = 80.0; gbc_CodeViewPanel.weightx = 100.0; gbc_CodeViewPanel.fill = GridBagConstraints.BOTH; gbc_CodeViewPanel.gridx = 0; gbc_CodeViewPanel.gridy = 1; mainPanel.add(CodeViewPanel, gbc_CodeViewPanel); CodeViewPanel.setLayout(new GridLayout(1, 1, 0, 0)); JScrollPane scrollPane = new JScrollPane(); CodeViewPanel.add(scrollPane); codeView = new JTextArea(); codeView.setBackground(Color.BLACK); codeView.setForeground(Color.YELLOW); scrollPane.setViewportView(codeView); JPanel controlPanel = new JPanel(); GridBagConstraints gbc_controlPanel = new GridBagConstraints(); gbc_controlPanel.weighty = 100.0; gbc_controlPanel.weightx = 20.0; gbc_controlPanel.fill = GridBagConstraints.BOTH; gbc_controlPanel.gridx = 11; gbc_controlPanel.gridy = 0; frame.getContentPane().add(controlPanel, gbc_controlPanel); GridBagLayout gbl_controlPanel = new GridBagLayout(); gbl_controlPanel.columnWidths = new int[]{106, 0}; gbl_controlPanel.rowHeights = new int[]{54, 54, 54, 0, 0, 0, 0, 0, 0}; gbl_controlPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_controlPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE}; controlPanel.setLayout(gbl_controlPanel); JPanel panel = new JPanel(); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.fill = GridBagConstraints.BOTH; gbc_panel.insets = new Insets(0, 0, 5, 0); gbc_panel.gridx = 0; gbc_panel.gridy = 0; controlPanel.add(panel, gbc_panel); GridBagLayout gbl_panel = new GridBagLayout(); gbl_panel.columnWidths = new int[]{60, 0, 0}; gbl_panel.rowHeights = new int[]{15, 0, 0, 0, 0, 0}; gbl_panel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE}; gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE}; panel.setLayout(gbl_panel); JLabel label = new JLabel("工位任务:"); GridBagConstraints gbc_label = new GridBagConstraints(); gbc_label.insets = new Insets(0, 0, 5, 5); gbc_label.anchor = GridBagConstraints.NORTHWEST; gbc_label.gridx = 0; gbc_label.gridy = 0; panel.add(label, gbc_label); JLabel label_1 = new JLabel("工位名称:"); GridBagConstraints gbc_label_1 = new GridBagConstraints(); gbc_label_1.insets = new Insets(0, 0, 5, 5); gbc_label_1.anchor = GridBagConstraints.EAST; gbc_label_1.gridx = 0; gbc_label_1.gridy = 1; panel.add(label_1, gbc_label_1); deviceNameTextField = new JTextField(); GridBagConstraints gbc_deviceNameTextField = new GridBagConstraints(); gbc_deviceNameTextField.weightx = 100.0; gbc_deviceNameTextField.insets = new Insets(0, 0, 5, 0); gbc_deviceNameTextField.fill = GridBagConstraints.HORIZONTAL; gbc_deviceNameTextField.gridx = 1; gbc_deviceNameTextField.gridy = 1; panel.add(deviceNameTextField, gbc_deviceNameTextField); deviceNameTextField.setColumns(10); JLabel lblIp = new JLabel("设备IP:"); GridBagConstraints gbc_lblIp = new GridBagConstraints(); gbc_lblIp.anchor = GridBagConstraints.EAST; gbc_lblIp.insets = new Insets(0, 0, 5, 5); gbc_lblIp.gridx = 0; gbc_lblIp.gridy = 2; panel.add(lblIp, gbc_lblIp); deviceIptextField = new JTextField(); GridBagConstraints gbc_deviceIptextField = new GridBagConstraints(); gbc_deviceIptextField.insets = new Insets(0, 0, 5, 0); gbc_deviceIptextField.fill = GridBagConstraints.HORIZONTAL; gbc_deviceIptextField.gridx = 1; gbc_deviceIptextField.gridy = 2; panel.add(deviceIptextField, gbc_deviceIptextField); deviceIptextField.setColumns(10); JLabel label_3 = new JLabel("状态:"); GridBagConstraints gbc_label_3 = new GridBagConstraints(); gbc_label_3.anchor = GridBagConstraints.NORTHEAST; gbc_label_3.insets = new Insets(0, 0, 5, 5); gbc_label_3.gridx = 0; gbc_label_3.gridy = 3; panel.add(label_3, gbc_label_3); statusTextField = new JTextField(); GridBagConstraints gbc_statusTextField = new GridBagConstraints(); gbc_statusTextField.fill = GridBagConstraints.HORIZONTAL; gbc_statusTextField.anchor = GridBagConstraints.NORTH; gbc_statusTextField.insets = new Insets(0, 0, 5, 0); gbc_statusTextField.gridx = 1; gbc_statusTextField.gridy = 3; panel.add(statusTextField, gbc_statusTextField); statusTextField.setColumns(10); JLabel label_2 = new JLabel("描述:"); GridBagConstraints gbc_label_2 = new GridBagConstraints(); gbc_label_2.anchor = GridBagConstraints.EAST; gbc_label_2.insets = new Insets(0, 0, 0, 5); gbc_label_2.gridx = 0; gbc_label_2.gridy = 4; panel.add(label_2, gbc_label_2); infotextField = new JTextField(); GridBagConstraints gbc_infotextField = new GridBagConstraints(); gbc_infotextField.fill = GridBagConstraints.HORIZONTAL; gbc_infotextField.gridx = 1; gbc_infotextField.gridy = 4; panel.add(infotextField, gbc_infotextField); infotextField.setColumns(10); JPanel beginPanel = new JPanel(); GridBagConstraints gbc_beginPanel = new GridBagConstraints(); gbc_beginPanel.fill = GridBagConstraints.BOTH; gbc_beginPanel.insets = new Insets(0, 0, 5, 0); gbc_beginPanel.gridx = 0; gbc_beginPanel.gridy = 1; controlPanel.add(beginPanel, gbc_beginPanel); JButton btnBeginButton = new JButton("开始/暂停"); btnBeginButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { startMonitor = !startMonitor; } }); beginPanel.setLayout(new BorderLayout(0, 0)); beginPanel.add(btnBeginButton); JPanel clean = new JPanel(); GridBagConstraints gbc_clean = new GridBagConstraints(); gbc_clean.insets = new Insets(0, 0, 5, 0); gbc_clean.fill = GridBagConstraints.BOTH; gbc_clean.gridx = 0; gbc_clean.gridy = 2; controlPanel.add(clean, gbc_clean); clean.setLayout(new BorderLayout(0, 0)); JButton btnCleanButton = new JButton("清除数据"); clean.add(btnCleanButton); JPanel panel_1 = new JPanel(); GridBagConstraints gbc_panel_1 = new GridBagConstraints(); gbc_panel_1.weighty = 100.0; gbc_panel_1.weightx = 100.0; gbc_panel_1.fill = GridBagConstraints.BOTH; gbc_panel_1.gridx = 0; gbc_panel_1.gridy = 3; controlPanel.add(panel_1, gbc_panel_1); btnCleanButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { cleanData(); } }); } public void setEnabled(boolean b) { this.frame.setEnabled(b); } public void setVisible(boolean b) { this.frame.setVisible(b); } public void cleanData() { startMonitor = false; codeDeviceService.cleanData(); startMonitor = true; refresh(); } public void refreshDeviceList() { deviceTree.setModel(new DefaultTreeModel( new DefaultMutableTreeNode("工位任务:") { { List<WorkPositionJob> list = codeDeviceService.initCodeDevice(); if(list != null && list.size() > 0) { for(CodeDevice cd : list) { add(new DefaultMutableTreeNode(cd.getName())); } } add(new DefaultMutableTreeNode("+")); } } )); } private void deviceSelectEventHandler(TreeSelectionEvent e) { if(e.getNewLeadSelectionPath() == null) { codeDeviceService.setCurrentCodeDevice(null); return; } String value = e.getNewLeadSelectionPath().getLastPathComponent().toString(); if(value.equals(SELECT_EVENT_ADD)) { AddDeviceDialog dialog = new AddDeviceDialog(this); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); dialog.setAlwaysOnTop(true); frame.setEnabled(false); }else { codeDeviceService.setCurrentCodeDevice(value); setCurrentDeviceInfo(value); } refresh(); } private void setCurrentDeviceInfo(String value) { WorkPositionJob cd = codeDeviceService.getCurrentCodeDevice(); if(codeDeviceService.isAllCodeDevice(cd)) { deviceNameTextField.setText("所有设备"); deviceIptextField.setText(""); infotextField.setText("当前统计数据为所有设备数据"); }else { deviceNameTextField.setText(cd.getName()); deviceIptextField.setText(cd.getIp()); infotextField.setText(cd.getInfo()); if(cd.getTargetAccount()>=cd.getSuccCount()) { statusTextField.setText(String.format("目标数%d 大于等于 实际扫描数 %d, 正常",cd.getTargetAccount(), cd.getSuccCount())); }else { statusTextField.setText(String.format("目标数%d 小于 实际扫描数 %d, 异常正常",cd.getTargetAccount(), cd.getSuccCount())); statusTextField.setCaretColor(Color.RED); } } } private void refresh() { WorkPositionJob cd = codeDeviceService.getCurrentCodeDevice(); allCountValueField.setText(cd.getAllCount()+""); normalValueField.setText(cd.getSuccCount()+""); errCountValue.setText(cd.getErrCount() + ""); if(!codeDeviceService.isAllCodeDevice(cd)) { if(cd.getTargetAccount()>=cd.getSuccCount()) { statusTextField.setText(String.format("目标数%d 大于等于 实际扫描数 %d, 正常",cd.getTargetAccount(), cd.getSuccCount())); }else { statusTextField.setText(String.format("目标数%d 小于 实际扫描数 %d, 异常",cd.getTargetAccount(), cd.getSuccCount())); statusTextField.setForeground(Color.RED); } } } }
true
6384a0bd38700cc85785af2b0f0cfd35d6b9cdf9
Java
piraga/Datacopy
/Datacopy/src/com/datacopy/application/Props.java
UTF-8
839
2.1875
2
[]
no_license
package com.datacopy.application; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class Props { private static final String PropertiesPath = "/datacopy.properties"; public Properties getProperties() throws Exception { // Properties p = new Properties(); // InputStream is = new FileInputStream(PropertiesPath); // p.load(is); // System.out.println(p.getProperty("SEED")); // return p; // String fileName = "/db.properties"; Properties prop = new Properties(); InputStream ip = Props.class.getResourceAsStream(PropertiesPath); try { prop.load(ip); // return prop; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return prop; } }
true
0ea215eb14b914351f19f01d7f2470f12c95abe8
Java
Dynatrace-Reinhard-Pilz/Dynatrace-MoM
/dt-utils/src/main/java/com/dynatrace/utils/DomUtil.java
UTF-8
2,593
2.359375
2
[]
no_license
package com.dynatrace.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class DomUtil implements ErrorHandler { private static final String EXM_NO_DYNATRACE = "%s is not a System Profile (no dynatrace element found)"; private static final String EXM_NO_VERSION = "%s is not a System Profile (no version attribute found)"; private static final String EXM_INV_VERSION = "%s is not a System Profile (version attribute invalid)"; private static final ErrorHandler ERROR_HANDLER = new DomUtil(); public static Document build(byte[] bytes) throws IOException { try (InputStream in = Strings.openStream(bytes)) { return build(in); } } public static Document build(String s) throws IOException { try (InputStream in = Strings.openStream(s)) { return build(in); } } public static Document build(File file) throws IOException { try (InputStream in = new FileInputStream(file)) { return build(in); } } public static Document build(InputStream in) throws IOException { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(ERROR_HANDLER); return db.parse(in); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e); } } public static Version extractVersion(Document doc, String fName) throws IOException { NodeList dtElems = doc.getElementsByTagName("dynatrace"); if (dtElems.getLength() == 0) { throw new IOException(String.format(EXM_NO_DYNATRACE, fName)); } Element dtElem = (Element) dtElems.item(0); String vAtt = dtElem.getAttribute("version"); if (vAtt == null) { throw new IOException(String.format(EXM_NO_VERSION, fName)); } try { return Version.parse(vAtt); } catch (IllegalArgumentException e) { throw new IOException(String.format(EXM_INV_VERSION, fName), e); } } @Override public void warning(SAXParseException exception) throws SAXException { // ingore } @Override public void error(SAXParseException exception) throws SAXException { // ingore } @Override public void fatalError(SAXParseException exception) throws SAXException { // ingore } }
true
dacbe19738de569d93d1c810a36c0842ec228811
Java
doroha/Basic---Java-projects
/ProjectsManagment/src/Decorator/AdvancedDesignDecorator.java
UTF-8
278
3.046875
3
[]
no_license
package Decorator; public class AdvancedDesignDecorator implements Design{ private Design design; public AdvancedDesignDecorator(Design design){ this.design = design; } public void displayDesign(){ design.displayDesign(); } }
true
cd330015c5b6713545f84ba1f1036e0a8028ae95
Java
mkaouer/MetaModelsRulesGenerator
/src/AccountDemo.java
UTF-8
1,749
3.671875
4
[]
no_license
import java.text.*; import java.util.Date; public class AccountDemo { class Account { private int id; private double balance; private double annualInterestRate; private Date dateCreated; Account() { id = 0 ; balance = 0 ; annualInterestRate = 0 ; dateCreated= new Date(); } Account(int ID, double BALANCE) { id = ID; balance = BALANCE; dateCreated = new Date(); } public int getId() { return id; } public double getBalance() { return balance; } public double getAnnualInterestRate() { return annualInterestRate; } public void setId(int id) { this.id = id ; } public void setBalance(double balance) { this.balance = balance ; } public void setAnnualInterestRate(double annualInterestRate) { this.annualInterestRate = annualInterestRate; } public Date getDateCreated() { return dateCreated; } public double getMonthlyInterestRate() { return annualInterestRate/12.0; } public void withdraw(double amount) { balance = balance - amount; } public void deposit(double amount) { balance = balance + amount; } class AccountProg { public void main(String[] args) { DecimalFormat df = new DecimalFormat("$$.$$"); Account account = new Account(1122,2000); account.setAnnualInterestRate(4.5); account.withdraw(2500); account.deposit(3000); System.out.println("Balance is :" + df.format(account.getBalance())); System.out.println("Monthly Interest is: " + df.format(account.getMonthlyInterestRate())); System.out.println("Account created on: " + account.getDateCreated()); } } }}
true
44b63fa1ccb8f7b7fed6a9aa875f9e94831dcfbf
Java
aartisoft/SnacksReady
/app/src/main/java/com/w3engineers/core/util/helper/ViewUtils.java
UTF-8
24,506
1.734375
2
[]
no_license
/* * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://mindorks.com/license/apache-v2 * * 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.w3engineers.core.util.helper; import android.app.Activity; import android.app.ActivityManager; import android.app.Fragment; import android.content.Context; import android.content.res.Resources; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.media.MediaScannerConnection; import android.net.Uri; import android.support.design.widget.TabLayout; import android.support.v4.content.ContextCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.TypedValue; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.webkit.WebView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import com.w3engineers.core.AppController; import com.w3engineers.core.snacksready.R; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Semaphore; /* * **************************************************************************** * * Copyright © 2018 W3 Engineers Ltd., All rights reserved. * * * * Created by: * * Name : SUDIPTA KUMAR PAIK * * Date : 2/1/18 * * Email : sudipta@w3engineers.com * * * * Purpose : ViewUtils for all view related Utils method * * * * Last Edited by : SUDIPTA KUMAR PAIK on 2/1/18. * * History: * * 1: * * 2: * * * * Last Reviewed by : SUDIPTA KUMAR PAIK on 2/1/18. * **************************************************************************** */ public final class ViewUtils { private Context context; public static final Semaphore LOCK = new Semaphore(0); private ViewUtils() { // This utility class is not publicly instantiable } private ViewUtils(Context context) { this.context = context; } public static float pxToDp(float px) { float densityDpi = Resources.getSystem().getDisplayMetrics().densityDpi; return px / (densityDpi / 160f); } public static int dpToPx(float dp) { float density = Resources.getSystem().getDisplayMetrics().density; return Math.round(dp * density); } public static void changeIconDrawableToGray(Context context, Drawable drawable) { if (drawable != null) { drawable.mutate(); drawable.setColorFilter(ContextCompat .getColor(context, R.color.colorGray), PorterDuff.Mode.SRC_ATOP); } } public static boolean isVisible(Fragment fragment, int viewId) { View view = getViewById(fragment, viewId); if (view != null) { return view.getVisibility() == View.VISIBLE; } return false; } public static View getViewById(Fragment fragment, int viewId) { return getViewById(fragment.getView(), viewId); } public static boolean isChecked(Fragment fragment, int viewId) { View view = getViewById(fragment, viewId); if (CompoundButton.class.isInstance(view)) { return ((CompoundButton) view).isChecked(); } return false; } public static void setVisibility(Activity activity, int viewId, int visibility) { setVisibility(getViewById(activity, viewId), visibility); } public static void setVisibility(Fragment fragment, int viewId, int visibility) { setVisibility(getViewById(fragment, viewId), visibility); } public static void setVisibility(View view, int visibility) { if (view != null) { view.setVisibility(visibility); } } public static void setVisibility(View parentView, int viewId, int visibility) { setVisibility(getViewById(parentView, viewId), visibility); } // View Related works public static boolean isNull(View view) { return view == null; } public static boolean isNull(Activity activity) { return activity == null; } public static boolean isNull(Fragment fragment) { return fragment == null; } private static boolean isNull(Object view) { return view == null; } public static Spinner getSpinnerById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (Spinner) activity.findViewById(viewId); } return null; } public static Spinner getSpinnerById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (Spinner) fragment.getView().findViewById(viewId); } return null; } public static LinearLayout getLinearLayoutById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (LinearLayout) activity.findViewById(viewId); } return null; } public static LinearLayout getLinearLayoutById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (LinearLayout) fragment.getView().findViewById(viewId); } return null; } public static TextView getTextViewById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (TextView) activity.findViewById(viewId); } return null; } public static TextView getTextViewById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (TextView) fragment.getView().findViewById(viewId); } return null; } public static EditText getEditTextById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (EditText) activity.findViewById(viewId); } return null; } public static EditText getEditTextById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (EditText) fragment.getView().findViewById(viewId); } return null; } public static WebView getWebViewById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (WebView) fragment.getView().findViewById(viewId); } return null; } public static Button getButtonById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (Button) fragment.getView().findViewById(viewId); } return null; } public static ImageButton getImageButtonById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (ImageButton) fragment.getView().findViewById(viewId); } return null; } public static ImageButton getImageButtonById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (ImageButton) activity.findViewById(viewId); } return null; } public static ImageView getImageViewById(Fragment fragment, int viewId) { if (!isNull(fragment) && viewId > 0) { return (ImageView) fragment.getView().findViewById(viewId); } return null; } public static View getViewById(View parentView, int viewId) { if (!isNull(parentView) && viewId > 0) { return parentView.findViewById(viewId); } return null; } public static View getViewById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return activity.findViewById(viewId); } return null; } public static ImageView getImageViewById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (ImageView) activity.findViewById(viewId); } return null; } public static Button getButtonById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (Button) activity.findViewById(viewId); } return null; } public static ToggleButton getToggleButtonById(Activity activity, int viewId) { if (!isNull(activity) && viewId > 0) { return (ToggleButton) activity.findViewById(viewId); } return null; } public static ViewPager getViewPager(View parentView, int viewPagerId) { View viewPager = getViewById(parentView, viewPagerId); if (ViewPager.class.isInstance(viewPager)) { return (ViewPager) viewPager; } return null; } public static TabLayout getTabLayout(View parentView, int tabLayoutId) { View tabLayout = getViewById(parentView, tabLayoutId); if (TabLayout.class.isInstance(tabLayout)) { return (TabLayout) tabLayout; } return null; } public static Toolbar getToolbar(Activity activity, int toolbarId) { View toolbar = getViewById(activity, toolbarId); if (Toolbar.class.isInstance(toolbar)) { return (Toolbar) toolbar; } return null; } public static boolean setClickListener(View view, View.OnClickListener clickListener) { if (!isNull(view)) { view.setOnClickListener(clickListener); return true; } return false; } public static boolean setClickListener(Activity activity, int viewId, View.OnClickListener clickListener) { View view = getViewById(activity, viewId); if (!isNull(view)) { view.setOnClickListener(clickListener); return true; } return false; } public static boolean setClickListener(Fragment fragment, int viewId, View.OnClickListener clickListener) { View view = getViewById(fragment.getView(), viewId); if (!isNull(view)) { view.setOnClickListener(clickListener); return true; } return false; } public static boolean setClickListener(View parentView, int viewId, View.OnClickListener clickListener) { View view = getViewById(parentView, viewId); if (!isNull(view)) { view.setOnClickListener(clickListener); return true; } return false; } public static boolean setCheckedListener(Fragment fragment, int viewId, CompoundButton.OnCheckedChangeListener changeListener) { View view = getViewById(fragment.getView(), viewId); if (CompoundButton.class.isInstance(view)) { ((CompoundButton) view).setOnCheckedChangeListener(changeListener); return true; } return false; } public static void setText(Activity activity, int viewId, String text) { setText(getViewById(activity, viewId), text); } public static void setError(Activity activity, int viewId, String text) { setError(getViewById(activity, viewId), text); } public static void setText(Fragment fragment, int viewId, String text) { setText(getViewById(fragment.getView(), viewId), text); } public static void setError(Fragment fragment, int viewId, String text) { setError(getViewById(fragment.getView(), viewId), text); } public static void setText(View parentView, int viewId, String text) { setText(getViewById(parentView, viewId), text); } public static void setText(View parentView, int viewId, int value) { setText(getViewById(parentView, viewId), value); } public static void setText(View view, long value) { setText(view, Long.toString(value)); } public static void setText(View view, String text) { if (TextView.class.isInstance(view)) { ((TextView) view).setText(text); } } public static void setError(View view, String text) { if (TextView.class.isInstance(view)) { ((TextView) view).setError(text); } } public static void setTextColor(View view, int colorId) { if (TextView.class.isInstance(view)) { ((TextView) view).setTextColor(AndroidUtil.getColor(view.getContext(), colorId)); } } public static RecyclerView.LayoutManager newLinearLayoutManager(Context context) { return new LinearLayoutManager(context); } public static int dpToPx(int dp) { float density = Resources.getSystem().getDisplayMetrics().density; return Math.round(dp * density); } public static void hideKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0); } public static RecyclerView.LayoutManager newGridLayoutManager(Context context, int columns) { return new GridLayoutManager(context, columns); } public static RecyclerView.LayoutManager newStaggeredGridLayoutManager(int spanCount, int orientation) { return new StaggeredGridLayoutManager(spanCount, orientation); } public static RecyclerView.Adapter getAdapter(RecyclerView recyclerView) { if (recyclerView != null) { return recyclerView.getAdapter(); } return null; } public static int getStatusBarHeight(Context context) { int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { return context.getResources().getDimensionPixelSize(resourceId); } return 0; } public static int getActionBarHeight(Context context) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true); int actionBarHeight = context.getResources().getDimensionPixelSize(tv.resourceId); if (actionBarHeight > 0) { return actionBarHeight; } return 0; } public static int getHeight(Context context) { //DisplayMetrics displayMetrics = new DisplayMetrics(); return context.getResources().getDisplayMetrics().heightPixels; } public static void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { } } public static void isScanMedia(String... paths) { MediaScannerConnection.scanFile(AppController.getContext(), paths, null, new MediaScannerConnection.MediaScannerConnectionClient() { @Override public void onMediaScannerConnected() { } @Override public void onScanCompleted(String s, Uri uri) { } }); } public static boolean isEmpty(String... strings) { for (String string : strings) { if (TextUtils.isEmpty(string)) return true; } return false; } public static String lastUpdateDate(double value) { SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a"); String lastUpdatedTime = dateFormat.format(value); return "Updated at " + lastUpdatedTime; } public static String geoLocation(double latitute, double longitute) { return latitute + ", " + longitute; } public static String getDistance(String distance) { return String.valueOf(new DecimalFormat("##.##").format(distance)); } public static boolean isServiceRunning(Class<?> serviceClass, Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } public static String getTimeAgo(long time, final Context context) { final int SECOND_MILLIS = 1000; final int MINUTE_MILLIS = 60 * SECOND_MILLIS; final int HOUR_MILLIS = 60 * MINUTE_MILLIS; final int DAY_MILLIS = 24 * HOUR_MILLIS; final long WEEK_IN_MILLIS = DAY_MILLIS * 7; final long YEAR_MILLIS = WEEK_IN_MILLIS * 52; final long FIVE_MINUTE_MILLIS = MINUTE_MILLIS * 5; if (time < 1000000000000L) { time *= 1000; } long now = TimeUtil.parseToLocalMilliFromMilli(TimeUtil.currentTime()); if (/*headerTime > now || */time <= 0) { String dateString = DateFormat.format("hh:mm a", new Date(now)).toString(); return dateString; } long diff = now - time; //Fixme headerTime related work need to be done when the sender is using greater headerTime than receiver if (diff < 0L) { diff = -diff; } if (diff <= 2 * MINUTE_MILLIS) { return " " + context.getResources().getString(R.string.just_now); } else if (diff < 60 * MINUTE_MILLIS) { return diff / MINUTE_MILLIS + " " + context.getResources().getString(R.string.mins_ago); } else if (diff < 4 * HOUR_MILLIS) { if (diff >= 1 * HOUR_MILLIS && diff < 2 * HOUR_MILLIS) { return diff / HOUR_MILLIS + " " + context.getResources().getString(R.string.hour_ago); } else { return diff / HOUR_MILLIS + " " + context.getResources().getString(R.string.hours_ago); } } else if (diff < 24 * HOUR_MILLIS) { String dateString = DateFormat.format("hh:mm a", new Date(time)).toString(); return dateString; } else if (diff < 7 * DAY_MILLIS) { return new SimpleDateFormat("EEEE").format(new Date(time)); } else if (diff < 1 * YEAR_MILLIS) { int currentYear = TimeUtil.getYear(now); int timeYear = TimeUtil.getYear(time); if (currentYear != timeYear) { return DateFormat.format(" dd MMM yyyy ", new Date(time)).toString(); } return DateFormat.format(" dd MMM", new Date(time)).toString(); } else if (diff > 1 * YEAR_MILLIS) { String dateString = DateFormat.format(" dd MMM yyyy ", new Date(time)).toString(); return dateString; } else { return diff / DAY_MILLIS + " " + context.getResources().getString(R.string.days_ago); } } public static View viewById(Activity activity, int viewId) { if (activity != null) { return activity.findViewById(viewId); } return null; } public static void setBackground(Activity activity, int viewId, int drawableId) { setBackground(getViewById(activity, viewId), drawableId); } public static void setBackground(View view, int drawableId) { if (view != null) { view.setBackgroundResource(drawableId); } } public static RecyclerView getRecyclerView(Fragment fragment, int resourceId) { return getRecyclerView(fragment.getView(), resourceId); } public static RecyclerView getRecyclerView(Activity parentView, int resourceId) { View view = getViewById(parentView, resourceId); return getRecyclerView(view, resourceId); } public static RecyclerView getRecyclerView(View parentView, int resourceId) { View view = getViewById(parentView, resourceId); if (RecyclerView.class.isInstance(view)) { return (RecyclerView) view; } return null; } public static RecyclerView.Adapter getAdapter(Activity activity, int resourceId) { return getAdapter(getRecyclerView(activity, resourceId)); } public static PagerAdapter getPagerAdapter(ViewPager viewPager) { if (!isNull(viewPager)) { return viewPager.getAdapter(); } return null; } public static String getText(Activity activity, int viewId) { View view = getViewById(activity, viewId); if (TextView.class.isInstance(view)) { return ((TextView) view).getText().toString().trim(); } return null; } public static String getText(Fragment fragment, int viewId) { View view = getViewById(fragment, viewId); if (TextView.class.isInstance(view)) { return ((TextView) view).getText().toString().trim(); } return null; } public static String getText(View parentView, int viewId) { View view = getViewById(parentView, viewId); if (TextView.class.isInstance(view)) { return ((TextView) view).getText().toString().trim(); } return null; } public static void setImageResource(Fragment fragment, int viewId, int drawableId) { View view = getViewById(fragment, viewId); setImageResource(view, drawableId); } public static void setImageResource(View parentView, int viewId, int drawableId) { View view = getViewById(parentView, viewId); setImageResource(view, drawableId); } public static void setImageResource(View view, int drawableId) { if (ImageView.class.isInstance(view)) { ((ImageView) view).setImageResource(drawableId); } } public static void initRecyclerView( RecyclerView.LayoutManager layoutManager, BaseAdapter adapter, RecyclerClickListener.OnItemClickListener recyclerListener, RecyclerView recyclerView) { initRecyclerView(layoutManager, adapter, recyclerListener, null, null, recyclerView, false); } public static RecyclerClickListener getRecyclerListener(RecyclerView recyclerView, RecyclerClickListener.OnItemClickListener itemClickListener) { return new RecyclerClickListener(recyclerView, itemClickListener); } public static void initRecyclerView( RecyclerView.LayoutManager layoutManager, BaseAdapter adapter, RecyclerClickListener.OnItemClickListener recyclerListener, RecyclerClickListener.OnItemChildClickListener childListener, RecyclerView.OnScrollListener scrollListener, RecyclerView recyclerView, boolean enableNestedScroll) { if (recyclerView != null) { RecyclerClickListener recyclerClickListener = null; if (recyclerListener != null) { recyclerClickListener = getRecyclerListener(recyclerView, recyclerListener); } /* if (recyclerClickListener != null && childListener != null) { adapter.setRecyclerClickListener(recyclerClickListener); recyclerClickListener.setOnItemChildClickListener(childListener); }*/ recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); // recyclerView.setAdapter(adapter); // have compatible issue need to fixed later if (recyclerClickListener != null) { recyclerView.addOnItemTouchListener(recyclerClickListener); } if (scrollListener != null) { recyclerView.addOnScrollListener(scrollListener); } if (enableNestedScroll) { recyclerView.setNestedScrollingEnabled(true); } } } }
true
fbd8c94b2b4e81f0d3390c825a87e0e24a2f9024
Java
jabbott13153/CS372
/HW2 update/src/myJButton.java
UTF-8
2,151
2.96875
3
[]
no_license
import java.util.ArrayList; import java.awt.Image; import javax.swing.Icon; import javax.swing.JButton; public class myJButton extends JButton { Image icon; Building myBuilding; Police myPolice; Teacher myTeacher; Kid myKid; /** * Setters for all variables * @param i * @param s * @param ch * @param p * @param t * @param k */ public void setIcon(Image i){ icon = i; } public void setBuilding(Building b){ myBuilding = b; } public void setPolice(Police p){ myPolice = p; } public void setTeacher(Teacher t){ myTeacher = t; } public void setKid(Kid k){ myKid = k; } /** * getters for all variables except icon * @return */ public Building getBuilding(){ return myBuilding; } public String getBuildingName(){ return myBuilding.getName(); } public String getBuildingA(){ return myBuilding.getAddress(); } /* public CityHall getcHall(){ return mycHall; } public String getcHallName(){ return mycHall.getName(); } public String getcHallA(){ return mycHall.getName(); }*/ public Police getPolice(){ return myPolice; } public Kid getKid(){ return myKid; } /** * constructor for a school button * @param i * @param s */ myJButton(Icon i, Building b){ setIcon(i); setBuilding(b); } /*/** * Constructor for a city hall button * @param i * @param ch myJButton(Icon i, CityHall ch){ setIcon(i); setcHall(ch); }*/ /** * Constructor for a Police button * @param i * @param p */ myJButton(Icon i, Police p){ setIcon(i); setPolice(p); } /** * Constructor for a Kid button * @param i * @param k */ myJButton(Icon i, Kid k){ setIcon(i); setKid(k); } /** * Constructor for a teacher button * @param i * @param t */ myJButton(Icon i, Teacher t){ setIcon(i); setTeacher(t); } public void bOccupants(){ if(myBuilding == (School)myBuilding){ } } }
true
982f2a95b56e311d241beb4504b26c34ad038bc9
Java
avrisilman/TN
/app/src/main/java/un/app1/appDeps/AppModule.java
UTF-8
2,861
1.992188
2
[]
no_license
package un.app1.appDeps; import android.content.Context; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import un.app1.appConfig.AppData; import un.app1.appNetwork.internet.ConnectivityReceiver; import un.app1.pageModule.appHome.HomePresenter; import un.app1.pageModule.pageForgot.ForgotPasswordPresenter; import un.app1.pageModule.pageListrik.ListrikPresenter; import un.app1.pageModule.pageListrik.historylistrik.HistoryListrikPresenter; import un.app1.pageModule.pageLogin.LoginPresenter; import un.app1.pageModule.pageNotif.NotifPresenter; import un.app1.pageModule.pageProfile.ProfilePresenter; import un.app1.pageModule.pagePulsa.PulsaPresenter; import un.app1.pageModule.pageRegister.RegisterPresenter; import un.app1.pageModule.pageSplash.SplashPresenter; @Module public class AppModule { private Context context; public AppModule(Context context) { this.context = context; } @Provides @Singleton Context provideContext() { return context; } @Provides @Singleton public ConnectivityReceiver providesConnectivityReceiver() { return new ConnectivityReceiver(); } @Provides @Singleton public AppData providesAppData(Context context) { return new AppData(context); } //---PRESENTER--- @Provides @Singleton public NotifPresenter providesNotifPresenter(Context context) { return new NotifPresenter(context); } @Provides @Singleton public ProfilePresenter providesProfilePresenter(Context context) { return new ProfilePresenter(context); } @Provides @Singleton public ForgotPasswordPresenter providesForgotPasswordPresenter(Context context) { return new ForgotPasswordPresenter(context); } @Provides @Singleton public PulsaPresenter providesPulsaPresenter(Context context) { return new PulsaPresenter(context); } @Provides @Singleton public RegisterPresenter providesRegisterPresenter(Context context) { return new RegisterPresenter(context); } @Provides @Singleton public HomePresenter providesHomePresenter(Context context) { return new HomePresenter(context); } @Provides @Singleton public LoginPresenter providesLoginPresenter(Context context) { return new LoginPresenter(context); } @Provides @Singleton public ListrikPresenter providesListrikPresenter(Context context) { return new ListrikPresenter(context); } @Provides @Singleton public HistoryListrikPresenter providesHistoryListrikPresenter(Context context) { return new HistoryListrikPresenter(context); } @Provides @Singleton public SplashPresenter providesSplashPresenter() { return new SplashPresenter(); } }
true
cf15d5d0e320ed2212c57952c8103e89fefc5eed
Java
onrtekinn/my_spring_workshop
/spring-datajpa-postgres/src/main/java/com/otekin/entitiy/Adress.java
UTF-8
844
2.265625
2
[]
no_license
package com.otekin.entitiy; import lombok.*; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Entity @Table(name="Person_Adresses") @AllArgsConstructor @NoArgsConstructor @Getter @Setter @EqualsAndHashCode(of = {"id"}) @ToString public class Adress implements Serializable { @Id @SequenceGenerator(name ="seq_person_adress",allocationSize = 1) @GeneratedValue (generator = "seq_person_adress",strategy = GenerationType.SEQUENCE) private Long id; @Column(length=500,name = "adress") private String adress; @Enumerated private AdressType adressType; @Column(name ="IsActive") private boolean IsActive; @ManyToOne @JoinColumn(name="person_adresses_id") private Employee employee; public enum AdressType{ home, work, etc } }
true
f7b4ea04c8c16d499a4e227d12f61cb87e1ff1f8
Java
lilong9898/Test
/Algorithm/src/main/java/com/lilong/algorithm/sort/HeapSort.java
UTF-8
282
2.453125
2
[]
no_license
package com.lilong.algorithm.sort; /** * 堆排序 */ public class HeapSort extends BaseSort { public static void main(String[] args) { Integer numbers[] = new Integer[]{1, 2, 3, 4, 5, null, 6, 7, 8, 9, 10}; //TODO displayAsTree(numbers, 2); } }
true
af522a32bc9f8d4e37f3362e2b187594f7542fab
Java
willowtreeapps/Hyperion-Android
/hyperion-attr/src/main/java/com/willowtreeapps/hyperion/attr/collectors/PorterDuffModeValue.java
UTF-8
580
2.359375
2
[ "MIT" ]
permissive
package com.willowtreeapps.hyperion.attr.collectors; import android.graphics.PorterDuff; import androidx.annotation.Nullable; import com.willowtreeapps.hyperion.attr.AttributeValue; public class PorterDuffModeValue implements AttributeValue { @Nullable private final PorterDuff.Mode mode; public PorterDuffModeValue(@Nullable PorterDuff.Mode mode) { this.mode = mode; } @Override public CharSequence getDisplayValue() { if (mode == null) { return "None"; } else { return mode.name(); } } }
true
5fb605982a7122282bc8e5e842370e43442807f7
Java
gch12345/Sword-finger-offer
/java/src/operatingSystem/Lock/Banker.java
UTF-8
2,420
3.015625
3
[]
no_license
package operatingSystem.Lock; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Banker { private List<Integer> Request; private Integer index; public Banker(){ Request = new ArrayList<>(); } public Integer getIndex() { return index; } public List<Integer> getRequest() { return Request; } public boolean TrialDistribution(List<process> list, List<Integer> available) { System.out.println("银行家算法"); Scanner scanner = new Scanner(System.in); index = list.size(); while (true) { System.out.println("请输入请求进程名"); String name = scanner.next(); for (int i = 0; i < index; i++) { if (list.get(i).Name.equals(name)) { index = i; break; } } if (index >= list.size()) { System.out.println("没有此进程,请重新输入"); } else { break; } } System.out.println("请输入请求向量"); int Num = available.size(); while (Num > 0) { int num = scanner.nextInt(); if (num >= 0) { Request.add(num); Num--; } else { System.out.println("输入不合法,请重新输入"); } } // System.out.println(Request.isEmpty()); process cur = list.get(index); boolean re = Premise(cur, available); if (re) { for (int i = 0; i < Request.size(); i++) { //System.out.println(available.get(i)); available.set(i, available.get(i) - Request.get(i)); } } return re; } private boolean Premise(process cur, List<Integer> available) { for (int i = 0; i < cur.Need.size(); i++) { if (cur.Need.get(i) < Request.get(i)) { System.out.println("进程 " + cur.Name + " 所需要的资源数已超过它所宣布的最大值"); return false; } if (available.get(i) < Request.get(i)) { System.out.println("进程 " + cur.Name + " 尚无足够的资源," + cur.Name + " 须等待"); return false; } } return true; } }
true
326b25f3359be7bfa4f0350a0d71cb3c5ddb1d4d
Java
PanShengTao/ywgk
/ca/src/main/java/cc/lecent/ywgk/ca/model/LoginModel.java
UTF-8
4,255
2.265625
2
[]
no_license
package cc.lecent.ywgk.ca.model; import android.databinding.ObservableBoolean; import android.databinding.ObservableField; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.PopupWindow; import android.widget.TextView; import cc.lecent.bbc.base.BaseViewModel; import cc.lecent.bbc.utils.StringUtils; import cc.lecent.ywgk.ca.R; import cc.lecent.ywgk.ca.util.CountDownTimerUtils; import cc.lecent.ywgk.ca.util.StringUtil; import cc.lecent.ywgk.data.YwCallback; import cc.lecent.ywgk.data.YwRepository; import cc.lecent.ywgk.data.entity.Login; import cc.lecent.ywgk.data.util.PopupWindowUtils; import cc.lecent.ywgk.data.util.ToastUtils; /** * @Description: 账户登录model * @Author: 卢凤淦 * @CreateDate: 19-2-25 下午2:53 */ public class LoginModel extends BaseViewModel { private Fragment fragment; private CountDownTimerUtils mCountDownTimerUtils; public LoginModel(Fragment fragment) { this.fragment = fragment; } public ObservableField<String> phoneNumber=new ObservableField<>(); public ObservableField<String> verificationCode=new ObservableField<>(); //new一个ViewStyle给界面调用 public final ViewStyle viewStyle = new ViewStyle(); //定义ViewStyle需要的回调内容 public class ViewStyle { public final ObservableBoolean isSendSms = new ObservableBoolean(false);//更新UI的Spinner } public void onClickDelete(){ phoneNumber.set(""); } //登陆键点击事件 public void onClickToLogin(){ if (isLogin()){ goLogin(); } } //验证码点击事件 public void onClickGetSms(){ viewStyle.isSendSms.set(!viewStyle.isSendSms.get()); } //获取验证码 public void getSmsCode(Button button){ if (phoneNumber.get().isEmpty()){ ToastUtils.showToast(fragment.getActivity(),"请输入手机号"); return; }else if (phoneNumber.get().length()!=11){ ToastUtils.showToast(fragment.getActivity(),"您输入的手机号码格式有误"); return; } mCountDownTimerUtils = new CountDownTimerUtils(button, 60000, 1000,fragment.getActivity()); YwRepository.getInstance().getSendSmsCode(phoneNumber.get(), new YwCallback<Boolean>() { @Override public void onSuccess(Boolean aBoolean) { if (!aBoolean){ ToastUtils.showToast(fragment.getActivity(),"获取失败"); } } @Override public void onError(String err) { ToastUtils.showToast(fragment.getActivity(),err); } @Override public void onStart() { mCountDownTimerUtils.start(); } @Override public void onFinish() { mCountDownTimerUtils.onFinish(); mCountDownTimerUtils.cancel(); } }); } //登录 private void goLogin(){ YwRepository.getInstance().login(phoneNumber.get(), verificationCode.get(), new YwCallback<Login>() { @Override public void onSuccess(Login login) { } }); } private void initPupowindow(){ View menuView = View.inflate(fragment.getActivity(), R.layout.pupo_window_approve, null); final PopupWindow popupWindow = PopupWindowUtils.getPopupWindowAtLocation(menuView,fragment.getActivity().getWindow().getDecorView(), Gravity.CENTER, 0,0); } private boolean isLogin(){ if (StringUtils.isEmpty(phoneNumber.get())) { ToastUtils.showToast(fragment.getActivity(), "手机号码不能为空"); return false; } if (!StringUtil.isMobilePhoneNum(phoneNumber.get())) { ToastUtils.showToast(fragment.getActivity(), "请输入正确的手机号"); return false; } if (StringUtils.isEmpty(verificationCode.get())) { ToastUtils.showToast(fragment.getActivity(), "验证码不能为空"); return false; } return true; } }
true
31077b80e31bc17614693e214ad5413235dd3c92
Java
SKBost/Degree-Planner
/app/src/main/java/com/example/degreeplanner/ui/home/SharedHomeViewModel.java
UTF-8
6,586
2.75
3
[]
no_license
package com.example.degreeplanner.ui.home; import androidx.lifecycle.ViewModel; import com.example.degreeplanner.classes.Checklist; import com.example.degreeplanner.classes.Course; import com.example.degreeplanner.classes.Quarter; import com.example.degreeplanner.classes.RequirementCategory; import com.example.degreeplanner.classes.Schedule; import com.example.degreeplanner.ui.requirements.RequirementsViewModel; import java.util.ArrayList; import java.util.Collections; public class SharedHomeViewModel extends ViewModel { // Create Schedule class protected Schedule mySchedule = new Schedule(); int yearEntered = 2019; int numYears = 4; // Checklists for all categories Checklist majorChecklist = new Checklist(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.majorCourses)), new ArrayList<Course>()); Checklist minorChecklist = new Checklist(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.minorCourses)), new ArrayList<Course>()); Checklist collegeChecklist = new Checklist(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.collegeCourses)), new ArrayList<Course>()); Checklist universityChecklist = new Checklist(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.universityCourses)), new ArrayList<Course>()); // Holds location of seekBar int seekBarProgress = 0; /* * Getter method for seekBarProgress */ public int getSeekBarProgress() { return seekBarProgress; } /* * Getter method for checklist */ public Checklist getChecklist(String checklistName) { switch (checklistName) { case "major" : return majorChecklist; case "minor" : return minorChecklist; case "college" : return collegeChecklist; case "university" : return universityChecklist; } return majorChecklist; } /* * Getter method for mySchedule */ public Schedule getMySchedule() { return mySchedule; } /* * Getter method for year entered */ public int getMyYearEntered() { return yearEntered; } /* * Setter method for the schedule */ public void setMySchedule(Schedule newSchedule) { mySchedule = newSchedule; } /* * Setter method for checklists */ public void setMyChecklists(String category, Checklist newChecklist) { switch (category) { case "major" : majorChecklist = newChecklist; break; case "minor" : minorChecklist = newChecklist; break; case "college" : collegeChecklist = newChecklist; break; case "university" : universityChecklist = newChecklist; break; default: } } /* * Setter method for seekBarProgress */ public void setSeekBarProgress(int myProgress) { seekBarProgress = myProgress; } /* * Setter method for yearEntered */ public void setYearEntered(int myYearEntered) { yearEntered = myYearEntered; } public void setNumYears(int myNumYears) { numYears = myNumYears; } /* * Method to reset the requirement categories for the checklists */ public void resetChecklists() { // Reset major checklist majorChecklist.setRequirementCategories(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.majorCourses))); minorChecklist.setRequirementCategories(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.minorCourses))); collegeChecklist.setRequirementCategories(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.collegeCourses))); universityChecklist.setRequirementCategories(new ArrayList<RequirementCategory> (Collections.singletonList(RequirementsViewModel.universityCourses))); } /* * Method to create 4 quarters per year and add to the schedule */ public void createQuarters() { int year = yearEntered; for (int i = 0, j = 0; i < numYears; i+=1, year+=1, j+=4) { createQuartersHelper(j, year); } } /* * createQuarters helper method to name each quarter */ public void createQuartersHelper(int index, int year) { Quarter fallQuarter = new Quarter(index, "Fall" + " " + year); Quarter winterQuarter = new Quarter(index + 1, "Winter" + " " + (year + 1)); Quarter springQuarter = new Quarter(index + 2, "Spring" + " " + (year + 1)); Quarter summerQuarter = new Quarter(index + 3, "Summer" + " " + (year + 1)); getMySchedule().addQuarter(fallQuarter); getMySchedule().addQuarter(winterQuarter); getMySchedule().addQuarter(springQuarter); getMySchedule().addQuarter(summerQuarter); } /* * Adds planned course from popup to correct quarter */ public Course addCourseToQuarter(String course, String quarter, int year) { Course addedCourse = null; // Find quarter to add course to for (Quarter q: getMySchedule().getQuarters()) { if (q.getName().equals(quarter + " " + year)) { // Find course for (Course c: RequirementsViewModel.unplannedCourses.getCourses()) { String courseName = c.getDept() + " " + c.getCode(); if (courseName.equals(course)) { addedCourse = c; } } q.addCourse(addedCourse); return addedCourse; } } return addedCourse; } /* * Removes planned course from the associated quarter */ public Course removeCourseFromQuarter(Course course) { // Find quarter to remove course from for (Quarter q: getMySchedule().getQuarters()) { // Find and remove course for (Course removedCourse: q.getCourses()) { if (removedCourse.compareCourses(course)) { q.removeCourse(removedCourse); } } } return course; } }
true
efca12c527d6fc2642fe25bc9368e09d33cfae39
Java
tymoorej/Chess
/src/Exceptions/TooManyPlayersWithTheSameColourException.java
UTF-8
104
1.703125
2
[]
no_license
package Exceptions; public class TooManyPlayersWithTheSameColourException extends RuntimeException { }
true
5455acd3028eb10dde656e94c63f8453ad6a30f4
Java
MaxRomaschenko/JavaLessons
/src/main/java/behavioralPatterns/visitor/test/ProjectElement.java
UTF-8
120
1.851563
2
[]
no_license
package behavioralPatterns.visitor.test; public interface ProjectElement { void beWritten(Developer developer); }
true
536014ca93d9936aa843f0b2d1635f917a578f03
Java
alinke/PIXEL
/pixelcade-pipeserver/src/main/java/org/onebeartoe/pipe/server/pixelcade/PixelcadePipeServer.java
UTF-8
4,532
2.890625
3
[]
no_license
package org.onebeartoe.pipe.server.pixelcade; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; public class PixelcadePipeServer { static final int ERROR_PIPE_CONNECTED = 535; static final int ERROR_BROKEN_PIPE = 109; private int namedPipeHandle; private String pipeName, srcFile; private int pipeBuffer = 131072, fileBuffer = 8192; public PixelcadePipeServer(String pipeName, String srcFile) { this.pipeName = pipeName; this.srcFile = srcFile; } private void log(String message) { System.out.println(message); } private boolean createPipe() { boolean ok = false; namedPipeHandle = Pipes.CreateNamedPipe(pipeName, 0x00000003, 0x00000000, 2, pipeBuffer, pipeBuffer, 0xffffffff, 0); if (namedPipeHandle == -1) { log("CreateNamedPipe failed for " + pipeName + " for error " + " Message " + Pipes.FormatMessage(Pipes.GetLastError())); ok = false; } else { log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle); ok = true; } return ok; } private boolean connectToPipe() { log("Waiting for a client to connect to pipe " + pipeName); boolean connected = Pipes.ConnectNamedPipe(namedPipeHandle, 0); if (!connected) { int lastError = Pipes.GetLastError(); if (lastError == ERROR_PIPE_CONNECTED) connected = true; } if (connected) { log("Connected to the pipe " + pipeName); } else { log("Falied to connect to the pipe " + pipeName); } return connected; } public void runPipe() { if (createPipe()) { if (!connectToPipe()) { log("Connect ConnectNamedPipe failed : " + Pipes.FormatMessage(Pipes.GetLastError())); return; } else { log("Client connected."); } try { File f1 = new File(this.srcFile); InputStream in = new FileInputStream(f1); log("Sending data to the pipe"); byte[] buf = new byte[fileBuffer]; int len, bytesWritten; while ((len = in.read(buf)) > 0) { bytesWritten = Pipes.WriteFile(namedPipeHandle, buf, len); log("Sent " + len + "/" + bytesWritten + " bytes to the pipe"); if (bytesWritten == -1) { int errorNumber = Pipes.GetLastError(); log("Error Writing to pipe " + Pipes.FormatMessage(errorNumber)); } } in.close(); Pipes.FlushFileBuffers(namedPipeHandle); Pipes.CloseHandle(namedPipeHandle); Pipes.DisconnectNamedPipe(namedPipeHandle); log("Writing to the pipe completed."); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws IOException, InterruptedException { try { // Connect to the pipe RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\pixelcade", "rw"); String echoText = "Hello world\n"; // write to pipe pipe.write(echoText.getBytes()); //String aChar; StringBuffer fullString = new StringBuffer(); while(true){ int charCode = pipe.read(); if(charCode == 0) break; //aChar = new Character((char)charCode).toString(); fullString.append((char)charCode); } System.out.println("Response: " + fullString); pipe.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //String pipeName = "\\\\.\\pipe\\pixelcade"; //String fileName = "C:\\db2tabledata.txt";; //PixelcadePipeServer testPipe = new PixelcadePipeServer(pipeName, fileName); //testPipe.runPipe(); } }
true
8149024e935070c3651e69418217c51da1f76da1
Java
blackducksoftware/bdns
/src/main/java/com/blackducksoftware/bdns/VersionRange.java
UTF-8
1,120
1.835938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 Synopsys, 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.blackducksoftware.bdns; import java.util.function.Predicate; /** * A version range defines a request for one or more versions. Generally build systems will allow a range of versions to * be requested and only a single version to be used (potentially scoped). Some namespaces only allow a range consisting * of a single version to be specified while others may support complex expressions to define the range of versions. * * @author jgustie */ public interface VersionRange extends Predicate<Version> { }
true
3cb212dd0d1a15cf016248137c42077d31cac2e5
Java
taoyufan/automanx-api
/src/test/java/com/taobao/itest/junit/CalculatorTest.java
UTF-8
1,699
3.359375
3
[]
no_license
package com.taobao.itest.junit; import junit.framework.Assert; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class CalculatorTest { long time; static int index = 0; Calculator calculator; @BeforeClass public static void startTest() { System.out.println("测试开始执行了"); } @Before public void setUp() { System.out.printf("第%d个用例开始执行\n", ++index); time = System.currentTimeMillis(); calculator = new Calculator(); } @Test public void testPlus() throws InterruptedException { Assert.assertEquals(calculator.plus(1, 2), 3); Thread.sleep(100); } @After public void tearDown() { calculator = null; time = System.currentTimeMillis() - time; System.out.printf("第%d个用例执行了%d毫秒\n", index, time); } @AfterClass public static void endTest() { System.out.println("测试结束了"); } @Test public void testMinus() throws InterruptedException { Assert.assertEquals(calculator.minus(1, 2), -1); Thread.sleep(200); } @Test public void testMultiply() throws InterruptedException { Assert.assertEquals(calculator.multiply(1, 2), 2); Thread.sleep(300); } @Test public void testDivide() throws InterruptedException { Assert.assertEquals(calculator.divide(1, 2), 0.5); Thread.sleep(400); } } // 待测类 class Calculator { int plus(int x, int y) { return x + y; } int minus(int x, int y) { return x - y; } int multiply(int x, int y) { return x * y; } double divide(int x, int y) { return ((double) x) / y; } }
true
3fb2d1295ef52032fe6c6683224246e82bd62771
Java
solorzanojf/Reto2Ciclo2
/src/main/java/reto2ciclo2/logica/MedicamentosNatural.java
UTF-8
1,027
2.9375
3
[]
no_license
package reto2ciclo2.logica; public class MedicamentosNatural extends Medicamentos{ private final static int NUMERO_UNIDADES= 8; private int numero_unidades; public MedicamentosNatural(String marca, String tipo, double precioBase, int numero_unidades){ super(marca, tipo, precioBase); this.numero_unidades = numero_unidades; } public MedicamentosNatural(){ this.numero_unidades = NUMERO_UNIDADES; } public MedicamentosNatural(int numero_unidades){ this.numero_unidades = numero_unidades; } public static int getNumeroUnidades() { return NUMERO_UNIDADES; } public void setNumero_unidades(int numero_unidades) { this.numero_unidades = numero_unidades; } public double calcularPrecio(){ double precioFinal = super.calcularPrecio(); if (numero_unidades<10){ precioFinal+=11000; }else{ precioFinal+=15000; } return precioFinal; } }
true
ea21ceed1bad95084b815705ce0ddec70e94a19a
Java
espre05/starter-sboot-camel
/src/main/java/sb/app/camel/process/LoggingProcessor.java
UTF-8
302
2.09375
2
[]
no_license
package sb.app.camel.process; import org.apache.camel.Exchange; import org.apache.camel.Processor; public class LoggingProcessor implements Processor{ @Override public void process(Exchange ex) throws Exception { System.out.println("Now processing : " + ex.getIn().getBody(String.class)); } }
true
e427386c1e500ba96470332578726918ae5d82c9
Java
154336119/obd-Android
/app/src/main/java/com/slb/ttdandroidframework/ui/contract/HistoryContract.java
UTF-8
750
1.914063
2
[]
no_license
package com.slb.ttdandroidframework.ui.contract; import com.slb.frame.ui.presenter.IBaseFragmentPresenter; import com.slb.frame.ui.view.IBaseLoadingDialogView; import com.slb.ttdandroidframework.http.bean.HistoryErrorCodeEntity; import com.slb.ttdandroidframework.http.bean.ObdEntity; import com.slb.ttdandroidframework.http.bean.VehicleEntity; import java.util.List; /** * Created by Gifford on 2018/1/5. */ public class HistoryContract { public interface IView extends IBaseLoadingDialogView { void getHistoryErrorCodeSuccess(List<HistoryErrorCodeEntity> list); } public interface IPresenter<T> extends IBaseFragmentPresenter<T> { void getHistoryErrorCode(ObdEntity obd , VehicleEntity vehicle, String startDate, String endDate); } }
true
778b67a8941a3a70a52b8456a697f9d969c216af
Java
lgf-Allen/spring-boot-demo
/spring-boot-security/src/main/java/com/allen/spring/boot/config/filter/CustomerFilter.java
UTF-8
1,676
2.453125
2
[]
no_license
/** * */ package com.allen.spring.boot.config.filter; import java.io.IOException; import java.security.Principal; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; /** * @author first * */ //@Component public class CustomerFilter implements Filter { /* (non-Javadoc) * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Start customerFilter"); } /* (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)request; if(httpRequest.isUserInRole("USER")) { Principal principal = httpRequest.getUserPrincipal(); String username = principal.getName(); System.out.println("Username is "+ username); } chain.doFilter(httpRequest, response); } /* (non-Javadoc) * @see javax.servlet.Filter#destroy() */ @Override public void destroy() { System.out.println("Destory end."); } }
true
bccda9dacf080739257e5028e96515fe9ee1099a
Java
cdfq152313/AndroidBackup
/MyBlueTooth/app/src/main/java/com/example/denny/mybluetooth/ClientActivity.java
UTF-8
5,439
2.125
2
[]
no_license
package com.example.denny.mybluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.addweup.awubluetooth.io.BluetoothIO; import com.addweup.awubluetooth.io.BluetoothIOFactory; import java.util.Set; import java.util.TreeSet; public class ClientActivity extends AppCompatActivity implements BluetoothIO.Listener { public static final String TAG = "BTClient"; TextView textView; EditText editText; ListView pairListView; ListView searchListView; ArrayAdapter<String> searchAdapter; Handler uiHandler = new Handler(); BluetoothIO bluetoothIO; Set<BluetoothDevice> pairDevices; Set<BluetoothDevice> searchDevice = new TreeSet<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_client); pairDevices = BluetoothDeviceUtils.listPairDevices(); initView(); scanBluetooth(); } private void initView(){ textView = (TextView) findViewById(R.id.textView); editText = (EditText) findViewById(R.id.editText); pairListView = (ListView) findViewById(R.id.pairlistView); pairListView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, BluetoothDeviceUtils.listPairDevicesNameString(pairDevices))); pairListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { String deviceName = (String) adapterView.getItemAtPosition(i); for(BluetoothDevice device:pairDevices){ if(device.getName().equals(deviceName)){ if(bluetoothIO != null) bluetoothIO.disconnect(); bluetoothIO = BluetoothIOFactory.client(device, BluetoothConfig.UUID); bluetoothIO.connect(); bluetoothIO.setListener(ClientActivity.this); display("Connecting"); return; } } Toast.makeText(ClientActivity.this, "Not Found", Toast.LENGTH_SHORT).show(); } }); searchListView = (ListView) findViewById(R.id.searchlistView); searchAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); searchListView.setAdapter(searchAdapter); } private void scanBluetooth(){ // Register for broadcasts when a device is discovered. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(mReceiver, filter); BluetoothAdapter.getDefaultAdapter().startDiscovery(); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { Log.i(TAG, "onReceive: Start"); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Log.i(TAG, "onReceive: Finish"); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Discovery has found a device. Get the BluetoothDevice // object and its info from the Intent. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d(TAG, "onReceive: " + device.getName()); searchDevice.add(device); searchAdapter.add(device.getName()); searchAdapter.notifyDataSetChanged(); } } }; @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); if(bluetoothIO != null){ bluetoothIO.disconnect(); } } public void display(final String s){ Log.d(TAG, "display: " + s); uiHandler.post(new Runnable() { @Override public void run() { textView.setText(s); } }); } public void sendClick(View view){ if(bluetoothIO == null){ return; } bluetoothIO.send(editText.getText().toString()); } @Override public void onConnect() { display("Connected"); } @Override public void onResponse(String response) { display(response); } @Override public void onDisconnect() { display("Disconnected"); } }
true
3e0b727da3d6083892ac1efa77ec3bdf34e57518
Java
hamdan-codes/java-programs-till-now
/JAVA @ Hamdan Class 12/Mixer.java
UTF-8
820
3.484375
3
[]
no_license
import java.io.*; class Mixer { String x="",y=""; void input()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter First"); x=br.readLine(); System.out.println("Enter Second"); y=br.readLine(); } String mix(Mixer p,Mixer q) { return (p.x+" "+q.x+" "+p.y+" "+q.y); } public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Mixer a=new Mixer(); Mixer b=new Mixer(); Mixer c=new Mixer(); a.input(); b.input(); String ans=c.mix(a,b); System.out.println(ans); } }
true
7cf0e59de0ed119958f4aa586e9f774652ad035e
Java
DoubleDa/AndroidCodeFragment
/AndroidCodeFragment/app/src/main/java/com/dyx/acf/receiver/MsgReceiver.java
UTF-8
1,412
2.1875
2
[]
no_license
package com.dyx.acf.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import android.widget.Toast; /** * Created by dayongxin on 2016/8/11. */ public class MsgReceiver extends BroadcastReceiver { String receiveMsg = ""; public void onReceive(Context context, Intent intent) { SmsMessage[] msg = null; if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) { //StringBuilder buf = new StringBuilder(); Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdusObj = (Object[]) bundle.get("pdus"); msg = new SmsMessage[pdusObj.length]; for (int i = 0; i < pdusObj.length; i++) msg[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]); } for (int i = 0; i < msg.length; i++) { String msgTxt = msg[i].getMessageBody(); if (msgTxt.equals("Testing!")) { Toast.makeText(context, "success!", Toast.LENGTH_LONG).show(); return; } else { Toast.makeText(context, msgTxt, Toast.LENGTH_LONG).show(); return; } } return; } } }
true
285910ecdb5ace798546cd6fb0482dbd13c495c4
Java
huangchenyao/Design-Pattern-Learn
/src/main/java/hcy/command/TVController.java
UTF-8
273
2.734375
3
[]
no_license
package hcy.command; public class TVController { private TV tv; public TVController(TV tv) { this.tv = tv; } public void on() { new TVOnCommand(tv).execute(); } public void off() { new TVOffCommand(tv).execute(); } }
true
5bb46bad2c4b770e8695811681e2b5b9c740c885
Java
13141498695/jzkj-master
/jzkj-biz-admin/src/main/java/com/jzkj/modules/product/controller/ModelController.java
UTF-8
2,993
2.109375
2
[]
no_license
package com.jzkj.modules.product.controller; import com.jzkj.common.annotation.SysLog; import com.jzkj.common.utils.PageUtils; import com.jzkj.common.utils.ReturnResult; import com.jzkj.miservice.entity.product.ModelEntity; import com.jzkj.modules.product.service.ModelService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; @RestController @RequestMapping("/sys/model") public class ModelController { /** * * * @author zhangbin * @email zhangbin@xgjgas.com * @date 2019-01-10 15:55:39 */ @Resource private ModelService modelService; /** * 保存模型 */ @SysLog("保存模型") @RequestMapping("/add") @RequiresPermissions("sys:model:save") public ReturnResult save(@RequestBody ModelEntity model){ String string = java.util.UUID.randomUUID().toString(); model.setCreatetime(new Date()); model.setModelId(string); int i=modelService.save(model); return ReturnResult.ok(); } /** * 修改模型 */ @SysLog("修改模型") @RequestMapping("/update") @RequiresPermissions("sys:model:update") public ReturnResult update(@RequestBody ModelEntity model){ int i =modelService.update(model); return ReturnResult.ok(); } /** * 查询单个 */ @SysLog("修改模型回显") @RequestMapping("/info/{modelId}") /* @RequiresPermissions("sys:model:select") */ public ReturnResult select(@PathVariable("modelId") String modelId){ ModelEntity model=this.modelService.selectmodellist(modelId); System.out.println("修改查询:"+model.getModelName()); //修改模型回显 return ReturnResult.ok().put("model", model); } /** * 删除模型 */ @SysLog("删除模型") @RequestMapping("/delete") //@ResponseBody @RequiresPermissions("sys:model:delete") public ReturnResult delete(@RequestBody String [] modelId){ //ValidatorUtils.validateEntity(model, UpdateGroup.class); System.out.println("删除的id:"+(Arrays.asList(modelId))); for (int i = 0; i < modelId.length; i++) { modelService.delete(modelId[i]);; } return ReturnResult.ok(); } /** * 模型列表 */ @SysLog("模型列表") @RequestMapping("/list") @RequiresPermissions("sys:model:list") public ReturnResult list(@RequestParam Map<String, Object> params){ PageUtils page = modelService.queryPage(params); System.out.println("页面:"+page); return ReturnResult.ok().put("page", page); } /** * 模型列表 */ @SysLog("模型列表") @RequestMapping("/modellist") //@RequiresPermissions("sys:model:modellist") @ResponseBody public List<ModelEntity> modellistlist(){ List<ModelEntity> list=this.modelService.selectmodellist(); System.out.println(list.size()); return list; } }
true
bb48896176d0d4c8ef2b64603f2765c2a4394231
Java
f4r0fA/AgendaBeautifulProfisional
/app/src/main/java/com/digtech/agendaprofisional/SalonListActivity.java
UTF-8
5,011
1.929688
2
[]
no_license
package com.digtech.agendaprofisional; import android.app.AlertDialog; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.TextView; import android.widget.Toast; import com.digtech.agendaprofisional.Adapter.MyAdapterSaloes; import com.digtech.agendaprofisional.Common.Common; import com.digtech.agendaprofisional.Common.SpacesItemDecoration; import com.digtech.agendaprofisional.Interface.IGetCabeleleiroListener; import com.digtech.agendaprofisional.Interface.IOnLoadCountSalon; import com.digtech.agendaprofisional.Interface.ISaloesLoadListener; import com.digtech.agendaprofisional.Interface.IUserLoginRememberListener; import com.digtech.agendaprofisional.Model.Cabeleleiro; import com.digtech.agendaprofisional.Model.Saloes; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import dmax.dialog.SpotsDialog; import io.paperdb.Paper; public class SalonListActivity extends AppCompatActivity implements IOnLoadCountSalon, ISaloesLoadListener, IGetCabeleleiroListener, IUserLoginRememberListener { @BindView(R.id.txt_salon_count) TextView txt_salon_count; @BindView(R.id.recycler_salon) RecyclerView recycler_salon; IOnLoadCountSalon iOnLoadCountSalon; ISaloesLoadListener iSaloesLoadListener; AlertDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_salon_list); ButterKnife.bind(this); initView(); init(); loadSalonBaseOnCity(Common.state_name); } private void loadSalonBaseOnCity(String name) { dialog.show(); FirebaseFirestore.getInstance().collection("AllSalon") .document(name) .collection("Saloes") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { List<Saloes> saloes = new ArrayList<>(); iOnLoadCountSalon.onLoadCountSalonSuccess(task.getResult().size()); for (DocumentSnapshot salonSnapShot:task.getResult()){ Saloes salon = salonSnapShot.toObject(Saloes.class); salon.setSalomId(salonSnapShot.getId()); saloes.add(salon); } iSaloesLoadListener.onSaloesLoadSucess(saloes); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { iSaloesLoadListener.onSaloesLoadFailed("Verifique sua conexão ou tente mais tarde =("); } }); } private void init() { dialog = new SpotsDialog.Builder().setContext(this).setCancelable(false).setMessage("Carregando").build(); iOnLoadCountSalon = this; iSaloesLoadListener = this; } private void initView() { recycler_salon.setHasFixedSize(true); recycler_salon.setLayoutManager(new GridLayoutManager(this, 1)); recycler_salon.addItemDecoration(new SpacesItemDecoration(8)); } @Override public void onLoadCountSalonSuccess(int count) { txt_salon_count.setText(new StringBuilder("Salões Disponíveis (") .append(count) .append(")")); } @Override public void onSaloesLoadSucess(List<Saloes> saloesList) { MyAdapterSaloes salonAdapter = new MyAdapterSaloes(this, saloesList,this,this); recycler_salon.setAdapter(salonAdapter); dialog.dismiss(); } @Override public void onSaloesLoadFailed(String message) { Toast.makeText(this, "Verifique sua conexão ou tente mais tarde", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } @Override public void onGetCabeleleiroSuccess(Cabeleleiro cabeleleiro) { Common.currentCabeleleiro = cabeleleiro; Paper.book().write(Common.CABELELEIRO_KEY, new Gson().toJson(cabeleleiro)); } @Override public void onUserLoginSuccess(String user) { Paper.init(this); Paper.book().write(Common.LOGGED_KEY, user); Paper.book().write(Common.STATE_KEY, Common.state_name); Paper.book().write(Common.SALON_KEY, new Gson().toJson(Common.selected_salon)); } }
true
91a981f71119b5c39660916bc4bf48ff9891ee1b
Java
vidushi1991/mypoc
/Bookfariautomation/src/test/java/PDFEmail/BaseClass.java
UTF-8
1,258
2.34375
2
[]
no_license
/** * */ package PDFEmail; import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import bookfariscripts.Resources; /** * @author Vidushi Mishra * */ public class BaseClass extends Resources { static WebDriver driver; public static WebDriver openBrowser() { if(driver==null){ System.setProperty(browserDriver, driverpath); ChromeOptions options = new ChromeOptions(); options.addArguments("--start-maximized"); return driver = new ChromeDriver( options ); } return driver; } public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{ //Convert web driver object to TakeScreenshot TakesScreenshot scrShot =((TakesScreenshot)webdriver); //Call getScreenshotAs method to create image file File SrcFile=scrShot.getScreenshotAs(OutputType.FILE); //Move image file to new destination File DestFile=new File(fileWithPath); //Copy file at destination FileUtils.copyFile(SrcFile, DestFile); } }
true
4cb6f2a549eb389a8e0dbd31254df88914fe63b4
Java
haoy1220/Coding-Interviews
/src/main/java/面试题35_复杂链表的复制/Solution.java
UTF-8
1,971
3.453125
3
[]
no_license
package 面试题35_复杂链表的复制; import 数据结构.RandomListNode; /** * 题目描述 * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。 * (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) */ public class Solution { public RandomListNode Clone(RandomListNode pHead) { CloneNodes(pHead); ConnectRandomNode(pHead); return ReConnectNodes(pHead); } private RandomListNode ReConnectNodes(RandomListNode pHead) { RandomListNode pNode = pHead; RandomListNode pClonedHead = null; RandomListNode pClonedNode = null; if (pNode != null) { pClonedHead = pClonedNode = pNode.next; pNode.next = pClonedNode.next; pNode = pNode.next; } while (pNode != null) { pClonedNode.next = pNode.next; pClonedNode = pClonedNode.next; pNode.next = pClonedNode.next; pNode = pNode.next; } return pClonedHead; } private void ConnectRandomNode(RandomListNode pHead) { RandomListNode pNode = pHead; while (pNode != null) { RandomListNode pCloned = pNode.next; if (pNode.random != null) { pCloned.random = pNode.random.next; } pNode = pCloned.next; } } //节点需要new,而不会凭空出现,赋值只是复制了地址 private void CloneNodes(RandomListNode pHead) { RandomListNode pNode = pHead; while (pNode != null) { RandomListNode pCloned = new RandomListNode(pNode.label); pCloned.next = pNode.next; pCloned.random = null; pNode.next = pCloned; pNode = pCloned.next; } } }
true
efc656a0856a7252ae715c5cc748f730201bee35
Java
relish-wang/WhatEat
/app/src/main/java/com/xhxkj/zhcs/temp/UserInfoBeanDe.java
UTF-8
626
1.914063
2
[]
no_license
package com.xhxkj.zhcs.temp; /** * @author 王鑫 * Created by 王鑫 on 2015/10/5. * @deprecated */ public class UserInfoBeanDe { private String username; private String pwd; private String tel; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } }
true
7f26534a49f50db4d54f3208fc0a5db861a956d3
Java
vcshukla73/SeleniumSecession
/DropDownConcepts.java
UTF-8
2,004
2.453125
2
[]
no_license
package seleniumPractice; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import io.github.bonigarcia.wdm.WebDriverManager; public class DropDownConcepts { static WebDriver driver; public static void main(String[] args) throws InterruptedException { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); //driver.get("https://www.facebook.com/"); driver.get("https://www.orangehrm.com/orangehrm-30-day-trial/"); //driver.findElement(By.id("u_0_2")).click(); // String dob = "15-May-1973"; Thread.sleep(5000); By day = By.id("day"); By month = By.id("month"); By year = By.id("year"); By country = By.id("Form_submitForm_Country"); //WebElement day1=driver.findElement(day); //getDropdownOptions(day); //getDropdownOptions(month); //getDropdownOptions(year); //List<String> daylist=getDropdownOptions(day); //System.out.println(daylist); //List<String> monthlist=getDropdownOptions(month); //System.out.println(monthlist); List<String> countrylist= getDropdownOptions(country); System.out.println(countrylist); // for(int i=0;i<elements.size();i++) { // String text=elements.get(i).getText(); // System.out.println(text); // } Thread.sleep(4000); driver.quit(); } public static List<String> getDropdownOptions(By locator) { List<String> optionsList=new ArrayList(); Select select=new Select(getElement(locator)); List<WebElement> elements=select.getOptions(); //System.out.println(elements.size()); for (WebElement webElement : elements) { String text=webElement.getText(); optionsList.add(text); } return optionsList; } public static WebElement getElement(By locator) { WebElement element = driver.findElement(locator); return element; } }
true
350d57f0b994cd7366e9d260569d42d37b05775f
Java
akihiro117/DesignPattern
/src/factorymethod/concrete/Study.java
UTF-8
213
2.375
2
[]
no_license
package factorymethod.concrete; import factorymethod.template.Product; public class Study extends Product { Study() { } public void start() { System.out.println("勉強を開始します。"); } }
true
89476e6b35e8e054badf291826d66cf725ddbc3a
Java
JeffWoo2019/aliyun-openapi-java-sdk
/aliyun-java-sdk-ecsops/src/main/java/com/aliyuncs/ecsops/model/v20160401/OpsModifyDiskAttributeRequest.java
UTF-8
3,436
1.828125
2
[ "Apache-2.0" ]
permissive
/* * 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.aliyuncs.ecsops.model.v20160401; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; /** * @author auto create * @version */ public class OpsModifyDiskAttributeRequest extends RpcAcsRequest<OpsModifyDiskAttributeResponse> { private Boolean enableAutoSnapshot; private String operator; private String diskName; private Boolean deleteAutoSnapshot; private String diskId; private String diskDesc; private Boolean deleteWithInstance; private String auditParamStr; public OpsModifyDiskAttributeRequest() { super("Ecsops", "2016-04-01", "OpsModifyDiskAttribute", "ecsops"); setMethod(MethodType.POST); } public Boolean getEnableAutoSnapshot() { return this.enableAutoSnapshot; } public void setEnableAutoSnapshot(Boolean enableAutoSnapshot) { this.enableAutoSnapshot = enableAutoSnapshot; if(enableAutoSnapshot != null){ putQueryParameter("EnableAutoSnapshot", enableAutoSnapshot.toString()); } } public String getOperator() { return this.operator; } public void setOperator(String operator) { this.operator = operator; if(operator != null){ putQueryParameter("Operator", operator); } } public String getDiskName() { return this.diskName; } public void setDiskName(String diskName) { this.diskName = diskName; if(diskName != null){ putQueryParameter("DiskName", diskName); } } public Boolean getDeleteAutoSnapshot() { return this.deleteAutoSnapshot; } public void setDeleteAutoSnapshot(Boolean deleteAutoSnapshot) { this.deleteAutoSnapshot = deleteAutoSnapshot; if(deleteAutoSnapshot != null){ putQueryParameter("DeleteAutoSnapshot", deleteAutoSnapshot.toString()); } } public String getDiskId() { return this.diskId; } public void setDiskId(String diskId) { this.diskId = diskId; if(diskId != null){ putQueryParameter("DiskId", diskId); } } public String getDiskDesc() { return this.diskDesc; } public void setDiskDesc(String diskDesc) { this.diskDesc = diskDesc; if(diskDesc != null){ putQueryParameter("DiskDesc", diskDesc); } } public Boolean getDeleteWithInstance() { return this.deleteWithInstance; } public void setDeleteWithInstance(Boolean deleteWithInstance) { this.deleteWithInstance = deleteWithInstance; if(deleteWithInstance != null){ putQueryParameter("DeleteWithInstance", deleteWithInstance.toString()); } } public String getAuditParamStr() { return this.auditParamStr; } public void setAuditParamStr(String auditParamStr) { this.auditParamStr = auditParamStr; if(auditParamStr != null){ putQueryParameter("AuditParamStr", auditParamStr); } } @Override public Class<OpsModifyDiskAttributeResponse> getResponseClass() { return OpsModifyDiskAttributeResponse.class; } }
true
0f6938a881ce9bbdd5da6c624905497beab2a5d5
Java
serkan1496/rental-portal
/src/main/java/com/kafein/rental/controller/CompanyController.java
UTF-8
2,696
2.140625
2
[]
no_license
package com.kafein.rental.controller; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.kafein.rental.common.ServiceResponse; import com.kafein.rental.model.Company; import com.kafein.rental.service.CompanyServiceImpl; @RestController @RequestMapping(path = "/company") public class CompanyController { // private static final Logger logger = LoggerFactory.getLogger(CompanyController.class); @Autowired CompanyServiceImpl companyService; @PostMapping(path = "/save", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ServiceResponse> save(@RequestBody Company entity) { ServiceResponse response = companyService.save(entity); return new ResponseEntity<ServiceResponse> (response, response.getStatus()); } @PutMapping(path = "/update", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ServiceResponse> update(@RequestBody Company entity) { ServiceResponse response = companyService.update(entity); return new ResponseEntity<ServiceResponse> (response, response.getStatus()); } @GetMapping(path = "/getById/{id}" ,produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ServiceResponse> getById(@PathVariable("id") Long id){ ServiceResponse response = companyService.getById(id); return new ResponseEntity<ServiceResponse> (response, response.getStatus()); } @GetMapping(path = "/findAll" ,produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ServiceResponse> findAll(){ ServiceResponse response = companyService.findAll(); return new ResponseEntity<ServiceResponse> (response, response.getStatus()); } @DeleteMapping(path = "/deleteById/{id}" ,produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ServiceResponse> deleteById(@PathVariable("id") Long id) { ServiceResponse response = companyService.deleteById(id); return new ResponseEntity<ServiceResponse> (response, response.getStatus()); } }
true
014be92d2af5368c17e42b4f9d5c42582711a1fc
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/mportuesisf_ScreenInfo/app/src/main/java/com/jotabout/screeninfo/ScreenInfo.java
UTF-8
8,633
1.734375
2
[]
no_license
// isComment package com.jotabout.screeninfo; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * isComment */ public class isClassOrIsInterface extends Activity { // isComment // isComment // isComment private static final int isVariable = isIntegerConstant; private static final int isVariable = isNameExpr.isFieldAccessExpr; private static final int isVariable = isNameExpr.isFieldAccessExpr + isIntegerConstant; // isComment // isComment // isComment Dialog isVariable; Screen isVariable; // isComment // isComment // isComment @Override public void isMethod(Bundle isParameter) { super.isMethod(isNameExpr); isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr = new Screen(this); } @Override protected void isMethod() { super.isMethod(); isMethod(); isMethod(); isMethod(); isMethod(); isMethod(); isMethod(); isMethod(); isMethod(); isMethod(); } // isComment // isComment // isComment /** * isComment */ public void isMethod() { ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod()); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod()); } /** * isComment */ public void isMethod() { ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(this)); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(this)); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(this)); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(this)); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); } /** * isComment */ private void isMethod() { ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); } /** * isComment */ private void isMethod() { TextView isVariable = ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); isNameExpr.isMethod(isNameExpr.isMethod(this)); } /** * isComment */ private void isMethod() { TextView isVariable = ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); isNameExpr.isMethod(isNameExpr.isMethod(this)); } /** * isComment */ private void isMethod() { TextView isVariable = ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); isNameExpr.isMethod(isNameExpr.isMethod()); } /** * isComment */ private void isMethod() { TextView isVariable = ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); isNameExpr.isMethod(isNameExpr.isMethod(this)); } /** * isComment */ private void isMethod() { TextView isVariable = ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); isNameExpr.isMethod(isNameExpr.isMethod(this)); } /** * isComment */ private void isMethod() { TextView isVariable = ((TextView) isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr.isMethod())); } // isComment // isComment // isComment /** * isComment */ private String isMethod() { String isVariable = "isStringConstant"; PackageInfo isVariable; try { isNameExpr = isMethod().isMethod(isMethod(), isIntegerConstant); isNameExpr = this.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr) + "isStringConstant" + isNameExpr.isFieldAccessExpr; } catch (NameNotFoundException isParameter) { ; } return isNameExpr; } @Override protected Dialog isMethod(int isParameter) { isNameExpr = null; switch(isNameExpr) { case isNameExpr: isNameExpr = new Dialog(this); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); ((TextView) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isMethod()); ((Button) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(new View.OnClickListener() { @Override public void isMethod(View isParameter) { isNameExpr.isMethod(); } }); break; } return isNameExpr; } // isComment // isComment // isComment /** * isComment */ private void isMethod() { String isVariable = isNameExpr.isMethod(this); final Intent isVariable = new Intent(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr.isMethod("isStringConstant"); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr, isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr, isNameExpr); isMethod(isNameExpr.isMethod(isNameExpr, isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr))); } /** * isComment */ private String isMethod(int isParameter) { StringBuilder isVariable = new StringBuilder(); isNameExpr.isMethod(isMethod(isNameExpr)); isNameExpr.isMethod("isStringConstant"); isNameExpr.isMethod(isMethod()); isNameExpr.isMethod("isStringConstant"); return isNameExpr.isMethod(); } // isComment // isComment // isComment @Override public boolean isMethod(Menu isParameter) { isNameExpr.isMethod(isIntegerConstant, isNameExpr, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr); isNameExpr.isMethod(isIntegerConstant, isNameExpr, isIntegerConstant, isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr.isFieldAccessExpr); return true; } @Override public boolean isMethod(MenuItem isParameter) { switch(isNameExpr.isMethod()) { case isNameExpr: isMethod(isNameExpr); return true; case isNameExpr: isMethod(); return true; } return true; } }
true
35c40f7a19a264ed54116ca778a556158c07a979
Java
timipaul/shijin3_android-dev
/app/src/main/java/com/shijinsz/shijin/ui/store/GoodsSpecificationActivity.java
UTF-8
10,759
1.632813
2
[]
no_license
package com.shijinsz.shijin.ui.store; import android.app.Activity; import android.app.ActivityOptions; import android.app.admin.SystemUpdatePolicy; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.baidu.mapapi.common.SysOSUtil; import com.bumptech.glide.Glide; import com.hongchuang.hclibrary.recyclerview.PowerfulRecyclerView; import com.hongchuang.hclibrary.storage.ShareDataManager; import com.hongchuang.hclibrary.storage.SharedPreferencesKey; import com.hongchuang.hclibrary.view.Utils; import com.hongchuang.ysblibrary.YSBSdk; import com.hongchuang.ysblibrary.model.model.OAuthService; import com.hongchuang.ysblibrary.model.model.bean.BaseBean; import com.hongchuang.ysblibrary.model.model.bean.ShoppingShopBean; import com.hongchuang.ysblibrary.model.model.bean.StoreGoodsBean; import com.hongchuang.ysblibrary.model.model.bean.StroeCommentBean; import com.shijinsz.shijin.R; import com.shijinsz.shijin.base.BaseActivity; import com.shijinsz.shijin.ui.store.adapter.SpecificationAdapter; import com.shijinsz.shijin.utils.ErrorUtils; import com.shijinsz.shijin.utils.LoginUtil; import java.lang.reflect.Method; import java.text.BreakIterator; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.OnClick; import retrofit.callback.YRequestCallback; /*** * 商品规格 */ public class GoodsSpecificationActivity extends BaseActivity { @BindView(R.id.goods_img) ImageView mImg; @BindView(R.id.goods_price) TextView mPrice; @BindView(R.id.sell_num) TextView mSellNum; @BindView(R.id.goods_type) TextView mType; @BindView(R.id.recycler) PowerfulRecyclerView mRecycler; @BindView(R.id.et_num) TextView mGoodsNum; SpecificationAdapter adapter; @BindView(R.id.add_shop_car) TextView mShopCar; private String goodsId; private String isVIP; List<StoreGoodsBean.Specification> list = new ArrayList<>(); List<StoreGoodsBean.Sku> listSku = new ArrayList<>(); LinkedHashMap<String, String> mapData = new LinkedHashMap<>(); Map<String,String> priceMap = new HashMap<>(); @Override public int bindLayout() { return R.layout.store_goods_specification; } @Override public void initView(View view) { //设置视图背景透明 translucentActivity(GoodsSpecificationActivity.this); isVIP = ShareDataManager.getInstance().getPara(SharedPreferencesKey.KEY_is_store_vip); adapter = new SpecificationAdapter(R.layout.goods_size_measure, list); mRecycler.setAdapter(adapter); adapter.setOnListen(new SpecificationAdapter.onListen() { @Override public void callback(String key, String val,int index) { String textVal = ""; mapData.put(key, val); for (Map.Entry<String, String> entry : mapData.entrySet()) { if (!textVal.equals("")) { textVal += "-"; } textVal += entry.getValue().length() > 0 ? entry.getValue() : entry.getKey(); if (entry.getValue().equals("")) { mShopCar.setBackgroundColor(getResources().getColor(R.color.color_6d)); mShopCar.setEnabled(false); } else { mShopCar.setBackgroundColor(getResources().getColor(R.color.color_fdb)); mShopCar.setEnabled(true); } } String textPrice = ""; if (!textVal.isEmpty()) { textPrice = priceMap.get(textVal); } mType.setText("选择 " + textVal); mPrice.setText("¥" + textPrice); } }); goodsId = getIntent().getStringExtra("goodsId"); getGoodsData(goodsId); } //获取数据 private void getGoodsData(String goodsId) { YSBSdk.getService(OAuthService.class).getGoodsDetails(goodsId, new YRequestCallback<ShoppingShopBean>() { @Override public void onSuccess(ShoppingShopBean var1) { StoreGoodsBean goodsData = var1.getGoods(); listSku.addAll(var1.getGoods().getSku()); for (int i = 0;i < var1.getGoods().getSku().size();i++){ StoreGoodsBean.Sku sku = var1.getGoods().getSku().get(i); if(isVIP.equals("true")){ //会员价 priceMap.put(sku.getAttriValStr(),String.valueOf(sku.getDiscount())); if (goodsData.getDiscount() > 0) { mPrice.setText("¥" + goodsData.getDiscount()); } else { mPrice.setText("¥" + goodsData.getPrice()); } }else{ //普通价 priceMap.put(sku.getAttriValStr(),String.valueOf(sku.getPrice())); mPrice.setText("¥" + goodsData.getPrice()); } } Glide.with(mContext).load(goodsData.getCoverImg()[0]).into(mImg); mSellNum.setText("已售" + goodsData.getSalesVolume() + "件"); String key = ""; for (int i = 0; i < goodsData.getAttribute().length; i++) { key += goodsData.getAttribute()[i].getKey() + " "; list.add(goodsData.getAttribute()[i]); mapData.put(goodsData.getAttribute()[i].getKey(), ""); } mType.setText("选择 " + key); adapter.notifyDataSetChanged(); } @Override public void onFailed(String var1, String message) { ErrorUtils.error(mContext, var1, message); } @Override public void onException(Throwable var1) { var1.printStackTrace(); } }); } @OnClick({R.id.tv_hide, R.id.img_cancel, R.id.layout, R.id.bt_reduce, R.id.bt_add, R.id.bt_car, R.id.add_shop_car}) public void OnclickView(View view) { switch (view.getId()) { case R.id.tv_hide: case R.id.img_cancel: finish(); break; case R.id.layout: break; case R.id.bt_reduce: setGoodsNum(-1); break; case R.id.bt_add: setGoodsNum(1); break; case R.id.bt_car: //查看购物车 if (!LoginUtil.isLogin(mContext)) { return; } break; case R.id.add_shop_car: //新增购物车 if (!LoginUtil.isLogin(mContext)) { return; } addCarData(); break; } } //购物车新增数据 private void addCarData() { Map<String, Object> map = new HashMap<>(); String attri = ""; for (Map.Entry<String, String> entry : mapData.entrySet()) { if (attri.equals("")) { attri += entry.getValue(); } else { attri += "-" + entry.getValue(); } } map.put("attri", attri); map.put("num", mGoodsNum.getText().toString()); YSBSdk.getService(OAuthService.class).addCarGoods(goodsId, map, new YRequestCallback<StoreGoodsBean>() { @Override public void onSuccess(StoreGoodsBean var1) { AlertDialog alert = new AlertDialog.Builder(mContext).create(); alert.setTitle("操作提示"); alert.setMessage("添加购物车成功"); alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); alert.show(); } @Override public void onFailed(String var1, String message) { ErrorUtils.error(mContext, var1, message); } @Override public void onException(Throwable var1) { var1.printStackTrace(); } }); } public void setGoodsNum(int val) { int num = Integer.valueOf(mGoodsNum.getText().toString()); num += val; if (num < 0) { num = 0; } mGoodsNum.setText(String.valueOf(num)); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { setResult(1); finish(); return true; } return super.onKeyDown(keyCode, event); } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.bottom_silent, R.anim.bottom_out); } //设置视图透明 private void translucentActivity(Activity activity) { try { activity.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); activity.getWindow().getDecorView().setBackground(null); Method activityOptions = Activity.class.getDeclaredMethod("getActivityOptions"); activityOptions.setAccessible(true); Object options = activityOptions.invoke(activity); Class<?>[] classes = Activity.class.getDeclaredClasses(); Class<?> aClass = null; for (Class clazz : classes) { if (clazz.getSimpleName().contains("TranslucentConversionListener")) { aClass = clazz; } } Method method = Activity.class.getDeclaredMethod("convertToTranslucent", aClass, ActivityOptions.class); method.setAccessible(true); method.invoke(activity, null, options); } catch (Throwable t) { t.printStackTrace(); } } }
true
f3d19f71e70ef747cb36af53c1ac1e9eb1918739
Java
kwsantiago/Hackerrank-Solutions
/Data-Structures/Linked-Lists/insertPositionSinglyLinkedList.java
UTF-8
671
3.078125
3
[]
no_license
static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data,int position){ SinglyLinkedListNode newNode = new SinglyLinkedListNode(data); int i = 0; if(position == 0){ newNode.next = head; return newNode; } else{ SinglyLinkedListNode currentNode = head; while(--position > 0) currentNode = currentNode.next; SinglyLinkedListNode copyNode = currentNode.next; currentNode.next = newNode; newNode.next = currentNode.next; currentNode.next.next = copyNode; return head; } }
true
948fac8c937574c8c6ecaee2f6b4808accce4f4c
Java
fanshen2010/P2P_lending
/p2p_all/p2p_corebiz/target/classes/cn/com/p2p/customer/service/dto/CustomerDto.java
UTF-8
1,281
2.203125
2
[]
no_license
package cn.com.p2p.customer.service.dto; import cn.com.p2p.domain.customer.entity.CustEnterpriseInfo; import cn.com.p2p.domain.customer.entity.CustPersonalInfo; import cn.com.p2p.loan.service.dto.LoanEnterpriseInfoDto; import cn.com.p2p.loan.service.dto.LoanPersonalBasicDto; /** * 融资客户个人/企业信息数据传输对象 * 主要用于后台个人/企业客户管理页面 * @author * */ public class CustomerDto { /**个人融资客户信息*/ private CustPersonalInfo personalDto; /**企业融资客户信息*/ private CustEnterpriseInfo enterpriseDto; /**个人/企业融资统计信息*/ private StatisticalDto statisticalDto; public CustPersonalInfo getPersonalDto() { return personalDto; } public void setPersonalDto(CustPersonalInfo personalDto) { this.personalDto = personalDto; } public CustEnterpriseInfo getEnterpriseDto() { return enterpriseDto; } public void setEnterpriseDto(CustEnterpriseInfo enterpriseDto) { this.enterpriseDto = enterpriseDto; } public StatisticalDto getStatisticalDto() { return statisticalDto; } public void setStatisticalDto(StatisticalDto statisticalDto) { this.statisticalDto = statisticalDto; } }
true
869aa938d1f1be58a221ddc4452000b353b62e30
Java
ozkandemir/XText
/com.ykb.umap.dsl.ui/src-gen/com/ykb/umap/dsl/ui/contentassist/AbstractProductProposalProvider.java
UTF-8
9,084
1.84375
2
[]
no_license
/* * generated by Xtext */ package com.ykb.umap.dsl.ui.contentassist; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.*; import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor; import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext; /** * Represents a generated, default implementation of superclass {@link org.eclipse.xtext.xbase.ui.contentassist.XbaseProposalProvider}. * Methods are dynamically dispatched on the first parameter, i.e., you can override them * with a more concrete subtype. */ @SuppressWarnings("all") public class AbstractProductProposalProvider extends org.eclipse.xtext.xbase.ui.contentassist.XbaseProposalProvider { public void completeUMAPDsl_Elements(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCompilationUnit_NamespaceUnit(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCompilationUnit_UseUnit(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCompilationUnit_ProductUnit(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeCompilationUnit_DataTypes(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeDataType_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeDataType_Parameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeDataType_OperationUnits(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeUseUnit_ProductUnit(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeNamespaceUnit_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeProductUnit_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeProductUnit_Parameters(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeProductUnit_OperationUnits(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeParameterElement_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeParameterElement_Type(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeOperationUnit_Name(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeOperationUnit_Controls(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeOperationUnit_Statements(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeStatement_Statement(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void completeControlElement_Expression(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeControlElement_ControlStatement(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeExpressionElement_Parameter(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeExpressionElement_Operator(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeExpressionElement_Right(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeControlStatementElement_Error(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void complete_UMAPDsl(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_CompilationUnit(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_DataType(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_UseUnit(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_NamespaceUnit(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_QUALIFIEDID(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ProductUnit(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ParameterElement(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_UMAPDataTypes(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OperationUnit(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_Statement(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ControlElement(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ExpressionElement(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OPERATORS(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_ControlStatementElement(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } }
true
a19552bc3b51994eba5be4b2f7136a81cbccdbb3
Java
adilson-utiama/casadocodigo-javaee7
/src/main/java/br/com/casadocodigo/conf/ConfigureJMSDestination.java
UTF-8
287
1.671875
2
[]
no_license
package br.com.casadocodigo.conf; import javax.ejb.Singleton; import javax.jms.JMSDestinationDefinition; @JMSDestinationDefinition( name="java:/jms/topics/CarrinhoComprasTopico", interfaceName = "javax.jms.Topic" ) @Singleton public class ConfigureJMSDestination { }
true
d58698bb6d19536b6880ad3cf640b8d8214d7f84
Java
aronbsz/automatalearning
/automatalearning/src/main/java/hu/bme/mit/automatalearning/algorithm/dhc/DirectHypothesisConstructionMealy.java
UTF-8
8,346
2.25
2
[]
no_license
package hu.bme.mit.automatalearning.algorithm.dhc; import java.io.Serializable; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Set; import com.google.common.collect.Collections2; import com.google.common.collect.Sets; import java.util.List; import java.util.Map; import java.util.Optional; import hu.bme.mit.automatalearning.algorithm.ActiveLearningAlgorithm; import hu.bme.mit.automatalearning.hypothesis.DHCHypothesis; import hu.bme.mit.automatalearning.hypothesis.Hypothesis; import hu.bme.mit.automatalearning.hypothesis.DHCHypothesisMealy; import hu.bme.mit.automatalearning.teacher.Teacher; import hu.bme.mit.automatalearning.util.Utils; import hu.bme.mit.mealymodel.MealyMachine; import hu.bme.mit.mealymodel.State; import hu.bme.mit.mealymodel.Transition; public class DirectHypothesisConstructionMealy<I, O, M, S, T> extends ActiveLearningAlgorithm<I, O, DHCHypothesis<I, O, M, S, T>>{ Collection<? extends I> alphabet; HashSet<List<? extends I>> splitters; DHCHypothesis<I, O, M, S, T> hypothesis; public DirectHypothesisConstructionMealy(Teacher<I, O, DHCHypothesis<I, O, M, S, T>, ?> teacher, Collection<? extends I> alphabet, DHCHypothesis<I, O, M, S, T> hypothesis) { this.teacher = teacher; this.alphabet = alphabet; this.splitters = new HashSet<>(); this.hypothesis = hypothesis; } public DHCHypothesis<I, O, M, S, T> execute() { List<? extends I> counterExample = null; DHCHypothesis<I, O, M, S, T> h = null; do { if(counterExample != null) { refineHypothesis(counterExample); } h = constructHypothesis(); Utils.logHypothesisToJSON((Hypothesis<String, String, MealyMachine, State, Transition>) h, "DHC"); counterExample = teacher.equivalenceQuery(h, alphabet); }while(counterExample != null); return h; } public DHCHypothesis<I, O, M, S, T> constructHypothesis() { hypothesis.resetHypothesis(); ArrayDeque<QueueElement<I, O, S>> statesToComplete = new ArrayDeque<>(); statesToComplete.add(new QueueElement<I, O, S>(null, null, null, null)); Map<List<O>, S> signatures = new HashMap<>(); while(!statesToComplete.isEmpty()) { QueueElement<I, O, S> currentElement = statesToComplete.pop(); List<I> currSequence = getAccessSequence(currentElement); LinkedHashMap<I, O> currAlphabetSignature = findAlphabetOutputSignature(currSequence); List<O> currSignature = new ArrayList<>(currAlphabetSignature.values()); currSignature.addAll(findSplitterOutputSignature(currSequence)); S sibling = findStateWithSameSignature(signatures, currSignature); if(sibling != null) { //If a sibling exists, merge currState to sibling hypothesis.addTransition(currentElement.parentState, sibling, currentElement.input, currentElement.output); }else { //If there are no siblings, the targetState of all transitions going from currentState is set to a new state S newState = currentElement.parentElement == null ? hypothesis.addInitialState() : hypothesis.createNewState(); if (currentElement.parentElement != null) { hypothesis.addTransition(currentElement.parentState, newState, currentElement.input, currentElement.output); } signatures.put(currSignature, newState); for(I symbol : hypothesis.getHypothesisInputAlphabet()) { statesToComplete.add(new QueueElement<I, O, S>(newState, currentElement, symbol, currAlphabetSignature.get(symbol))); } } } return hypothesis; } private LinkedHashMap<I, O> findAlphabetOutputSignature(List<I> accessSequence){ LinkedHashMap<I, O> currSignature = new LinkedHashMap<>(); for(I symbol : this.alphabet) { List<I> currSequenceWithSymbol = new ArrayList<>(accessSequence); currSequenceWithSymbol.add(symbol); O outputSymbol = teacher.membershipQuery(currSequenceWithSymbol); currSignature.put(symbol, outputSymbol); } return currSignature; } private List<O> findSplitterOutputSignature(List<I> accessSequence){ List<O> retVal = new ArrayList<>(); for(List<? extends I> splitter : this.splitters) { List<I> currSequenceWithSymbol = new ArrayList<>(accessSequence); currSequenceWithSymbol.addAll(splitter); O outputSymbol = teacher.membershipQuery(currSequenceWithSymbol); retVal.add(outputSymbol); } return retVal; } private S findStateWithSameSignature(Map<List<O>, S> prevSignature, List<O> currSignature) { Optional<List<O>> exists = prevSignature.keySet().stream().filter(list -> list.equals(currSignature)).findFirst(); if(exists.isPresent()) { return prevSignature.get(exists.get()); } return null; } private List<I> getAccessSequence(QueueElement<I, O, S> currElement) { List<I> word = new ArrayList<>(); QueueElement<I, O, S> parent = currElement.parentElement; I in = currElement.input; while (parent != null && in != null) { word.add(in); in = parent.input; parent = parent.parentElement; } Collections.reverse(word); return word; } public void refineHypothesis(List<? extends I> counterExample) { for(int i = 0; i < counterExample.size(); i++) { List<? extends I> currSuffix = counterExample.subList(0+i, counterExample.size()); if(currSuffix.size() != 0 && currSuffix.size() != 1 && !splitters.stream().anyMatch(l -> l.equals(currSuffix))) { this.splitters.add(new ArrayList<>(currSuffix)); } } } /*public static void test() { Alphabet in = MealeymodelFactory.eINSTANCE.createAlphabet(); in.getCharacters().add("I1"); in.getCharacters().add("I2"); Alphabet out = MealeymodelFactory.eINSTANCE.createAlphabet(); out.getCharacters().add("O1"); out.getCharacters().add("O2"); List<State> s = new ArrayList<>(); State s1 = MealeymodelFactory.eINSTANCE.createState(); State s2 = MealeymodelFactory.eINSTANCE.createState(); State s3 = MealeymodelFactory.eINSTANCE.createState(); State s4 = MealeymodelFactory.eINSTANCE.createState(); State s5 = MealeymodelFactory.eINSTANCE.createState(); s1.setName("state 1"); s2.setName("state 2"); s3.setName("state 3"); s4.setName("state 4"); s5.setName("state 5"); s.add(s1); s.add(s2); s.add(s3); s.add(s4); s.add(s5); hu.bme.mit.mealeymodel.Transition t1 = MealeymodelFactory.eINSTANCE.createTransition(); hu.bme.mit.mealeymodel.Transition t2 = MealeymodelFactory.eINSTANCE.createTransition(); hu.bme.mit.mealeymodel.Transition t3 = MealeymodelFactory.eINSTANCE.createTransition(); hu.bme.mit.mealeymodel.Transition t4 = MealeymodelFactory.eINSTANCE.createTransition(); hu.bme.mit.mealeymodel.Transition t5 = MealeymodelFactory.eINSTANCE.createTransition(); t1.setInput("I1"); t2.setInput("I2"); t3.setInput("I3"); t4.setInput("I4"); t5.setInput("I3"); t1.setOutput("O1"); t2.setOutput("O1"); t3.setOutput("O1"); t4.setOutput("O2"); t5.setOutput("O1"); t1.setSourceState(s1); t2.setSourceState(s2); t3.setSourceState(s3); t4.setSourceState(s2); t5.setSourceState(s5); t1.setTargetState(s2); t2.setTargetState(s3); t3.setTargetState(s4); t4.setTargetState(s5); List<hu.bme.mit.mealeymodel.Transition> trans = new ArrayList<>(); trans.add(t1); trans.add(t2); trans.add(t3); trans.add(t4); trans.add(t5); DHCHypothesisMealy hy = new DHCHypothesisMealy(in, out, s1, s, trans); hy.rerouteAllTransitions(s5, s3); System.out.println(); }*/ //Great idea of Queue handling from the LearnLib framework static final class QueueElement<I, O, S> implements Serializable { private final S parentState; private final QueueElement<I, O, S> parentElement; private final I input; private final O output; private final int depth; QueueElement(S parentState, QueueElement<I, O, S> parentElement, I input, O output) { this.parentState = parentState; this.parentElement = parentElement; this.input = input; this.output = output; this.depth = (parentElement != null) ? parentElement.depth + 1 : 0; } } }
true
cb64f44b6d69208fb7af62e90efdc268a1d86249
Java
asynkronos/android-sensor-display
/src/com/asynkronos/android/sensordisplay/RotationVectorData.java
UTF-8
779
1.898438
2
[]
no_license
package com.asynkronos.android.sensordisplay; import com.asynkronos.android.sensordisplay.R; import android.os.Bundle; /** * * @author Michael Bruno * */ public class RotationVectorData extends SensorDashActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.four); sensorId = SensorType.ROTATION_VECTOR; init(); if(supported()){ createViews(R.string.rotation_vector,R.string.x_rot_lb, R.string.y_rot_lb,R.string.z_rot_lb, R.string.f_rot_lb); createSlider(true); createSaveToggle(true); }else{ createNoSupport(R.string.rotation_vector); } } }
true
48e2ec1c0566f7231a8786c5b49f21bdee28cb7a
Java
sqxz/renren-fast
/src/main/java/io/renren/modules/test/utils/WriteJsonFileThread.java
UTF-8
598
2.453125
2
[ "Apache-2.0" ]
permissive
package io.renren.modules.test.utils; /** * @author CT * @date 2019/6/2914:05 * @describe WriteFileThread用于 */ public class WriteJsonFileThread extends Thread{ String toWriteString = "";//定义线程内变量 String filePath = ""; public WriteJsonFileThread(String stringJson, String filePath){ //定义带参数的构造函数,达到初始化线程内变量的值 this.toWriteString = stringJson; this.filePath = filePath; } @Override public void run() { WriteJsonFile.WriteConfigJson(this.toWriteString, this.filePath); } }
true
81c829d1723fac8e38aad41c816325f6a9709ff3
Java
yashjhamnani7/Assignments1
/CoreJavaProj2/src/com/strinbuffer/Banner.java
UTF-8
404
3.046875
3
[]
no_license
package com.strinbuffer; class Banner { public static void main(String args[]) throws Exception { StringBuilder s1=new StringBuilder("Welcome to Java"); int len=s1.length(); char s; for(int i=0;i<len;i++) { s=s1.charAt(s1.length()-1); s1 = new StringBuilder(s+s1.substring(0,s1.length()-1)); System.out.println("\r"+s1); Thread.sleep(500); } } }
true
e4ca0b9202ef6151f49c883de5b81dd54d7c3bde
Java
jgofman/Interpreter-for-a-Toy-Programming-Language
/Interpreter.java
UTF-8
4,326
3.96875
4
[]
no_license
// Jacob Gofman // Professor Ernest Davis // Data Structures, Honors Section // Programming Assignment 4 import java.util.Scanner; public class Interpreter { static boolean defining = false; public static void main(String[] args) { boolean notDone = true; String funcName = ""; Scanner value = new Scanner(System.in); System.out.println("Welcome to Interpreter!"); // Nav Menu Start while (notDone) { // Directions of possible commands System.out.println("\nAssign <variable name> <expression> - Assign a prefix-formatted expression to variable"); System.out.println("Define <function name> - Define a function name (beginning of the function definition)"); System.out.println("End <function name> - Ends the function definition initiated by Define <function> command"); System.out.println("Call <function name> - Calls pre-defined function by name"); System.out.println("For <expression> <statement> - Initiates 'for' loop on the 'statement' for an 'expression' # of times "); System.out.println("Quit - Terminate the program."); System.out.println("\nINPUT: "); String input = value.nextLine(); // Split input into words and capitalize them String[] commands = input.split("\\s+"); if (commands[0].equalsIgnoreCase("assign") && (commands.length >= 3)) { // Assign Statement stmt1 = new Statement(input, commands); if (!defining) { // if not defining, evaluate statement String result = stmt1.evaluatePrefix(); if (result.equalsIgnoreCase("Invalid")) { System.out.println("\nInvalid operation. Variable not found."); } } else { // add to function Function.FunctionTable.get(funcName).addStmt(stmt1); } } else if (commands[0].equalsIgnoreCase("define") && (commands.length == 2)) { // Define if (!defining) { // if not defining, then define if statement is deemed correct if (!checkExist(commands[1])) { System.out.println("Defining " + commands[1]); define(commands[1]); funcName = commands[1]; } else { System.out.println("\nInvalid operation. Function name missing."); } } else { // if already defining, return invalid System.out.println("\nInvalid operation. You cannot define a function within a function."); } } else if (commands[0].equalsIgnoreCase("end") && (commands.length == 2)) { // End if (!defining) { // if not defining System.out.println("\nInvalid operation. There is no function being defined."); } else { // if defining, then end the function definition if (checkExist(commands[1])) { System.out.println("Ending " + commands[1]); end(); } else { System.out.println("\nInvalid operation. Function name missing."); } } } else if (commands[0].equalsIgnoreCase("call") && (commands.length == 2)) { // Call Statement stmt1 = new Statement(input, commands); if (!defining) { // if not defining, call function if (checkExist(commands[1])) { stmt1.call(commands[1]); } else { System.out.println("\nFunction with this name does not exist or is missing."); } } else { // if defining, add to function definition (statement array) Function.FunctionTable.get(funcName).addStmt(stmt1); } } else if (commands[0].equalsIgnoreCase("for") && (commands.length >= 4)) { Statement stmt1 = new Statement(input, commands); if (!defining) { // if not defining evaluate for loop stmt1.forLoop(stmt1); } else { // if defining add statement to function definition (statement array) Function.FunctionTable.get(funcName).addStmt(stmt1); } } else if (commands[0].equalsIgnoreCase("quit") && (commands.length == 1)) { // Quit System.out.println("\nThank you for using Interpreter. Have a nice day!"); System.exit(0); } else { // Unrecognized input System.out.println("\nInput not recognized, try again: "); } } // Nav Menu End } // Checks if function already exists in FunctionTable public static boolean checkExist(String name) { return Function.FunctionTable.containsKey(name); } public static void define(String fName) // enable define function { defining = true; Function f = new Function(fName); } public static void end() // end define function { if (defining == true) defining = false; } }
true
12ada74faa6da83bccee326cd9e08c426a5ceb78
Java
weichun97/screen
/src/main/resources/template/SwaggerConfig.java
UTF-8
2,165
2.03125
2
[]
no_license
package com.github.weichun97.common.swagger.config; import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.Arrays; import java.util.HashSet; import java.util.List; @Configuration @EnableSwagger2 @EnableSwaggerBootstrapUI /** * @author cocoyang * @version 1.0 **/ public class SwaggerConfig { @Value("${spring.application.name}") private String description; /** * 创建获取api应用 * @return */ @Bean public Docket createRestApi() { ParameterBuilder pb = new ParameterBuilder(); pb.name("Authorization").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).defaultValue("Bearer ").build(); List<Parameter> params = Arrays.asList(pb.build()); HashSet<String> strings = new HashSet<>(); strings.add("application/json"); return new Docket(DocumentationType.SWAGGER_2) .globalOperationParameters(params) .pathMapping("/") .select() .apis(RequestHandlerSelectors.basePackage("com.github.weichun97")) .paths(PathSelectors.any()) .build() .apiInfo(new ApiInfoBuilder() .title(description+"-api文档") .description(description+"-api文档") .version("1.0") .build()).produces(strings); } }
true
f09492585cc0df380e737a3adc90b19e77b686ba
Java
jambestwick/HackWechat
/app/src/main/java/com/tencent/mm/ui/h$6.java
UTF-8
555
1.523438
2
[]
no_license
package com.tencent.mm.ui; import android.content.ComponentName; import android.content.Intent; class h$6 implements Runnable { final /* synthetic */ h xFs; h$6(h hVar) { this.xFs = hVar; } public final void run() { Intent intent = new Intent(); intent.setComponent(new ComponentName(e$h.xEp, "com.tencent.mm.booter.MMReceivers$ToolsProcessReceiver")); intent.putExtra("tools_process_action_code_key", "com.tencent.mm.intent.ACTION_START_TOOLS_PROCESS"); this.xFs.sendBroadcast(intent); } }
true
c84ccb51b7791b63d9464696594f1c0d9909e7f9
Java
arthurxiaohz/ic-card
/j-hi-20110703/src/org/hi/base/menu/action/MenuLinkPageInfo.java
UTF-8
3,709
1.851563
2
[]
no_license
package org.hi.base.menu.action; import java.sql.Timestamp; import java.util.Date; import org.hi.framework.web.PageInfoView; import org.hi.framework.security.action.AuthorityPageInfo; import org.hi.base.menu.action.MenuPageInfo; import org.hi.base.organization.action.HiUserPageInfo; public class MenuLinkPageInfo extends PageInfoView{ protected Integer f_id; protected String f_id_op; protected String f_linkUrl; protected String f_linkUrl_op; protected String f_displayRef; protected String f_displayRef_op; protected String f_description; protected String f_description_op; protected Double f_sequence; protected String f_sequence_op; protected Integer f_menuLinkType; protected String f_menuLinkType_op; protected AuthorityPageInfo authority; protected MenuPageInfo menu; protected HiUserPageInfo creator; public Integer getF_id() { return this.f_id; } public void setF_id(Integer f_id) { this.f_id = f_id; } public String getF_id_op() { return this.f_id_op; } public void setF_id_op(String f_id_op) { this.f_id_op = f_id_op; } public String getF_linkUrl() { return this.f_linkUrl; } public void setF_linkUrl(String f_linkUrl) { this.f_linkUrl = f_linkUrl; } public String getF_linkUrl_op() { return this.f_linkUrl_op; } public void setF_linkUrl_op(String f_linkUrl_op) { this.f_linkUrl_op = f_linkUrl_op; } public String getF_displayRef() { return this.f_displayRef; } public void setF_displayRef(String f_displayRef) { this.f_displayRef = f_displayRef; } public String getF_displayRef_op() { return this.f_displayRef_op; } public void setF_displayRef_op(String f_displayRef_op) { this.f_displayRef_op = f_displayRef_op; } public String getF_description() { return this.f_description; } public void setF_description(String f_description) { this.f_description = f_description; } public String getF_description_op() { return this.f_description_op; } public void setF_description_op(String f_description_op) { this.f_description_op = f_description_op; } public Double getF_sequence() { return this.f_sequence; } public void setF_sequence(Double f_sequence) { this.f_sequence = f_sequence; } public String getF_sequence_op() { return this.f_sequence_op; } public void setF_sequence_op(String f_sequence_op) { this.f_sequence_op = f_sequence_op; } public Integer getF_menuLinkType() { return this.f_menuLinkType; } public void setF_menuLinkType(Integer f_menuLinkType) { this.f_menuLinkType = f_menuLinkType; } public String getF_menuLinkType_op() { return this.f_menuLinkType_op; } public void setF_menuLinkType_op(String f_menuLinkType_op) { this.f_menuLinkType_op = f_menuLinkType_op; } public AuthorityPageInfo getAuthority() { return authority; } public void setAuthority(AuthorityPageInfo authority) { this.authority = authority; } public MenuPageInfo getMenu() { return menu; } public void setMenu(MenuPageInfo menu) { this.menu = menu; } public HiUserPageInfo getCreator() { return creator; } public void setCreator(HiUserPageInfo creator) { this.creator = creator; } }
true
f91df0dd86a223ff7883b8e1c54bf9ed15e3a384
Java
IDragonfire/downlords-faf-client
/src/main/java/com/faforever/client/map/MapVaultController.java
UTF-8
8,131
1.757813
2
[ "MIT" ]
permissive
package com.faforever.client.map; import com.faforever.client.fx.JavaFxUtil; import com.faforever.client.fx.WindowController; import com.faforever.client.i18n.I18n; import com.faforever.client.map.event.MapUploadedEvent; import com.faforever.client.preferences.PreferencesService; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.stage.DirectoryChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.File; import java.lang.invoke.MethodHandles; import java.nio.file.Path; import java.util.List; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.function.Function; import java.util.stream.Collectors; import static com.faforever.client.fx.WindowController.WindowButtonType.CLOSE; public class MapVaultController { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final int TOP_ELEMENT_COUNT = 7; private static final int MAX_SUGGESTIONS = 10; @FXML Pane searchResultGroup; @FXML Pane searchResultPane; @FXML Pane showroomGroup; @FXML Pane loadingPane; @FXML TextField searchTextField; @FXML Pane newestMapsPane; @FXML Pane popularMapsPane; @FXML Pane recommendedMapsPane; @FXML Pane mapVaultRoot; @Resource MapService mapService; @Resource ApplicationContext applicationContext; @Resource MapDetailController mapDetailController; @Resource I18n i18n; @Resource EventBus eventBus; @Resource PreferencesService preferencesService; private boolean initialized; @FXML void initialize() { loadingPane.managedProperty().bind(loadingPane.visibleProperty()); showroomGroup.managedProperty().bind(showroomGroup.visibleProperty()); searchResultGroup.managedProperty().bind(searchResultGroup.visibleProperty()); } @PostConstruct void postConstruct() { Node mapDetailRoot = mapDetailController.getRoot(); mapVaultRoot.getChildren().add(mapDetailRoot); AnchorPane.setTopAnchor(mapDetailRoot, 0d); AnchorPane.setRightAnchor(mapDetailRoot, 0d); AnchorPane.setBottomAnchor(mapDetailRoot, 0d); AnchorPane.setLeftAnchor(mapDetailRoot, 0d); mapDetailRoot.setVisible(false); eventBus.register(this); } public void setUpIfNecessary() { if (initialized) { return; } initialized = true; displayShowroomMaps(); JavaFxUtil.makeSuggestionField(searchTextField, this::createMapSuggestions, aVoid -> onSearchMapButtonClicked()); } private void displayShowroomMaps() { enterLoadingState(); mapService.getMostPlayedMaps(TOP_ELEMENT_COUNT).thenAccept(maps -> populateMaps(maps, popularMapsPane)) .thenCompose(aVoid -> mapService.getMostLikedMaps(TOP_ELEMENT_COUNT)).thenAccept(maps -> populateMaps(maps, recommendedMapsPane)) .thenCompose(aVoid -> mapService.getNewestMaps(TOP_ELEMENT_COUNT)).thenAccept(maps -> populateMaps(maps, newestMapsPane)) .thenRun(this::enterShowroomState) .exceptionally(throwable -> { logger.warn("Could not populate maps", throwable); return null; }); } @FXML void onSearchMapButtonClicked() { if (searchTextField.getText().isEmpty()) { onResetButtonClicked(); return; } enterSearchResultState(); mapService.lookupMap(searchTextField.getText(), 100) .thenAccept(this::displaySearchResult); } private void enterLoadingState() { showroomGroup.setVisible(false); searchResultGroup.setVisible(false); loadingPane.setVisible(true); } private void populateMaps(List<MapBean> maps, Pane pane) { ObservableList<Node> children = pane.getChildren(); Platform.runLater(() -> { children.clear(); for (MapBean map : maps) { MapTileController controller = applicationContext.getBean(MapTileController.class); controller.setMap(map); controller.setOnOpenDetailListener(this::onShowMapDetail); children.add(controller.getRoot()); } }); } @FXML void onResetButtonClicked() { searchTextField.clear(); showroomGroup.setVisible(true); searchResultGroup.setVisible(false); } private void enterSearchResultState() { showroomGroup.setVisible(false); searchResultGroup.setVisible(true); loadingPane.setVisible(false); } private CompletionStage<Set<Label>> createMapSuggestions(String string) { return mapService.lookupMap(string, MAX_SUGGESTIONS) .thenApply(new Function<List<MapBean>, Set<Label>>() { @Override public Set<Label> apply(List<MapBean> mapBeans) { return mapBeans.stream() .map(result -> { String name = result.getDisplayName(); Label item = new Label(name) { @Override public int hashCode() { return getText().hashCode(); } @Override public boolean equals(Object obj) { return obj != null && obj.getClass() == getClass() && getText().equals(((Label) obj).getText()); } }; item.setUserData(name); return item; }) .collect(Collectors.toSet()); } }); } private void enterShowroomState() { showroomGroup.setVisible(true); searchResultGroup.setVisible(false); loadingPane.setVisible(false); } @FXML void onShowMapDetail(MapBean map) { mapDetailController.setMap(map); mapDetailController.getRoot().setVisible(true); mapDetailController.getRoot().requestFocus(); } @FXML void onSearchMapsButtonClicked() { if (searchTextField.getText().isEmpty()) { onResetButtonClicked(); return; } enterSearchResultState(); mapService.lookupMap(searchTextField.getText(), 100) .thenAccept(this::displaySearchResult); } private void displaySearchResult(List<MapBean> maps) { showroomGroup.setVisible(false); searchResultGroup.setVisible(true); populateMaps(maps, searchResultPane); } public void onUploadMapButtonClicked() { Platform.runLater(() -> { DirectoryChooser directoryChooser = new DirectoryChooser(); directoryChooser.setInitialDirectory(preferencesService.getPreferences().getForgedAlliance().getCustomMapsDirectory().toFile()); directoryChooser.setTitle(i18n.get("mapVault.upload.chooseDirectory")); File result = directoryChooser.showDialog(getRoot().getScene().getWindow()); if (result == null) { return; } openMapUploadWindow(result.toPath()); }); } public Node getRoot() { return mapVaultRoot; } private void openMapUploadWindow(Path path) { MapUploadController mapUploadController = applicationContext.getBean(MapUploadController.class); mapUploadController.setMapPath(path); Stage mapUploadWindow = new Stage(StageStyle.TRANSPARENT); mapUploadWindow.initModality(Modality.NONE); mapUploadWindow.initOwner(getRoot().getScene().getWindow()); WindowController windowController = applicationContext.getBean(WindowController.class); windowController.configure(mapUploadWindow, mapUploadController.getRoot(), true, CLOSE); mapUploadWindow.show(); } public void onRefreshClicked() { mapService.evictCache(); displayShowroomMaps(); } @Subscribe public void onMapUploaded(MapUploadedEvent event) { onRefreshClicked(); } }
true
67536c1c24f2c73561ce57d93d59aa632d7f6a3e
Java
togetherworks/training
/src/com/togetherworks/designpattern/decorator/StarbuzzCofe.java
UTF-8
656
3.140625
3
[]
no_license
package com.togetherworks.designpattern.decorator; public class StarbuzzCofe { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Beverage beverage=new Espresso(); System.out.println(beverage.getDescrpition()+" $:"+beverage.cost()); Beverage beverage2=new DarkRost(); System.out.println(beverage2.getDescrpition()+" $:"+beverage2.cost()); Beverage beverage3=new HouselBlend(); beverage3=new Mocha(beverage3); beverage3=new Soy(beverage3); beverage3=new Whip(beverage3); System.out.println(beverage3.getDescrpition()+" $:"+beverage3.cost()); } }
true
1b0acf95e9183c1ac453bdee9bcfee263d80e091
Java
muhammedsedef/Kodlama.io_Java-React_BootCamp
/registerAndLoginDemo/src/dataAccess/abstracts/UserDao.java
UTF-8
281
2.234375
2
[]
no_license
package dataAccess.abstracts; import java.util.List; import entities.concretes.User; public interface UserDao { void add(User user); User getUserById(int id); User getUserByEmail(String email); void update(User user); void delete(User user); List <User> getAllUser(); }
true
bbfd276ec88ac2eed177e56eebc126e94d0e0755
Java
R0DR1G0VEL0SA/Automatizacion3
/src/main/java/com/qvision/pagefactory/LoginPage.java
UTF-8
752
2.515625
3
[]
no_license
package com.qvision.pagefactory; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class LoginPage { @FindBy(name = "user") WebElement txtUsuario; @FindBy(name = "password") WebElement txtPasword; @FindBy(xpath = "//input[@class='button']") WebElement btnLogin; public void inicioSesion(String user, String password) { sendText(txtUsuario, user); sendText(txtPasword, password); clickOnElement(btnLogin); } //metodo generico para dar click en los elementos private void clickOnElement(WebElement element) { element.click(); } //metodo generico para enviar texto a los imput private void sendText(WebElement element, String text) { element.clear(); element.sendKeys(text); } }
true
56bb436a519f7db17b65c07f8276a87b46715ec9
Java
omererdogmus/Selenium_Methods
/src/main/java/Methods/Sel_013_XPath.java
UTF-8
1,519
2.703125
3
[]
no_license
package Methods; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class Sel_013_XPath { public static void main(String[] args) throws InterruptedException { // XPath is used to find location of element on the web page using HTML structure (XML) // Absolute XPath : it starts with single slash (/). // /html/body/div/div/div[2]/form/div[3]/div/div/div[2]/input // Relative XPath : it starts with double slash (//). // //*[@id="username"] WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://app.hubspot.com/login"); Thread.sleep(5000); // First Usage WebElement userElement = driver.findElement(By.xpath("//input[@id='username']")); userElement.sendKeys("newyork@sample.com"); WebElement userPassword = driver.findElement(By.xpath("//input[@id='password']")); userPassword.sendKeys("test123@"); WebElement loginBtn = driver.findElement(By.xpath("//button[@id=\"loginBtn\"]")); loginBtn.click(); // Second Usage By username = By.xpath("//input[@id='username']"); By password = By.xpath("//input[@id='password']"); By loginButton = By.xpath("//button[@id=\\\"loginBtn\\\"]"); ElementUtil.getElement(driver, username).sendKeys("omer@gmail.com"); ElementUtil.getElement(driver, password).sendKeys("123test@"); ElementUtil.getElement(driver, loginButton); } }
true
ac46520a3d58135c1a7373840477b25417fd5e84
Java
nkorzh/JavaStudy
/CSC_Java_Intro_Stepik/6/4_mail_task/src/MailMessage.java
UTF-8
225
2.3125
2
[]
no_license
import java.util.function.*; // TODO: make static and copy public class MailMessage extends AbstractSendable<String> { public MailMessage(String from, String to, String content) { super(from, to, content); } }
true
1f45b4f6cf37ae79a7854a47dfca6479c799417b
Java
iain-davis/Mumue
/src/main/java/org/mumue/mumue/connection/states/PlayerMenuHandler.java
UTF-8
2,597
2.453125
2
[]
no_license
package org.mumue.mumue.connection.states; import javax.inject.Inject; import com.google.inject.Singleton; import org.mumue.mumue.components.character.CharacterDao; import org.mumue.mumue.configuration.ApplicationConfiguration; import org.mumue.mumue.connection.Connection; import org.mumue.mumue.text.TextMaker; import org.mumue.mumue.text.TextName; @Singleton class PlayerMenuHandler implements ConnectionState { private final ConnectionStateProvider connectionStateProvider; private final CharacterDao characterDao; private final TextMaker textMaker; @Inject public PlayerMenuHandler(ConnectionStateProvider connectionStateProvider, CharacterDao characterDao, TextMaker textMaker) { this.connectionStateProvider = connectionStateProvider; this.characterDao = characterDao; this.textMaker = textMaker; } @Override public ConnectionState execute(Connection connection, ApplicationConfiguration configuration) { if (connection.getInputQueue().isEmpty()) { return this; } String input = connection.getInputQueue().pop(); switch (input.toUpperCase()) { case "A": if (connection.getPlayer().isAdministrator()) { return connectionStateProvider.get(AdministrationMenu.class); } else { return handleInvalidOption(connection); } case "P": if (playerHasCharacters(connection.getPlayer().getId())) { return connectionStateProvider.get(CharacterSelectionPrompt.class); } return handleCharacterNeeded(connection); case "C": return connectionStateProvider.get(UniverseSelectionPrompt.class); default: return handleInvalidOption(connection); } } private boolean playerHasCharacters(long playerId) { return !characterDao.getCharacters(playerId).isEmpty(); } private ConnectionState handleCharacterNeeded(Connection connection) { String text = textMaker.getText(TextName.CharacterNeeded, connection.getLocale()); connection.getOutputQueue().push(text); return connectionStateProvider.get(UniverseSelectionPrompt.class); } private ConnectionState handleInvalidOption(Connection connection) { String text = textMaker.getText(TextName.InvalidOption, connection.getLocale()); connection.getOutputQueue().push(text); return connectionStateProvider.get(PlayerMenuPrompt.class); } }
true
482971388440356d53e7b265b0dc805fd56ceda5
Java
Emmagitlab/game
/game/src/game/RepeatTaskWithCooldown.java
UTF-8
1,540
3.34375
3
[]
no_license
/* * 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 game; import java.util.*; /** * * @author T440 */ public class RepeatTaskWithCooldown { public String repeatTaskWithCooldown(String task, int k){ if(task == null || task.length() == 0) return null; HashMap<Character, Integer> map = new HashMap<>(); StringBuilder sb = new StringBuilder(); int count = 0; for(int i = 0; i < task.length(); i++){ count++; if(!map.containsKey(task.charAt(i))){ map.put(task.charAt(i), count); sb.append(task.charAt(i)); }else{ int oldCount = map.get(task.charAt(i)); if(count - oldCount >k){ sb.append(task.charAt(i)); }else{ int temp = oldCount+k+1; for(int j = count; j < temp; j++){ sb.append("_"); } sb.append(task.charAt(i)); count = temp; map.put(task.charAt(i), count); } } } return sb.toString(); } public static void main(String[] args){ RepeatTaskWithCooldown sol = new RepeatTaskWithCooldown(); String s = "aabbcc"; System.out.println(sol.repeatTaskWithCooldown(s, 4)); } }
true
904f3f411f059371d4a9856a198df27dcc0f1e7c
Java
nicekuo/nice_library
/src/main/java/nice/com/nice_library/bean/VersionListBean.java
UTF-8
1,373
2.140625
2
[]
no_license
package nice.com.nice_library.bean; public class VersionListBean extends BaseBean{ private static final long serialVersionUID = 7100465559042745268L; private VersionBean data; private int version=1;//版本 相当于是version_code private String versionName=""; //版本名称 相当于是version_name private String url="";//更新地址 private String description="";//更新描述 private String update_time="";//应用上次更新时间 private int force=-1; public int getForce() { return force; } public void setForce(int force) { this.force = force; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getVersionName() { return versionName; } public void setVersionName(String versionName) { this.versionName = versionName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUpdate_time() { return update_time; } public void setUpdate_time(String update_time) { this.update_time = update_time; } public VersionBean getData() { return data; } public void setData(VersionBean data) { this.data = data; } }
true
8d586163c69b47d307a4a658a8f0adb004ce1b34
Java
lifan120/springboot-freemarker
/src/test/java/com/lf/freemarker/DemoApplicationTests.java
UTF-8
2,166
2.453125
2
[]
no_license
package com.lf.freemarker; import com.lf.freemarker.bean.TableInfo; import com.lf.freemarker.dao.TableDao; import freemarker.template.Configuration; import freemarker.template.Template; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootTest class DemoApplicationTests { private static final String TEMPLATE_PATH = "src/main/resources/templates"; private static final String CLASS_PATH = "src/main/java/com/lf/freemarker/controller"; @Autowired private TableDao dao; @Test void contextLoads() { Configuration configuration = new Configuration(); Writer out = null; try { // step2 获取模版路径 configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH)); // step3 创建数据模型 Map<String, Object> dataMap = new HashMap<String, Object>(); List<TableInfo> tableInfos = dao.selectAllTableInfo("db2019", "payment"); dataMap.put("tableInfos",tableInfos); // step4 加载模版文件 Template template = configuration.getTemplate("controller.ftl"); // step5 生成数据 File docFile = new File(CLASS_PATH + "\\" + "User.java"); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile))); // step6 输出文件 template.process(dataMap, out); System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^User.java 文件创建成功 !"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != out) { out.flush(); } } catch (Exception e2) { e2.printStackTrace(); } } } }
true
bc5e334c1410e8d07576fc8168ab23f5921d63b8
Java
cjchao0/pinyougou
/pinyougou/pinyougou_sellergoods/pinyougou_sellergoods_service/src/main/java/com/chao/sellergoods/service/impl/SellerServiceImpl.java
UTF-8
1,634
2.078125
2
[]
no_license
package com.chao.sellergoods.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.chao.mapper.SellerMapper; import com.chao.pojo.TbSeller; import com.chao.sellergoods.service.SellerService; import com.chao.service.impl.BaseServiceImpl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.entity.Example; import java.util.List; @Service public class SellerServiceImpl extends BaseServiceImpl<TbSeller> implements SellerService { @Autowired private SellerMapper sellerMapper; @Override public PageInfo<TbSeller> search(Integer pageNum, Integer pageSize, TbSeller seller) { //设置分页 PageHelper.startPage(pageNum, pageSize); //创建查询对象 Example example = new Example(TbSeller.class); //创建查询条件对象 Example.Criteria criteria = example.createCriteria(); //状态查询 if(StringUtils.isNotBlank(seller.getStatus())){ criteria.andEqualTo("status",seller.getStatus()); } //公司名称查询 if (StringUtils.isNotBlank(seller.getName())) { criteria.andLike("name", "%" + seller.getName() + "%"); } //店铺名称查询 if(StringUtils.isNotBlank(seller.getNickName())){ criteria.andLike("nickName","%" + seller.getNickName() + "%"); } List<TbSeller> list = sellerMapper.selectByExample(example); return new PageInfo<>(list); } }
true
982e0619118c640d2672b788bf19ae85769e37e9
Java
PrabhuBala678/JLProject
/Johnlewis-Selenium-Cucumber-master/src/main/java/pages/ContactusPage.java
UTF-8
978
1.882813
2
[ "MIT" ]
permissive
package pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; public class ContactusPage extends BasePage{ @FindBy(how=How.CSS, using=".selector,.hover") public static WebElement div_heading; @FindBy(how=How.ID, using="id_contact") public static Select subject_heading; @FindBy(how=How.ID, using="email") public static WebElement email; @FindBy(how=How.ID, using="id_order") public static WebElement order_reference; @FindBy(how=How.ID, using="message") public static WebElement message; @FindBy(how=How.ID, using="submitMessage") public static WebElement submit; @FindBy(how=How.CLASS_NAME, using="alert-danger") public static WebElement error_message; public ContactusPage() { PageFactory.initElements(driver, this); this.driver = driver; } }
true
2de2933d7d9c37a572655ca4371ec4fa6277158c
Java
OmarGarza1/Generation_Bootcamp
/CRUD_MVC/src/com/crud/model/Producto.java
UTF-8
829
2.21875
2
[]
no_license
package com.crud.model; public class Producto { private String idProducto; private String nombreProducto; private double precioProducto; private int existencias; public double getPrecioProducto() { return precioProducto; } public void setPrecioProducto(double precioProducto) { this.precioProducto = precioProducto; } public int getExistencias() { return existencias; } public void setExistencias(int existencias) { this.existencias = existencias; } public String getIdProducto() { return idProducto; } public void setIdProducto(String idProducto) { this.idProducto = idProducto; } public String getNombreProducto() { return nombreProducto; } public void setNombreProducto(String nombreProducto) { this.nombreProducto = nombreProducto; } }
true
b5530072854f64a4d7e34c785b8112b8ba65c1b8
Java
dam240/androidjava
/goods/src/com/cd/use/action/admin_book.java
UTF-8
5,615
1.71875
2
[]
no_license
package com.cd.use.action; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.cd.admin.model.book; import com.cd.bean.broy; import com.cd.bean.page1; import com.cd.use.model.car; import com.cd.use.service.seri; import com.opensymphony.xwork2.ActionSupport; @Component("min_book") @Scope("prototype") public class admin_book extends ActionSupport { private seri ser; private String bname; private int now; private String dan_ji; private String book_name; private String tu_B; private int pid; private int cartItemIdArray; private String hiddenTotal; private String cartItemIds; public void setCartItemIdArray(int cartItemIdArray) { this.cartItemIdArray = cartItemIdArray; } public void setHiddenTotal(String hiddenTotal) { this.hiddenTotal = hiddenTotal; } public void setCartItemIds(String cartItemIds) { this.cartItemIds = cartItemIds; } public void setPid(int pid) { this.pid = pid; } public void setBook_name(String book_name) { this.book_name = book_name; } public void setTu_B(String tu_B) { this.tu_B = tu_B; } public void setDan_ji(String dan_ji) { this.dan_ji = dan_ji; } public void setMout(String mout) { this.mout = mout; } private String mout; public seri getSer() { return ser; } public String getBname() { return bname; } public int getNow() { return now; } public String getMout() { return mout; } public int getBook_id() { return book_id; } private int book_id; public void setBook_id(int book_id) { this.book_id = book_id; } public void setNow(int now) { this.now = now; } public void setBname(String bname) { this.bname = bname; } @Resource public void setSer(seri ser) { this.ser = ser; } @Override public String execute() throws Exception { // TODO Auto-generated method stub HttpServletRequest sq =ServletActionContext.getRequest(); HttpSession s=sq.getSession(); int count=ser.book_count(bname); page1 p=new page1(); p.setNow(now); p.setSize(5); System.out.println("use"+count); page1 ha=broy.io(p, count); System.out.println("ggggg"); List<book> li=ser.use_list_use(bname,ha.getIndex(),ha.getSize()); sq.setAttribute("li", li); sq.setAttribute("page", ha); s.setAttribute("bname", bname); return super.execute(); } public String list_op(){ HttpServletRequest sq =ServletActionContext.getRequest(); HttpSession s=sq.getSession(); String name=(String) s.getAttribute("bname"); int count=ser.book_count(name); page1 p=new page1(); p.setNow(now); p.setSize(5); System.out.println("use"+count); page1 ha=broy.io(p, count); List<book> li=ser.use_list_use(name,ha.getIndex(),ha.getSize()); sq.setAttribute("li", li); sq.setAttribute("page", ha); s.setAttribute("bname", bname); return SUCCESS; } public String car_ini(){ HttpServletRequest sq=ServletActionContext.getRequest(); HttpSession sw= sq.getSession(); String name=(String) sw.getAttribute("usename"); if(name!=null&&!name.equals("")){ float dan=Float.parseFloat(dan_ji); float mo=Float.parseFloat(mout); float i=dan*mo; car c=new car(); c.setBook_id(book_id); c.setUser_id(name); c.setMout(mout); c.setDan_ji(dan_ji); c.setBook_name(book_name); c.setTu_B(tu_B); c.setXi_ji(""+i); System.out.println("|"+i+"|"); System.out.println(name+"|"+dan_ji+"|"+mout+book_name+tu_B); ser.car_save(c); return SUCCESS; } else{ return ERROR; } } public String load_my(){ HttpServletRequest sq=ServletActionContext.getRequest(); HttpSession sw= sq.getSession(); String name=(String) sw.getAttribute("usename"); if(name!=null&&!name.equals("")){ List<car> li = ser.load_my(name); String ui=""; if(li.size()>0){ ui="usename"; } sq.setAttribute("li", li); sq.setAttribute("bool", ui); return SUCCESS; } return ERROR; } public String load_ku(){ System.out.println(this.cartItemIds +"-----"+this.hiddenTotal); HttpServletRequest sq=ServletActionContext.getRequest(); HttpSession sw= sq.getSession(); String name=(String) sw.getAttribute("usename"); System.out.println(name); List<car> li = ser.load_my(name); int j=0; int l=li.size(); String [] i= new String [l]; for(car c:li){ i[j]=""+c.getId(); j++; } sq.setAttribute("li", li); sw.setAttribute("total", hiddenTotal); sw.setAttribute("ioc",i ); return SUCCESS; } public String delete_car(){ System.out.println(pid); ser.delete_car(pid); return SUCCESS; } public String delete_carLIST(){ System.out.println("---dhhhhhhhhhhhhhhhhhhhhh-"); String ji[]=bname.split(","); for(int i=0;i<ji.length;i++){ int o=Integer.parseInt(ji[i]); ser.delete_car(o); } System.out.println("---||cartItemIdArray.length|||---"+ji.length); return SUCCESS; } }
true