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
8cae3f752f2c429e05bc96c35b370b28a6ed1e06
Java
afomina/tetris
/src/ru/afomina/tetris/ui/TetrisPanel.java
UTF-8
5,525
2.9375
3
[]
no_license
package ru.afomina.tetris.ui; import ru.afomina.tetris.figure.Figure; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; /** * Created by alexandra on 14.01.15. */ public class TetrisPanel extends JPanel implements ActionListener { public static final int WINDOW_WIDTH = 300; public static final int WINDOW_HEIGHT = 400; public static final int GAME_WIDTH = 12; public static final int GAME_HEIGHT = 20; public static final int ONE_CUBE_SIZE = 10; public static final int FIELD_WIDTH = ONE_CUBE_SIZE * GAME_WIDTH; public static final int FIELD_HEIGHT = ONE_CUBE_SIZE * GAME_HEIGHT; public static final int FIELD_X = (WINDOW_WIDTH - FIELD_WIDTH) / 2; public static final int FIELD_Y = 0; private static final int SPEED = 500; private Figure figure = new Figure(); private int figureX = FIELD_X + FIELD_WIDTH / 2 - ONE_CUBE_SIZE; private int figureY = 0; private boolean[][] game = new boolean[GAME_HEIGHT + 2][GAME_WIDTH + 2]; private Timer timer; public TetrisPanel() { for (int i = 0; i < GAME_WIDTH + 2; i ++) { game[0][i] = true; game[GAME_HEIGHT + 1][i] = true; } // for (int i = 0; i < GAME_HEIGHT; i++) { // game[i][0] = true; // game[i][GAME_WIDTH + 1] = true; // } setFocusable(true); requestFocusInWindow(); addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_RIGHT : if (figureX + ONE_CUBE_SIZE <= FIELD_X + FIELD_WIDTH - figure.getWidth() * ONE_CUBE_SIZE) { figureX += ONE_CUBE_SIZE; } break; case KeyEvent.VK_LEFT : if (figureX - ONE_CUBE_SIZE >= FIELD_X) { figureX -= ONE_CUBE_SIZE; } break; // case KeyEvent.VK_UP : // figure.rotate(); // break; // case KeyEvent.VK_DOWN : // figureY += ONE_CUBE_SIZE; // checkCollision(); // break; } reload(); } @Override public void keyReleased(KeyEvent e) { } }); timer = new Timer(SPEED, this); timer.start(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics2D = (Graphics2D) g; drawBorder(graphics2D); g.setColor(Color.MAGENTA); if (!timer.isRunning()) { g.drawString("GAME OVER", FIELD_X + FIELD_WIDTH / 5, FIELD_Y + FIELD_HEIGHT / 2); } else { for (int y = 1; y < GAME_HEIGHT; y++) { for (int x = 1; x < GAME_WIDTH; x++) { if (game[y][x]) { g.fillRect(FIELD_X + x * ONE_CUBE_SIZE, FIELD_Y + y * ONE_CUBE_SIZE, ONE_CUBE_SIZE, ONE_CUBE_SIZE); } } } figure.paint(figureX, figureY, graphics2D); } } private void reload() { validate(); repaint(); } private void drawBorder(Graphics g) { g.setColor(Color.LIGHT_GRAY); for (int x = FIELD_X + ONE_CUBE_SIZE; x < FIELD_X + FIELD_WIDTH; x += ONE_CUBE_SIZE) { g.drawLine(x, FIELD_Y, x, FIELD_Y + FIELD_HEIGHT); } for (int y = FIELD_Y + ONE_CUBE_SIZE; y < FIELD_Y + FIELD_HEIGHT; y += ONE_CUBE_SIZE) { g.drawLine(FIELD_X, y, FIELD_X + FIELD_WIDTH, y); } g.setColor(Color.BLACK); g.drawRect(FIELD_X, FIELD_Y, FIELD_WIDTH, FIELD_HEIGHT); } @Override public void actionPerformed(ActionEvent e) { figureY += ONE_CUBE_SIZE; if (checkCollision()) { figureY -= ONE_CUBE_SIZE; for (int y = 0; y < 2; y++) { for (int x = 0; x < 4; x++) { if (figure.getPosition()[y][x]) { game[(figureY - FIELD_Y) / ONE_CUBE_SIZE + y][(figureX - FIELD_X) / ONE_CUBE_SIZE + x] = true; } } } newFigure(); } reload(); } private void newFigure() { figure = new Figure(); figureX = FIELD_X + FIELD_WIDTH / 2 - ONE_CUBE_SIZE; figureY = 0; } private boolean checkCollision() { for (int y = 0; y < 2; y++) { for (int x = 0; x < 4; x++) { int gameY = (figureY - FIELD_Y) / ONE_CUBE_SIZE + y; if (figure.getPosition()[y][x] && game[gameY][(figureX - FIELD_X) / ONE_CUBE_SIZE + x]) { if (gameY == 1) { gameOver(); } else if (figureY > FIELD_Y + FIELD_HEIGHT - ONE_CUBE_SIZE) { figureY = FIELD_Y + FIELD_HEIGHT - ONE_CUBE_SIZE; } return true; } } } return false; } private void gameOver() { timer.stop(); } }
true
129791a5bcc6357423c38e533ba4eacc97884cd6
Java
teropa/globetrotter
/src/main/java/teropa/globetrotter/client/marker/MarkerLayer.java
UTF-8
7,014
2.21875
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package teropa.globetrotter.client.marker; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import teropa.globetrotter.client.Layer; import teropa.globetrotter.client.Map; import teropa.globetrotter.client.View; import teropa.globetrotter.client.common.LonLat; import teropa.globetrotter.client.common.Point; import teropa.globetrotter.client.common.Rectangle; import teropa.globetrotter.client.common.Size; import teropa.globetrotter.client.event.internal.ViewClickEvent; import teropa.globetrotter.client.grid.Tile; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.widgetideas.graphics.client.ImageLoader; import com.google.gwt.widgetideas.graphics.client.ImageLoader.CallBack; public class MarkerLayer extends Layer implements ViewClickEvent.Handler { private static class MarkerData { public final Marker marker; public final ImageElement image; public final LonLat projectedLoc; public MarkerData(Marker marker, ImageElement image, LonLat projectedPos) { this.marker = marker; this.image = image; this.projectedLoc = projectedPos; } } private final List<MarkerData> markers = new ArrayList<MarkerData>(); private final HandlerManager handlers = new HandlerManager(this); private HashMap<Tile, ArrayList<MarkerData>> markersByTile = new HashMap<Tile, ArrayList<MarkerData>>(); public MarkerLayer(String name) { super(name, false); } @Override public void init(Map map) { super.init(map); map.getView().addViewClickHandler(this); } public void addMarkers(final Collection<? extends Marker> newMarkers) { HashSet<String> urls = collectImageUrls(newMarkers); ImageLoader.loadImages(urls.toArray(new String[urls.size()]), new CallBack() { public void onImagesLoaded(ImageElement[] imageElements) { for (int i=0 ;i<imageElements.length ; i++) { drawMatchingMarkers(imageElements[i]); } } private void drawMatchingMarkers(ImageElement img) { String src = img.getSrc(); for (Marker eachMarker : newMarkers) { if (src.equals(eachMarker.getImage().getURL())) { MarkerData data = new MarkerData(eachMarker, img, projectLocation(eachMarker)); markers.add(data); updateMatchingTiles(data); } } } }); } private HashSet<String> collectImageUrls(Collection<? extends Marker> markers) { HashSet<String> urls = new HashSet<String>(); for (Marker each : markers) { urls.add(each.getImage().getURL()); } return urls; } private void updateMatchingTiles(MarkerData data) { for (java.util.Map.Entry<Tile, ArrayList<MarkerData>> entry : markersByTile.entrySet()) { if (isMarkerInTile(data, entry.getKey())) { entry.getValue().add(data); map.getView().tileUpdated(entry.getKey(), this); } } } private boolean isMarkerInTile(MarkerData data, Tile tile) { Rectangle tileRect = new Rectangle(tile.getLeftX(), tile.getTopY(), map.getTileSize().getWidth(), map.getTileSize().getHeight()); ImageResource imgResource = data.marker.getImage(); int imgWidth = imgResource.getWidth(); int imgHeight = imgResource.getHeight(); Point pt = getMarkerPoint(data, tile); Rectangle markerRect = new Rectangle(pt.getX(), pt.getY(), imgWidth, imgHeight); if (map.calc().intersect(tileRect, markerRect)) { return true; } return false; } public void removeMarker(Marker marker) { MarkerData data = null; for (MarkerData each : markers) { if (each.marker.equals(marker)) { data = each; markers.remove(each); break; } } if (data != null) { for (java.util.Map.Entry<Tile, ArrayList<MarkerData>> entry : markersByTile.entrySet()) { if (entry.getValue().remove(data)) { map.getView().tileUpdated(entry.getKey(), this); } } } } public HandlerRegistration addMarkerClickHandler(MarkerClickEvent.Handler handler) { return handlers.addHandler(MarkerClickEvent.TYPE, handler); } public HandlerRegistration addMarkerDoubleClickHandler(MarkerDoubleClickEvent.Handler handler) { return handlers.addHandler(MarkerDoubleClickEvent.TYPE, handler); } @Override public void drawOn(View canvasView) { for (java.util.Map.Entry<Tile, ArrayList<MarkerData>> entry : markersByTile.entrySet()) { Tile tile = entry.getKey(); for (MarkerData aech : entry.getValue()) { drawMarker(aech, tile); } } } private void drawMarker(MarkerData data, Tile inTile) { ImageResource imgResource = data.marker.getImage(); int imgWidth = imgResource.getWidth(); int imgHeight = imgResource.getHeight(); Point pt = getMarkerPoint(data, inTile); map.getView().getCanvas().drawImage( data.image, imgResource.getLeft(), imgResource.getTop(), imgWidth, imgHeight, pt.getX(), pt.getY(), imgWidth, imgHeight); } private LonLat projectLocation(Marker marker) { LonLat normalizedLoc = getProjection().from(marker.getLoc()); LonLat projectedLoc = map.getProjection().to(normalizedLoc); return projectedLoc; } public void onViewClicked(ViewClickEvent event) { Point p = event.point; for (java.util.Map.Entry<Tile, ArrayList<MarkerData>> entry : markersByTile.entrySet()) { Tile tile = entry.getKey(); for (MarkerData data : entry.getValue()) { Point pt = getMarkerPoint(data, tile); if (p.getX() >= pt.getX() && p.getX() <= pt.getX() + data.marker.getSize().getWidth() && p.getY() >= pt.getY() && p.getY() <= pt.getY() + data.marker.getSize().getHeight()) { handlers.fireEvent(new MarkerClickEvent(data.marker, this)); break; } } } } private Point getMarkerPoint(MarkerData data, Tile inTile) { Point point = map.calc().getPoint(data.projectedLoc); Size fullMapSize = map.calc().getVirtualPixelSize(); int actualX = (inTile.getLeftX() / fullMapSize.getWidth()) * fullMapSize.getWidth() + point.getX(); point = new Point(actualX, point.getY()); return data.marker.getPinPosition().translateAroundPoint(point, data.marker.getSize()); } @Override public void onTilesActivated(Collection<Tile> newTiles) { for (Tile each : newTiles) { ArrayList<MarkerData> markersForThis = new ArrayList<MarkerLayer.MarkerData>(); for (MarkerData data : markers) { if (isMarkerInTile(data, each)) { markersForThis.add(data); } } markersByTile.put(each, markersForThis); } } @Override public void onTilesDeactivated(Collection<Tile> removedTiles) { markersByTile.keySet().removeAll(removedTiles); } @Override public void onAllTilesDeactivated() { markersByTile.clear(); } @Override public void updateTile(Tile tile) { ArrayList<MarkerData> markersForTile = markersByTile.get(tile); if (markersForTile != null) { for (MarkerData data : markersForTile) { drawMarker(data, tile); } } } }
true
caea5042986c4d108792b746532dc2a2c8077bab
Java
herohyohwan/spring-web-tiles
/src/main/java/com/example/demo/config/WebApplicationConfig.java
UTF-8
5,282
1.570313
2
[]
no_license
package com.example.demo.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import com.google.common.collect.Lists; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.http.MediaType; import org.springframework.http.converter.*; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.UriComponentsBuilderMethodArgumentResolver; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import org.springframework.web.servlet.view.tiles3.TilesConfigurer; import org.springframework.web.servlet.view.tiles3.TilesView; import org.springframework.web.servlet.view.tiles3.TilesViewResolver; import javax.inject.Inject; import java.nio.charset.Charset; import java.text.DateFormat; import java.util.List; import java.util.TimeZone; /** * WebApplicationConfig * * @author herohyohwan@gmail.com * @date 2017.01.09 */ @EnableWebMvc @ComponentScan(basePackages = "com.example.demo", includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)) public class WebApplicationConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); registry.addResourceHandler("_hcheck.jsp").addResourceLocations("/"); registry.addResourceHandler("/favicon.ico").addResourceLocations("/"); registry.addResourceHandler("/static/**").addResourceLocations("/static/"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public InternalResourceViewResolver internalResourceViewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setOrder(2); return viewResolver; } @Bean public TilesViewResolver tilesViewResolver() { TilesViewResolver tilesViewResolver = new TilesViewResolver(); tilesViewResolver.setViewClass(TilesView.class); tilesViewResolver.setOrder(1); return tilesViewResolver; } @Bean public TilesConfigurer getTilesConfigurer() { TilesConfigurer tilesConfigurer = new TilesConfigurer(); tilesConfigurer.setDefinitions(new String[] {"/WEB-INF/tiles/tiles.xml"}); tilesConfigurer.setCheckRefresh(true); return tilesConfigurer; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new ByteArrayHttpMessageConverter()); converters.add(new FormHttpMessageConverter()); converters.add(new ResourceHttpMessageConverter()); converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); converters.add(new MappingJackson2HttpMessageConverter()); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.TEXT_HTML); configurer.mediaType("html", MediaType.TEXT_HTML); configurer.mediaType("js", MediaType.TEXT_HTML); configurer.mediaType("json", MediaType.APPLICATION_JSON); } @Bean @Inject public ContentNegotiatingViewResolver contentNegotiatingViewResolver(ContentNegotiationManager contentNegotiationManager) { ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver(); viewResolver.setContentNegotiationManager(contentNegotiationManager); viewResolver.setDefaultViews(Lists.newArrayList( jsonView() )); viewResolver.setOrder(3); return viewResolver; } private View jsonView() { MappingJackson2JsonView jsonView = new MappingJackson2JsonView(); jsonView.setContentType("application/json"); return jsonView; } }
true
50b6893c70ba74fb3400b04ee3328c5cce7f3330
Java
samarthgupta29/CureFitFeedClone
/java/com/example/curefitfeed/View/MindFragment.java
UTF-8
2,646
2.140625
2
[]
no_license
package com.example.curefitfeed.View; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.curefitfeed.Adapter.EatAdapter; import com.example.curefitfeed.R; import com.example.curefitfeed.Repository.InputStreamHelper; import com.example.curefitfeed.ViewModel.UnsplashImageViewModel; import java.io.IOException; import java.io.InputStream; public class MindFragment extends Fragment { private UnsplashImageViewModel unsplashImageViewModel; private RecyclerView mindRv; private EatAdapter eatAdapter; private RecyclerView.LayoutManager layoutManager; @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); unsplashImageViewModel = ViewModelProviders.of(getActivity()).get(UnsplashImageViewModel.class); unsplashImageViewModel.init(new InputStreamHelper() { @Override public InputStream getInputStream(String file) { try { if(getActivity()!=null){ return getActivity().getAssets().open(file); } else { return null; } } catch (IOException e) { e.printStackTrace(); return null; } } }); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.mind_fragment,null); mindRv = view.findViewById(R.id.mindRv); mindRv.setHasFixedSize(true); layoutManager = new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,false); mindRv.setLayoutManager(layoutManager); eatAdapter = new EatAdapter(getActivity(),unsplashImageViewModel.getMindFeed()); mindRv.setAdapter(eatAdapter); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //System.out.println(unsplashImageViewModel.getMindFeed()); } }
true
65c3a22b4d07322f7a20602003c0e0765be32f02
Java
isTheEarlyBird/springboot_mao
/src/main/java/com/my/mao/controller/user/UserController.java
UTF-8
2,749
2.265625
2
[]
no_license
package com.my.mao.controller.user; import com.my.mao.domain.User; import com.my.mao.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.text.SimpleDateFormat; import java.util.Date; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * 用户登录 * @param name 用户名 * @param password 用户密码 * @param request * @return */ @PostMapping("/login.do") public ModelAndView login(String name, String password, HttpServletRequest request) throws Exception { ModelAndView mv = null; User user = userService.checkExistsUser(name, password); if (null == user){ mv = new ModelAndView(); mv.addObject("error", "用户或密码错误"); mv.setViewName("/user/login"); }else { request.getSession().setAttribute("user", user); mv = new ModelAndView("redirect:/index/init.do"); } return mv; } /** * 用户登出 * @param request * @return */ @RequestMapping("/logout.do") public String logout(HttpServletRequest request){ HttpSession session = request.getSession(); session.removeAttribute("user"); //移除购物车 session.removeAttribute("cart"); return "redirect:/index/init.do"; } /** * 根据用户名查询 用户名是否已存在 * @param name * @param response * @throws Exception */ @RequestMapping("/checkedUserExists.do") @ResponseBody public String checkedUserExists(@RequestBody String name, HttpServletResponse response) throws Exception { Long num = userService.checkedUserExists(name.split("=")[1]); if (num > 0) { return "false"; } else { return "true"; } } /** * 用户注册 * @param user * @return */ @PostMapping("/register.do") public String register(User user) throws Exception { user.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())); userService.addUser(user); return "redirect:/user/toLogin"; } }
true
a5f47a29ff8dedfa6936f3b639bd4dfb29f536bc
Java
ZhanGb1nG/S_2_Spring-boot-helloworld
/src/main/java/com/example/demo/rabbit/simple/SimpleReceiver.java
UTF-8
515
2.234375
2
[]
no_license
package com.example.demo.rabbit.simple; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; /** * 简单模式消费者 * * @Author ZhanG_b1nG * @Date 2021/9/3 11:05 * @Version 1.0 **/ @Slf4j public class SimpleReceiver { @RabbitHandler @RabbitListener(queues = SimpleSender.SIMPLE_QUEUQ_HELLO) public void receive(String in) { log.info(" [x] Received '{}'", in);; } }
true
e4cf6e3347ae9e940886c01759bd70f205b29a1d
Java
Jason-Addison/ShootEmUp
/src/entities/RocketManager.java
UTF-8
2,526
2.546875
3
[]
no_license
package entities; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.util.ArrayList; import engine.Camera; import engine.Key; import engine.Upgrades; import gfx.Sources; public class RocketManager { int hydraTick = 0; int hydraTickMax = 10; private Upgrades up = new Upgrades(); private Camera cam = new Camera(); public static ArrayList<Hydra> hydra = new ArrayList<Hydra>(); public static ArrayList<RocketSmoke> hydraSmoke = new ArrayList<RocketSmoke>(); int rsDespawn = 30; int hydraDespawn = 1500; public void tick() { if(Key.hydra) { hydraTick++; if(hydraTick >= hydraTickMax) { hydraTick = 0; shootHydra(); } //addSmoke(); } } public void render(Graphics g) { for(int i = 0; i < hydra.size(); i++) { hydra.get(i).pos.x -= Helicopter.hVelo; hydra.get(i).pos.x += hydra.get(i).velocity; hydraSmoke.add(new RocketSmoke(new Rectangle(hydra.get(i).pos.x, hydra.get(i).pos.y + 5, 2, 2), 1f, 1f, 0.5f, 0f, 0)); hydraSmoke.add(new RocketSmoke(new Rectangle(hydra.get(i).pos.x - 5, hydra.get(i).pos.y + 5, 2, 2), 1f, 1f, 0.5f, 0.2f, 0)); hydraSmoke.add(new RocketSmoke(new Rectangle(hydra.get(i).pos.x - 10, hydra.get(i).pos.y + 5, 2, 2), 1f, 1f, 0.5f, 0.2f, 0)); g.drawImage(Sources.hydraRocketR, hydra.get(i).pos.x, hydra.get(i).pos.y, hydra.get(i).pos.width, hydra.get(i).pos.height, null); if(hydra.get(i).pos.x > Helicopter.hX - cam.getCamera() + hydraDespawn) { hydra.remove(i); } } for(int x = 0; x < hydraSmoke.size(); x++) { g.setColor(new Color(hydraSmoke.get(x).r, hydraSmoke.get(x).g, hydraSmoke.get(x).b, hydraSmoke.get(x).trans)); g.fillRect(hydraSmoke.get(x).pos.x, hydraSmoke.get(x).pos.y, hydraSmoke.get(x).pos.width, hydraSmoke.get(x).pos.height); hydraSmoke.get(x).tick++; if(hydraSmoke.get(x).tick >= rsDespawn) { hydraSmoke.remove(x); } if(hydraSmoke.get(x).trans > 0.3) { hydraSmoke.get(x).trans -= 0.3; } if(hydraSmoke.get(x).r >= 0.3) { hydraSmoke.get(x).trans -= 0.3; } if(hydraSmoke.get(x).trans <= 0.3) { hydraSmoke.remove(x); } } } public void shootHydra() { Upgrades.currentHydra--; hydra.add(new Hydra(up.getHydraVel(), up.getHydraDmg(), new Rectangle((int) Helicopter.hX - (int) cam.getCamera() + 30, (int) Helicopter.hY + 65, 20, 10))); } public void addSmoke() { } }
true
c98d24d62642f34737d72b6ba22cc70ffe109c94
Java
wengxingxia/001java8
/src/com/xander/java8/_05optional/OptionalTest.java
UTF-8
4,635
3.5625
4
[]
no_license
package com.xander.java8._05optional; import com.xander.java8._03methodRef.Person; import org.junit.Test; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; /** * Description: * * @author Xander * datetime: 2020/9/7 9:02 */ public class OptionalTest { @Test public void test() { Person p = new Person("张三", 18); // 通过给定的value,返回一个值为给定value的Optional实例,若value为null,则抛出NullPointerException // Optional<Object> o = Optional.of(null); Optional<Person> opPerson = Optional.of(p); System.out.println("of(T value): " + opPerson); // 通过给定的value,返回一个值为给定value的Optional实例,value可为null,若value为null,则返回 Optional.EMPTY Optional<Person> opNull = Optional.ofNullable(null); System.out.println("ofNullable(T value): " + opNull); // 如果此 Optional 存在值,则返回值,否则抛出NoSuchElementException // Person person = opNull.get();// 抛出NoSuchElementException Person person = opPerson.get(); System.out.println("T get(): " + person); // 如果存在值 value!=null,返回true,否则返回false boolean opNullPresent = opNull.isPresent(); System.out.println("opNull persent: " + opNullPresent); if (!opNull.isPresent()) { System.out.println("opNull 的 value == null"); } else { System.out.println("opNull 的 value = " + opNull.get()); } boolean opPersonPresent = opPerson.isPresent(); System.out.println("opPerson persent: " + opPersonPresent); // 如果 opPerson 的 value != null,输出下面语句 opPerson.ifPresent(value -> System.out.println(value.getName() + "的年龄是" + value.getAge())); // 如果 Optional 的值存在而且匹配给定的 predicate(断定型函数式接口),返回当前Optional,否则返回一个空Optional(值为null) System.out.println("opNull.filter(): " + opNull.filter(value -> value.getAge() == 18)); System.out.println("opPerson.filter() 匹配age==18: " + opPerson.filter(value -> value.getAge() == 18)); System.out.println("opPerson.filter() 匹配age==19: " + opPerson.filter(value -> value.getAge() == 19)); // 如果值存在,对该值应用给定的映射方法,如果是非null的结果,返回一个描述该值的 optional,否则返回一个空Optional(值为null) // Person::getName 方法引用等同于 lambda表达式:value->value.getName() // Function<Person, String> funcGetName = value->value.getName(); Function<Person, String> funcGetName = Person::getName; Optional<String> opNameofOpNull = opNull.map(funcGetName); Optional<String> opNameofOpPerson = opPerson.map(funcGetName); System.out.println("opNull.map(): " + opNameofOpNull); System.out.println("opPerson.map(): " + opNameofOpPerson); // 如果 Optional 的值存在,应用提供的映射方法并返回结果 Optional,否则返回一个空的Optional Optional<Person> op1 = opNull.flatMap(value -> Optional.of(new Person("李四", 20))); Optional<Person> op2 = opPerson.flatMap(value -> Optional.of(new Person("李四", 20))); System.out.println("opNull.flatMap(): " + op1); System.out.println("opPerson.flatMap(): " + op2); // 如果此Optional的value不为null,则返回value,否则返回给定的other对象 Person wangwu = new Person("王五", 25); System.out.println("opNull.orElse(): " + opNull.orElse(wangwu)); System.out.println("opPerson.orElse(): " + opPerson.orElse(wangwu)); // 如果此Optional的value不为null,则返回value,否则通过调用给定的Supplier(供给型函数式接口)返回一个T类型的对象 Supplier<Person> supplier = () -> new Person("赵六", 26); System.out.println("opNull.orElseGet(): " + opNull.orElseGet(supplier)); System.out.println("opPerson.orElseGet(): " + opPerson.orElseGet(supplier)); // 如果此Optional的value不为null,则返回value,否则通过调用给定的Supplier创建一个Throwable Supplier<NullPointerException> nullPointerExceptionSupplier = () -> new NullPointerException("value is null"); System.out.println("opPerson.orElseThrow(): " + opPerson.orElseThrow(nullPointerExceptionSupplier)); System.out.println("opNull.orElseThrow(): " + opNull.orElseThrow(nullPointerExceptionSupplier)); } }
true
7e6637fac03f352864eaf58a6ea720afc5ab66cb
Java
marcusletric/tetris
/src/main/java/model/HighscoresModel.java
UTF-8
1,259
3.25
3
[]
no_license
package model; import java.io.IOException; import java.sql.SQLException; import java.util.List; import controller.DatabaseController; /** * Model to store list of high scores. */ public class HighscoresModel { /** * Database controller instance. */ private DatabaseController dbCtrl; /** * List of scores. */ private List<ScoreItem> scoreList; /** * Constructor. * * Gets fresh high score list from database. */ public HighscoresModel() { updateScores(); } /** * Request a fresh list of high scores from database. */ public void updateScores(){ try { dbCtrl = new DatabaseController(); scoreList = dbCtrl.getScores(); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Getter for high scores list. * * @return List of {@link ScoreItem} */ public List<ScoreItem> getScores(){ return scoreList; } /** * Checks if a score is high score. * * @param score point amount to check * @return <code>ture</code> if score is a high score, <code>false</code> else. */ public boolean isHighscore(long score){ if(scoreList.size() < 20 || scoreList.get(19).getScore() < score){ return true; } return false; } }
true
b94609de5a25ff572248f1ea1e57e367553a134e
Java
a1573595/RealTimeCamera
/app/src/main/java/com/a1573595/realtimecamera/LogoClassificationActivity.java
UTF-8
13,990
1.71875
2
[]
no_license
package com.a1573595.realtimecamera; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.hardware.Camera; import android.os.Bundle; import android.os.SystemClock; import android.util.DisplayMetrics; import android.util.Size; import android.view.View; import android.widget.TextView; import androidx.annotation.Nullable; import com.a1573595.realtimecamera.customView.OverlayView; import com.a1573595.realtimecamera.tflite.ImageUtils; import com.a1573595.realtimecamera.tflite.MultipleClassificationModel; import com.a1573595.realtimecamera.tflite.MultipleClassifier; import com.a1573595.realtimecamera.tool.Logger; import com.asus.robotframework.API.RobotAPI; import com.asus.robotframework.API.RobotCallback; import com.asus.robotframework.API.RobotCmdState; import com.asus.robotframework.API.RobotCommand; import com.asus.robotframework.API.RobotErrorCode; import com.asus.robotframework.API.RobotFace; import com.asus.robotframework.API.WheelLights; import java.io.IOException; import java.util.Arrays; public class LogoClassificationActivity extends CameraActivity { private Logger logger = new Logger(this.getClass()); private static final Size DESIRED_PREVIEW_SIZE = new Size(640, 480); private static final boolean MAINTAIN_ASPECT = false; private static final String MODEL_FILE = "logoclassify2.tflite"; private static final int MODEL_INPUT_SIZE = 224; private static final int NUM_ITEMS = 7; private boolean HAS_FRONT_CAMERA = false; private MultipleClassifier detector; private long timestamp = 0; private boolean computingImage = false; private Bitmap rgbFrameBitmap = null; private Bitmap croppedBitmap = null; private Matrix frameToCropTransform; private int scale_width = 0; private OverlayView trackingOverlay; private Paint paint; private TextView tv_debug; private String[] logos = new String[]{"Carleton", "McMaster", "Trent", "Uoit", "UoT", "Waterloo", "Background"}; private RobotAPI robotAPI; private RobotCallback robotCallback; private int serialStatus = -1; private int[] frameArray = new int[3]; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); tv_debug = findViewById(R.id.tv_debug); initZenbo(); } private void initZenbo() { initRobotCallback(); robotAPI = new RobotAPI(getApplicationContext(), robotCallback); } private void initRobotCallback() { robotCallback = new RobotCallback() { @Override public void onResult(int cmd, int serial, RobotErrorCode err_code, Bundle result) { super.onResult(cmd, serial, err_code, result); } @Override public void onStateChange(int cmd, int serial, RobotErrorCode err_code, RobotCmdState state) { super.onStateChange(cmd, serial, err_code, state); logger.i(RobotCommand.getRobotCommand(cmd).name() + ", serial:" + serial + ", state:" + state.ordinal()); switch (RobotCommand.getRobotCommand(cmd).name()) { case "SPEAK": if (state.ordinal() == 3) ; // Start break; case "PLAY_EMOTIONAL_ACTION": break; case "SET_EXPRESSION": if (state.ordinal() == 5 && serial == serialStatus) { //End robotAPI.robot.setExpression(RobotFace.HIDEFACE); Arrays.fill(frameArray, -1); serialStatus = -1; } break; } } @Override public void initComplete() { super.initComplete(); } }; } @Override public void onResume() { super.onResume(); View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN ); computingImage = false; } @Override public void onDestroy() { super.onDestroy(); if (robotAPI != null) robotAPI.release(); } @Override protected Size getDesiredPreviewFrameSize() { return DESIRED_PREVIEW_SIZE; } @Override protected void onPreviewSizeChosen(Size size, int rotation) { HAS_FRONT_CAMERA = hasFrontCamera(); // Initialize TensorFlow Lite module try { detector = MultipleClassificationModel.create( getAssets(), MODEL_FILE, MODEL_INPUT_SIZE, false, NUM_ITEMS ); } catch (final IOException e) { logger.e("Module could not be initialized"); finish(); } previewWidth = size.getWidth(); previewHeight = size.getHeight(); logger.i(getString(R.string.initializing_size, previewWidth, previewHeight)); int sensorOrientation = rotation - getScreenOrientation(); logger.i(getString(R.string.camera_orientation_relative, sensorOrientation)); trackingOverlay = findViewById(R.id.tracking_overlay); int h = trackingOverlay.getMeasuredHeight(); int w = trackingOverlay.getMeasuredWidth(); int preview_scale = h > w ? w / DESIRED_PREVIEW_SIZE.getWidth() : h / DESIRED_PREVIEW_SIZE.getHeight(); //預覽畫面放大比例 int crop_scale = DESIRED_PREVIEW_SIZE.getWidth() / MODEL_INPUT_SIZE; //預覽畫面與擷取影像比例 float scale = preview_scale * crop_scale / 2; RectF rectF = new RectF( (w / 2) - (MODEL_INPUT_SIZE * scale), (h / 2) - (MODEL_INPUT_SIZE * scale), (w / 2) + (MODEL_INPUT_SIZE * scale), (h / 2) + (MODEL_INPUT_SIZE * scale) ); scale_width = (int) (rectF.width() / scale); paint = new Paint(); paint.setAntiAlias(true);//消除鋸齒 paint.setStrokeWidth(25);//設置畫筆的寬度 paint.setStyle(Paint.Style.STROKE);//設置繪製輪廓 paint.setColor(Color.RED);//設置顏色 trackingOverlay.addCallback( canvas -> canvas.drawRect(rectF, paint)); rgbFrameBitmap = Bitmap.createBitmap(previewWidth, previewHeight, Bitmap.Config.ARGB_8888); croppedBitmap = Bitmap.createBitmap(MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, Bitmap.Config.ARGB_8888); frameToCropTransform = ImageUtils.getTransformationMatrix( scale_width, scale_width, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE, sensorOrientation, MAINTAIN_ASPECT ); } private boolean hasFrontCamera() { Camera.CameraInfo ci = new Camera.CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); i++) { Camera.getCameraInfo(i, ci); if (ci.facing == Camera.CameraInfo.CAMERA_FACING_BACK) return true; } return false; } @Override protected void processImage() { ++timestamp; final long currTimestamp = timestamp; // No mutex needed as this method is not reentrant. if (computingImage) { readyForNextImage(); return; } computingImage = true; logger.i("Preparing image " + currTimestamp + " for module in bg thread."); rgbFrameBitmap.setPixels(getRgbBytes(), 0, previewWidth, 0, 0, previewWidth, previewHeight); readyForNextImage(); final Canvas canvas = new Canvas(croppedBitmap); canvas.drawBitmap(cropBitmap(rgbFrameBitmap, scale_width), frameToCropTransform, null); runInBackground( () -> { final long startTime = SystemClock.uptimeMillis(); // Module output final float[] results = detector.recognizeImage( HAS_FRONT_CAMERA ? croppedBitmap : flip(croppedBitmap)); long lastProcessingTimeMs = SystemClock.uptimeMillis() - startTime; logger.i("Running detection on image " + lastProcessingTimeMs); final int index_logo = findMaxIndex(results); if (index_logo == NUM_ITEMS - 1) { paint.setColor(Color.RED); robotAPI.wheelLights.setColor(WheelLights.Lights.SYNC_BOTH, 0xff, 0xFF0000); } else { paint.setColor(Color.GREEN); robotAPI.wheelLights.setColor(WheelLights.Lights.SYNC_BOTH, 0xff, 0x00FF00); } trackingOverlay.postInvalidate(); computingImage = false; runOnUiThread( () -> { tv_debug.setText(String.format("%d ms\n%s: %f\n%s: %f\n" + "%s: %f\n%s: %f\n%s: %f\n%s: %f\n%s: %f\n\n%s", lastProcessingTimeMs, logos[0], results[0], logos[1], results[1] , logos[2], results[2], logos[3], results[3], logos[4], results[4], logos[5], results[5], logos[6], results[6], logos[index_logo])); if (serialStatus != -1) return; for (int i = frameArray.length - 1; i >= 0; i--) { frameArray[i] = ((i > 0) ? frameArray[i - 1] : index_logo); } if (index_logo != NUM_ITEMS - 1 && isSame(frameArray)) { zenboTalking(index_logo); } }); }); } private Bitmap toGrayscale(Bitmap bmpOriginal) { int width, height; height = bmpOriginal.getHeight(); width = bmpOriginal.getWidth(); Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bmpGrayscale); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bmpOriginal, 0, 0, paint); return bmpGrayscale; } //從中間截取一個正方形 public Bitmap cropBitmap(Bitmap bitmap, int cropWidth) { int w = bitmap.getWidth(); // 得到圖片的寬,高 int h = bitmap.getHeight(); return Bitmap.createBitmap(bitmap, (w - cropWidth) / 2, (h - cropWidth) / 2, cropWidth, cropWidth); } private Bitmap flip(Bitmap d) { Matrix m = new Matrix(); m.preScale(-1, 1); Bitmap dst = Bitmap.createBitmap(d, 0, 0, d.getWidth(), d.getHeight(), m, false); dst.setDensity(DisplayMetrics.DENSITY_DEFAULT); return dst; } private int findMaxIndex(float[] array) { int index = 0; float max = 0; for (int i = 0; i < array.length; i++) { if (array[i] > max) { max = array[i]; index = i; } } return index; } private boolean isSame(int[] array) { boolean isSame = true; for (int i = 0; i < array.length - 1; i++) { if (array[i] != array[i + 1]) { isSame = false; break; } } return isSame; } private void zenboTalking(int index) { String sentence; // ACTIVE、CONFIDENT、EXPECTING、HAPPY、INTERESTED、PLEASED、PROUD、SINGING RobotFace face = RobotFace.HAPPY; switch (index) { case 0: sentence = "Carleton University, it is a public comprehensive university in Ottawa. We are good friends."; break; case 1: sentence = "McMaster University, it is seen as a science-oriented university, and is known for it's medical school. I have a lot of friends on campus over there."; break; case 2: sentence = "Trent University, it is a public university in Peterborough. We are partners for a long time."; break; case 3: sentence = "Ontario Tech University, I work on there, it is a great place. You should study there. I look forward to seeing you there at Ontario Tech University on campus."; face = RobotFace.SHY; break; case 4: sentence = "University of Toronto, We Ontario Tech University has a lot of faculty members graduated from there."; face = RobotFace.EXPECTING; break; default: sentence = "University of Waterloo, it is most famous for its co-operative education programs. We are good research partners."; face = RobotFace.WORRIED; break; } serialStatus = robotAPI.robot.setExpression(face, sentence); } }
true
724e374aa3e04c283ad681e8df5069f0d2a3df6c
Java
marifatulikhsan/TugasPraktikum4
/Nomer3.java
UTF-8
853
3.046875
3
[]
no_license
package TugasModul4; public class Nomer3 { public static void main(String[] args){ int[] data = {25,7,9,13,3}; for (int i=0; i<data.length; i++){ System.out.print(data[i]+" "); } for (int i=0; i<data.length-1; i++){ int indeksKecil = i; for (int j=i+1; j<data.length; j++){ if (data[j]<data[indeksKecil]){ indeksKecil = j; } } int temp = data[i]; data[i] = data[indeksKecil]; data[indeksKecil] = temp; } System.out.println("\n"); System.out.println("*** Selection Sort ***"); for (int i=0; i<data.length; i++){ System.out.print(data[i]+" "); } System.out.println("\n"); System.out.println("Marifatul Ikhsan"); } }
true
1fca9d372e5d20d814b445f585040baab72eb107
Java
cspASiTa/diy
/src/main/java/com/hycxkj/production/font/FontSimpleProduction.java
UTF-8
554
1.695313
2
[]
no_license
package com.hycxkj.production.font; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author 陈少平 * @description * @create in 2018/3/29 16:30 */ @Data @NoArgsConstructor public class FontSimpleProduction implements Serializable{ private long proId; private int userId; private String userNick; private String avatar; private String title; private int categoryId; private String image; private int likeCount; private byte allowComments; private int readnumber; }
true
eccc944ded9b82f736546a11913862e9f14fde01
Java
JoannaLilja/NetPro-homework2-2
/src/server/model/Game.java
UTF-8
3,157
2.8125
3
[]
no_license
package server.model; import java.io.IOException; import java.util.LinkedList; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import server.controller.Controller; import server.integration.FileHandler; import shared.GameData; /** * Stores game data and holds functionality related to the game */ public class Game { private Controller contr; private FileHandler fileHandler = new FileHandler(); private int triesLeft; private int points; private String currentWord; private StringBuilder displayWord = new StringBuilder(); private char winLoss = '-'; private LinkedList<String> guessHistory = new LinkedList<String>(); private String errorMessage; public Game() throws IOException, InterruptedException, ExecutionException { pickNewWord(); } public void setController(Controller contr) { this.contr = contr; } public GameData getGameData() { return new GameData(triesLeft, points, displayWord.toString(), winLoss, guessHistory, errorMessage); } char getWinLoss() { return winLoss; } int getTriesLeft() { return triesLeft; } int getPoints() { return points; } String getError() { return errorMessage; } String getDisplayWord() { return displayWord.toString(); } private void pickNewWord() throws IOException, InterruptedException, ExecutionException { CompletableFuture.runAsync(() -> { try { currentWord = fileHandler.getWord(); System.out.println(currentWord); triesLeft = currentWord.length(); for(int i = 0; i < currentWord.length(); i++) displayWord.append('_'); contr.respond(); } catch (IOException e) { e.printStackTrace(); } }); if (displayWord.length()>0) displayWord = new StringBuilder(); } public void receiveGuess(String guess) throws IOException, InterruptedException, ExecutionException { errorMessage = ""; if (!guess.equals(".start")) { Guess g = new Guess(guess); if (g.isValid()) { guessHistory.add(guess); if (g.isWordGuess) receiveWordGuess(guess); else receiveLetterGuess(guess.charAt(0)); } } } private void receiveWordGuess(String guess) throws IOException, InterruptedException, ExecutionException { if (guess.equalsIgnoreCase(currentWord)) { points++; winLoss = 'w'; guessHistory.clear(); pickNewWord(); } else if(triesLeft <= 0) { points--; winLoss = 'l'; guessHistory.clear(); pickNewWord(); } else { triesLeft--; contr.respond(); } } private void receiveLetterGuess(char guess) throws IOException, InterruptedException, ExecutionException { boolean correct = false; winLoss = '-'; for (int i = 0; i < currentWord.length(); i++) if (currentWord.charAt(i) == guess) { displayWord.setCharAt(i, guess); correct = true; } if(correct == false) { triesLeft--; if(triesLeft <= 0) { points--; winLoss = 'l'; guessHistory.clear(); pickNewWord(); } else { contr.respond(); } } else contr.respond(); } }
true
32bb15cbd42b56965df5f7f68434af1b2d7ca02e
Java
antonven/YourFaceSeemsAttendance
/app/src/main/java/myapps/wycoco/com/yourfaceseemsattendance/Loader.java
UTF-8
868
2.296875
2
[]
no_license
//package myapps.wycoco.com.yourfaceseemsattendance; // //import android.content.AsyncTaskLoader; //import android.content.Context; // //import java.util.ArrayList; // //import myapps.wycoco.com.yourfaceseemsattendance.Models.SubjectModel; // ///** // * Created by dell on 3/24/2017. // */ // //public class Loader extends AsyncTaskLoader<ArrayList<SubjectModel>>{ // // private String mUrl; // // public Loader(Context context, String mUrl) { // super(context); // this.mUrl = mUrl; // } // // @Override // protected void onStartLoading() { // forceLoad(); // } // // // @Override // public ArrayList<SubjectModel> loadInBackground() { // if(mUrl == null){ // return null; // } // // ArrayList<SubjectModel> articles = QueryUtils.fetchNewsData(mUrl); // return articles; // } //}
true
0df300116c64798ef766983db769c968384add7c
Java
ihsanulhaq89/Streaming
/app/src/main/java/com/sample/myapp/streaming/ServerActivity.java
UTF-8
4,603
2.0625
2
[]
no_license
package com.sample.myapp.streaming; import net.majorkernelpanic.streaming.Session; import net.majorkernelpanic.streaming.SessionBuilder; import net.majorkernelpanic.streaming.gl.SurfaceView; import net.majorkernelpanic.streaming.rtsp.RtspServer; import net.majorkernelpanic.streaming.video.VideoQuality; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.media.MediaPlayer; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.SurfaceHolder; import android.view.WindowManager; import android.widget.Toast; public class ServerActivity extends Activity implements Session.Callback, SurfaceHolder.Callback { private final static String TAG = "VirtualFrontView"; private static final String BITRATE = "bitrate"; private static final String RESOLUTION = "resolution"; private SurfaceView mSurfaceView; // For client video playback MediaPlayer mediaPlayer; SurfaceHolder surfaceHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_server); //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mSurfaceView = (SurfaceView) findViewById(R.id.surface); // Sets the port of the RTSP server to 8988 Editor editor = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()).edit(); editor.putString(RtspServer.KEY_PORT, String.valueOf(8988)); editor.commit(); // Get bitrate int bitrate = Integer.valueOf(getIntent().getStringExtra(BITRATE)); if (bitrate < 100000) bitrate = 100000; // Get resolution String resolution = getIntent().getStringExtra(RESOLUTION); int resX = 176; int resY = 144; if (resolution.equals("320x240")) { resX = 320; resY = 240; } else if (resolution.equals("352x288")) { resX = 352; resY = 288; } else if (resolution.equals("528x432")) { resX = 528; resY = 432; } else if (resolution.equals("704x576")) { resX = 704; resY = 576; } else { resX = 176; resY = 144; } Toast.makeText(this, "Resolution: " + resX + "x" + resY + ", Bitrate: " + bitrate, Toast.LENGTH_LONG).show(); // Configures the SessionBuilder SessionBuilder.getInstance().setSurfaceView(mSurfaceView) .setPreviewOrientation(0).setContext(this) .setVideoQuality(new VideoQuality(resX, resY, 20, bitrate)) .setAudioEncoder(SessionBuilder.AUDIO_NONE) .setVideoEncoder(SessionBuilder.VIDEO_H264); // Starts the RTSP server getApplicationContext().startService( new Intent(getApplicationContext(), RtspServer.class)); } @Override protected void onPause() { super.onPause(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Stop RTSP server if it is running getApplicationContext().stopService(new Intent(this, RtspServer.class)); } @Override protected void onStop() { super.onStop(); finish(); } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub } @Override public void onBitrateUpdate(long bitrate) { } @Override public void onSessionError(int reason, int streamType, Exception e) { // TODO Auto-generated method stub } @Override public void onPreviewStarted() { // TODO Auto-generated method stub } @Override public void onSessionConfigured() { // TODO Auto-generated method stub } @Override public void onSessionStarted() { // TODO Auto-generated method stub } @Override public void onSessionStopped() { // TODO Auto-generated method stub } }
true
44a5c8c69103ecc94729be9b9be8f70a12715424
Java
DimaWeissburd/jogl-Basic-Exploration-Game
/src/CameraMovement.java
UTF-8
4,022
2.875
3
[]
no_license
import static com.jogamp.opengl.math.FloatUtil.cos; import static com.jogamp.opengl.math.FloatUtil.sin; public class CameraMovement { public static void translate (float[] eye, float[] center, float[] up, float[] dv) { float[] u = {center[0] - eye[0], center[1] - eye[1], center[2] - eye[2]}; u = Utility.normalize(u); float[] v = Utility.VectorCrossVector(u, up); v = Utility.normalize(v); eye[0] += dv[0] * u[0] + dv[1] * v[0] + dv[2] * up[0]; eye[1] += dv[0] * u[1] + dv[1] * v[1] + dv[2] * up[1]; eye[2] += dv[0] * u[2] + dv[1] * v[2] + dv[2] * up[2]; center[0] += dv[0] * u[0] + dv[1] * v[0] + dv[2] * up[0]; center[1] += dv[0] * u[1] + dv[1] * v[1] + dv[2] * up[1]; center[2] += dv[0] * u[2] + dv[1] * v[2] + dv[2] * up[2]; } public static void rotate (float[] eye, float[] center, float[] up, float[] dt) { float[] u = {center[0] - eye[0], center[1] - eye[1], center[2] - eye[2]}; u = Utility.normalize(u); float[] v = Utility.VectorCrossVector(u, up); v = Utility.normalize(v); // rotate up / down if (dt[1] != 0) { float[] temp = { u[0] * (cos(dt[1]) + v[0] * v[0] * (1 - cos(dt[1]))) + u[1] * (v[0] * v[1] * (1 - cos(dt[1])) + v[2] * sin(dt[1])) + u[2] * (v[0] * v[2] * (1 - cos(dt[1])) - v[1] * sin(dt[1])), u[0] * (v[0] * v[1] * (1 - cos(dt[1])) - v[2] * sin(dt[1])) + u[1] * (cos(dt[1]) + v[1] * v[1] * (1 - cos(dt[1]))) + u[2] * (v[1] * v[2] * (1 - cos(dt[1])) + v[0] * sin(dt[1])), u[0] * (v[0] * v[2] * (1 - cos(dt[1])) + v[1] * sin(dt[1])) + u[1] * (v[1] * v[2] * (1 - cos(dt[1])) - v[0] * sin(dt[1])) + u[2] * (cos(dt[1]) + v[2] * v[2] * (1 - cos(dt[1]))) }; center[0] = temp[0] + eye[0]; center[1] = temp[1] + eye[1]; center[2] = temp[2] + eye[2]; up = Utility.VectorCrossVector(v, temp); // doesn't work when looking straight up/down up[0] = v[1] * temp[2] - v[2] * temp[1]; up[1] = v[2] * temp[0] - v[0] * temp[2]; up[2] = v[0] * temp[1] - v[1] * temp[0]; } // rotate left / right if (dt[0] != 0) { up = Utility.normalize(up); float[] temp = { u[0] * (cos(dt[0]) + up[0] * up[0] * (1 - cos(dt[0]))) + u[1] * (up[0] * up[1] * (1 - cos(dt[0])) + up[2] * sin(dt[0])) + u[2] * (up[0] * up[2] * (1 - cos(dt[0])) - up[1] * sin(dt[0])), u[0] * (up[0] * up[1] * (1 - cos(dt[0])) - up[2] * sin(dt[0])) + u[1] * (cos(dt[0]) + up[1] * up[1] * (1 - cos(dt[0]))) + u[2] * (up[1] * up[2] * (1 - cos(dt[0])) + up[0] * sin(dt[0])), u[0] * (up[0] * up[2] * (1 - cos(dt[0])) + up[1] * sin(dt[0])) + u[1] * (up[1] * up[2] * (1 - cos(dt[0])) - up[0] * sin(dt[0])) + u[2] * (cos(dt[0]) + up[2] * up[2] * (1 - cos(dt[0]))) }; center[0] = temp[0] + eye[0]; center[1] = temp[1] + eye[1]; center[2] = temp[2] + eye[2]; } // rotate clockwise / counterclockwise if (dt[2] != 0) { u = Utility.normalize(u); float[] temp = { up[0] * (cos(dt[2]) + u[0] * u[0] * (1 - cos(dt[2]))) + up[1] * (u[0] * u[1] * (1 - cos(dt[2])) + u[2] * sin(dt[2])) + up[2] * (u[0] * u[2] * (1 - cos(dt[2])) - u[1] * sin(dt[2])), up[0] * (u[0] * u[1] * (1 - cos(dt[2])) - u[2] * sin(dt[2])) + up[1] * (cos(dt[2]) + u[1] * u[1] * (1 - cos(dt[2]))) + up[2] * (u[1] * u[2] * (1 - cos(dt[2])) + u[0] * sin(dt[2])), up[0] * (u[0] * u[2] * (1 - cos(dt[2])) + u[1] * sin(dt[2])) + up[1] * (u[1] * u[2] * (1 - cos(dt[2])) - u[0] * sin(dt[2])) + up[2] * (cos(dt[2]) + u[2] * u[2] * (1 - cos(dt[2]))) }; up[0] = temp[0]; up[1] = temp[1]; up[2] = temp[2]; } } }
true
b5c50e113a2b324cff0ca56c8a022f835be2726f
Java
nguyenvietdai1998/demo_shop
/src/main/java/com/nvd/shop_demo/service/impl/AbstractServiceImpl.java
UTF-8
1,904
2.375
2
[]
no_license
package com.nvd.shop_demo.service.impl; import com.nvd.shop_demo.exception.ObjectNotFoundException; import com.nvd.shop_demo.model.response.PageResponse; import com.nvd.shop_demo.repository.BaseRepository; import com.nvd.shop_demo.service.BaseService; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; public abstract class AbstractServiceImpl<T, ID> implements BaseService<T, ID> { protected final BaseRepository baseRepository; public AbstractServiceImpl(BaseRepository baseRepository) { this.baseRepository = baseRepository; } @Override public <RQ> void save(RQ request, Function<RQ, T> transform) { T t = transform.apply(request); baseRepository.save(t); } @Override public void delete(ID id) { baseRepository.delete(id); } @Override public <RP> RP findById(ID id, Function<T, RP> transform) { Optional<T> t = baseRepository.findById(id); t.orElseThrow(() -> new ObjectNotFoundException("Not found with: " + id)); return transform.apply(t.get()); } @Override public <RP> PageResponse<RP> find(Specification<T> filter, Pageable pageable, Function<T, RP> transform) { Page<T> page = baseRepository.findAll(filter, pageable.previousOrFirst()); List<RP> data = page.stream().map(transform::apply).collect(Collectors.toList()); return PageResponse.of(page.getTotalElements(), data); } @Override public <RP> List<RP> filter(Specification<T> filter, Function<T, RP> transform) { List<T> list = baseRepository.findAll(filter); return list.stream().map(transform::apply).collect(Collectors.toList()); } }
true
96e8f0b8d95defc5e903c257b6a9f5621f32e5d3
Java
EloiAncellin/FinalProjectJava232
/app/src/main/java/eloi/ancellin/finalproject/controller/AddItem.java
UTF-8
6,265
2.171875
2
[]
no_license
package eloi.ancellin.finalproject.controller; import android.app.Activity; import android.content.Intent; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import eloi.ancellin.finalproject.R; import eloi.ancellin.finalproject.modele.Item; import eloi.ancellin.finalproject.modele.User; import eloi.ancellin.finalproject.modele.databaseAcess; public class AddItem extends AppCompatActivity { private EditText name; private EditText price; private EditText qty; private Button subButton; private User usr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_item); //get the user from the shopping Activity Bundle param = getIntent().getExtras(); usr = param.getParcelable("usr"); name = findViewById(R.id.activity_add_item_name); price = findViewById(R.id.activity_add_item_price); qty = findViewById(R.id.activity_add_item_qty); subButton = findViewById(R.id.activity_add_item_submit); subButton.setEnabled(false); name.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // have to add the security String sName = name.getText().toString(); String sPrice = price.getText().toString(); String sQty = qty.getText().toString(); boolean boolName = Security.isString(sName); boolean boolPrice = Security.isFloat(sPrice); boolean boolQty = Security.isInt(sQty); if(boolName && boolPrice && boolQty && sName.length()>2 && sPrice.length()>0 && sQty.length()>0){ subButton.setEnabled(true); }else{ subButton.setEnabled(false); } } @Override public void afterTextChanged(Editable s) { String sName = name.getText().toString(); boolean boolName = Security.isString(sName); if(databaseAcess.testUniqueItem(sName) == false){ subButton.setEnabled(false); } } }); price.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // have to add the security String sName = name.getText().toString(); String sPrice = price.getText().toString(); String sQty = qty.getText().toString(); boolean boolName = Security.isString(sName); boolean boolPrice = Security.isFloat(sPrice); boolean boolQty = Security.isInt(sQty); if(boolName && boolPrice && boolQty && sName.length()>2 && sPrice.length()>0 && sQty.length()>0){ subButton.setEnabled(true); }else{ subButton.setEnabled(false); } } @Override public void afterTextChanged(Editable s) { String sName = name.getText().toString(); boolean boolName = Security.isString(sName); if(databaseAcess.testUniqueItem(sName) == false){ subButton.setEnabled(false); } } }); qty.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // have to add the security String sName = name.getText().toString(); String sPrice = price.getText().toString(); String sQty = qty.getText().toString(); boolean boolName = Security.isString(sName); boolean boolPrice = Security.isFloat(sPrice); boolean boolQty = Security.isInt(sQty); if(boolName && boolPrice && boolQty && sName.length()>2 && sPrice.length()>0 && sQty.length()>0){ subButton.setEnabled(true); }else{ subButton.setEnabled(false); } } @Override public void afterTextChanged(Editable s) { String sName = name.getText().toString(); boolean boolName = Security.isString(sName); if(databaseAcess.testUniqueItem(sName) == false){ subButton.setEnabled(false); } } }); subButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // have to add the security String sName = name.getText().toString(); float fPrice = Float.parseFloat(price.getText().toString()); int iQty = Integer.parseInt(qty.getText().toString()); Item it = new Item(sName, iQty, 1, fPrice); // Saving the user in the database databaseAcess.addUsrItem(usr, it); // Returning the new item Intent resultShopActivityIntent = new Intent(AddItem.this, Shopping.class); String strIt = it.serialize(); System.out.println(strIt); resultShopActivityIntent.putExtra("itemStr", strIt); setResult(1, resultShopActivityIntent); finish(); } }); } }
true
e564aaae458d2b131761dd068eada944a1f8a168
Java
seungbeomi/development
/querydsl/src/main/java/kr/co/bnksys/querydsl/model/second/Code.java
UTF-8
637
2
2
[]
no_license
package kr.co.bnksys.querydsl.model.second; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Builder @Getter @NoArgsConstructor @AllArgsConstructor @Table(name = "TB_EBCC_CODE") @Entity public class Code { @Id @Column(name = "ID") private Long id; @Column(name = "CODE") private String code; @Column(name = "CODE_TEXT") private String codeText; @Column(name = "CODE_VALUE") private String codeValue; }
true
c32170883ca676f101d9249f5fba9c732468a238
Java
arthurmr96/rest-school-java
/src/java/dao/DAOProfessores.java
UTF-8
3,376
2.484375
2
[]
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 dao; import fw.Data; import java.sql.Connection; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import to.TOProfessores; import to.TOUsuario; /** * * @author 71500286 */ public class DAOProfessores { public static boolean save(Connection c, TOProfessores t) throws Exception{ StringBuilder sql = new StringBuilder(); if(t.getId() < 1){ sql.append("insert into professores (nome, telefone, sexo, idade)" + "VALUES (" + "\""+t.getNome()+"\", " + "\""+t.getTelefone()+"\", " + "\""+t.getSexo()+"\", " + "\"" + t.getIdade()+ "\")"); } else{ sql.append("update usuario " + "SET name = \""+t.getNome()+"\"," + " telefone =\"" + t.getTelefone()+ "\"," + " sexo =\"" + t.getSexo()+ "\"," + " idade =\"" + t.getIdade()+ "\"," + "WHERE id = " + t.getId()); } return Data.executeUpdate(c, sql.toString()) > 0; } public static boolean delete(Connection c, int id) throws Exception{ StringBuilder sql = new StringBuilder(); sql.append("delete from professores WHERE id = " + id); return Data.executeUpdate(c, sql.toString()) > 0; } public static TOProfessores getOne (Connection c, int id) throws Exception{ StringBuilder sql = new StringBuilder(); sql.append("select * from professores where id = " + id); try{ ResultSet res = Data.executeQuery(c, sql.toString()); while(res.next()){ TOProfessores t = new TOProfessores(); t.setId(res.getInt("id")); t.setNome(res.getString("name")); t.setTelefone(res.getString("email")); t.setSexo(res.getInt("token")); t.setIdade(res.getInt("expiracao")); return t; } } catch(Exception e){ return null; } return null; } public static List<TOProfessores> getAll (Connection c) throws Exception{ StringBuilder sql = new StringBuilder(); sql.append("select * from professores"); List<TOProfessores> l = new ArrayList<>(); try{ ResultSet res = Data.executeQuery(c, sql.toString()); while(res.next()){ TOProfessores t = new TOProfessores(); t.setId(res.getInt("id")); t.setNome(res.getString("name")); t.setTelefone(res.getString("email")); t.setSexo(res.getInt("token")); t.setIdade(res.getInt("expiracao")); l.add(t); } } catch(Exception e){ return null; } return l; } }
true
01597b2375d9910df24c6026d2e630ac5268712a
Java
allienson/TrabICS3
/src/trab3/ics/Gui.java
UTF-8
9,020
2.390625
2
[]
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 trab3.ics; import java.awt.Button; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.GroupLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.TableColumnModel; /** * * @author Usuário */ public class Gui extends Frame implements ActionListener { Controlador controlador; JFrame frame = new JFrame("Conversor MIDI-Java"); PanelPersonalizado panelConteudo = new PanelPersonalizado(); GroupLayout layout = new GroupLayout(panelConteudo); BufferedImage backgroundPanel; ImageIcon frameIcon = new ImageIcon("./img/frameicon.png"); JOptionPane popup = new JOptionPane(); JFileChooser chooser; JPanel panelTopo = new JPanel(); JPanel panelTopo2 = new JPanel(); JPanel panelMIDI = new JPanel(); JPanel panelPlay = new JPanel(); JTextField caminhoTextField = new JTextField(" Escolha um arquivo MIDI..."); JLabel labelMIDI = new JLabel("Arquivo MIDI", SwingConstants.LEFT); BotaoSimples botaoAbrir = new BotaoSimples("Abrir"); BotaoSimples botaoResetar = new BotaoSimples("Resetar Conversor"); BotaoSimples botaoFiller = new BotaoSimples(""); BotaoSimples botaoTraduzir = new BotaoSimples("Traduzir MIDI"); BotaoSimples botaoJava = new BotaoSimples("Criar Java"); BotaoSimples botaoTocar = new BotaoSimples("Tocar"); Color corFundo = new Color(0, 0, 0); Color corFundo2 = new Color(199, 199, 199); Color corFundo3 = new Color(39, 40, 34); Color corTexto = new Color(230, 232, 234); Color corTexto2 = new Color(142, 145, 151); Color corAzul = new Color(40, 102, 213); Color corAzul2 = new Color(38, 17, 244); Font font1 = new Font("Gill Sans MT Condensed", java.awt.Font.PLAIN, 30); Font font2 = new Font("Arial Narrow", java.awt.Font.ITALIC, 18); Font font3 = new Font("Monospaced", java.awt.Font.PLAIN, 15); JLabel code = new JLabel(""); public class PanelPersonalizado extends JPanel { public PanelPersonalizado() { try { backgroundPanel = ImageIO.read(new File("./img/background.jpg")); } catch(IOException e) { e.printStackTrace(); } setOpaque(true); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(backgroundPanel, 0, 0, getWidth(), getHeight(), this); } } public class BotaoSimples extends JButton{ public BotaoSimples(String label) { setText(label); setContentAreaFilled(false); setBorder(BorderFactory.createEmptyBorder()); setOpaque(true); setBackground(corAzul); setForeground(corTexto); setFocusable(false); setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void setEnabled(boolean b){ if (b){ setBackground(corAzul); setForeground(corTexto); } else { setBackground(corFundo2); } super.setEnabled(b); } } public Gui(Controlador control){ this.controlador = control; code.setFont(font3); // PANEL TOPO panelTopo.setPreferredSize(new Dimension (650, 40)); panelTopo.setOpaque(false); caminhoTextField.setEditable(false); caminhoTextField.setBackground(corFundo); caminhoTextField.setForeground(corTexto); caminhoTextField.setBorder(BorderFactory.createEmptyBorder()); caminhoTextField.setPreferredSize(new Dimension(350, 25)); botaoAbrir.setPreferredSize(new Dimension(55, 25)); botaoAbrir.setEnabled(true); botaoAbrir.addActionListener(this); botaoResetar.setPreferredSize(new Dimension(120, 25)); botaoResetar.setEnabled(false); botaoResetar.addActionListener(this); botaoFiller.setPreferredSize(new Dimension(100, 25)); botaoFiller.setOpaque(false); panelTopo.add(caminhoTextField); panelTopo.add(botaoAbrir); panelTopo.add(botaoFiller); panelTopo.add(botaoResetar); panelTopo.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 10)); chooser = new JFileChooser("midi/."); FileFilter filter = new FileNameExtensionFilter("Arquivo MIDI","mid"); chooser.addChoosableFileFilter(filter); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setFileFilter(filter); // PANEL TOPO 2 panelTopo2.setPreferredSize(new Dimension (650, 60)); panelTopo2.setOpaque(false); labelMIDI.setFont(font1); labelMIDI.setForeground(corTexto); panelTopo2.add(labelMIDI); panelTopo2.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 10)); // PANEL MIDI panelMIDI.setPreferredSize(new Dimension (650, 350)); panelMIDI.setOpaque(false); panelMIDI.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); // PANEL PLAY panelPlay.setPreferredSize(new Dimension (650, 50)); panelPlay.setOpaque(false); botaoTraduzir.setPreferredSize(new Dimension(100, 25)); botaoTraduzir.setEnabled(false); botaoTraduzir.addActionListener(this); botaoJava.setPreferredSize(new Dimension(100, 25)); botaoJava.setEnabled(false); botaoJava.addActionListener(this); botaoTocar.setPreferredSize(new Dimension(60, 25)); botaoTocar.setEnabled(false); botaoTocar.addActionListener(this); panelPlay.add(botaoTraduzir); panelPlay.add(botaoJava); panelPlay.add(botaoTocar); panelPlay.setLayout(new FlowLayout(FlowLayout.CENTER, 30, 20)); layout.setVerticalGroup(layout.createSequentialGroup() .addComponent(panelTopo) .addComponent(panelTopo2) .addComponent(panelMIDI) .addComponent(panelPlay) ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension (700, 550)); frame.setResizable(false); frame.setContentPane(panelConteudo); frame.setIconImage(frameIcon.getImage()); frame.pack(); frame.setVisible(true); } public JTable preparaTabelaMIDI(Object[][] dados){ String[] colunas = {"Tique", "Trilha", "Mensagem"}; JTable tabela = new JTable(dados, colunas); TableColumnModel tcm = tabela.getColumnModel(); tabela.setOpaque(false); tcm.getColumn(0).setPreferredWidth(10); tcm.getColumn(1).setPreferredWidth(10); tcm.getColumn(2).setPreferredWidth(400); JScrollPane panelTabela = new JScrollPane(tabela); panelTabela.setPreferredSize(new Dimension (650, 350)); tabela.setFillsViewportHeight(true); panelMIDI.add(panelTabela); return tabela; } @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == botaoTraduzir) { controlador.traduz(this); } if (source == botaoJava) { controlador.geraJava(this); } if (source == botaoAbrir) { controlador.abreMidi(this); } if (source == botaoTocar) { controlador.toca(this); } if (source == botaoResetar) { controlador.reseta(this); } } }
true
f3b0c2257032270270a53f7aa27ad6f1bc72fe99
Java
bukhmastov/CDOITMO
/app/src/main/java/com/bukhmastov/cdoitmo/model/firebase/config/FBConfigMessage.java
UTF-8
1,260
2.53125
3
[ "MIT" ]
permissive
package com.bukhmastov.cdoitmo.model.firebase.config; import com.bukhmastov.cdoitmo.model.JsonEntity; import com.bukhmastov.cdoitmo.model.JsonProperty; import java.util.Objects; public class FBConfigMessage extends JsonEntity { @JsonProperty("type") private int type; @JsonProperty("message") private String message; public FBConfigMessage() { super(); } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof FBConfigMessage)) return false; FBConfigMessage fbConfig = (FBConfigMessage) o; return type == fbConfig.type && Objects.equals(message, fbConfig.message); } @Override public int hashCode() { return Objects.hash(type, message); } @Override public String toString() { return "FBConfigMessage{" + "type=" + type + ", message='" + message + '\'' + '}'; } }
true
93a3c151c0f93e14d8a3c461f5f935f5025ae8bd
Java
Warmanfarooq/doc
/app/src/main/java/com/pdftron/pdf/dialog/signature/SavedSignaturePickerFragment.java
UTF-8
14,366
1.664063
2
[]
no_license
/* */ package com.pdftron.pdf.dialog.signature; /* */ /* */ import android.app.AlertDialog; /* */ import android.content.Context; /* */ import android.content.DialogInterface; /* */ import android.os.Bundle; /* */ import android.util.SparseBooleanArray; /* */ import android.view.KeyEvent; /* */ import android.view.LayoutInflater; /* */ import android.view.Menu; /* */ import android.view.MenuItem; /* */ import android.view.View; /* */ import android.view.ViewGroup; /* */ import android.widget.TextView; /* */ import androidx.annotation.NonNull; /* */ import androidx.annotation.Nullable; /* */ import androidx.appcompat.widget.Toolbar; /* */ import androidx.fragment.app.Fragment; /* */ import androidx.recyclerview.widget.GridLayoutManager; /* */ import androidx.recyclerview.widget.RecyclerView; /* */ import com.github.clans.fab.FloatingActionButton; /* */ import com.pdftron.pdf.adapter.SavedSignatureAdapter; /* */ import com.pdftron.pdf.interfaces.OnSavedSignatureListener; /* */ import com.pdftron.pdf.tools.R; /* */ import com.pdftron.pdf.utils.ToolbarActionMode; /* */ import com.pdftron.pdf.utils.Utils; /* */ import com.pdftron.pdf.widget.recyclerview.ItemClickHelper; /* */ import com.pdftron.pdf.widget.recyclerview.ItemSelectionHelper; /* */ import com.pdftron.pdf.widget.recyclerview.SimpleRecyclerView; /* */ import com.pdftron.pdf.widget.recyclerview.ViewHolderBindListener; /* */ import java.io.File; /* */ import java.util.ArrayList; /* */ import java.util.Collections; /* */ import java.util.HashSet; /* */ import java.util.List; /* */ import java.util.Set; /* */ /* */ /* */ /* */ public class SavedSignaturePickerFragment /* */ extends Fragment /* */ { /* */ private OnSavedSignatureListener mOnSavedSignatureListener; /* */ private SavedSignatureAdapter mSavedSignatureAdapter; /* */ private ItemSelectionHelper mItemSelectionHelper; /* */ private ToolbarActionMode mActionMode; /* */ private Toolbar mToolbar; /* */ private Toolbar mCabToolbar; /* */ /* */ public static SavedSignaturePickerFragment newInstance() { /* 51 */ return new SavedSignaturePickerFragment(); /* */ } /* */ /* */ /* */ @Nullable /* */ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { /* 57 */ return inflater.inflate(R.layout.fragment_custom_rubber_stamp_picker, container, false); /* */ } /* */ /* */ /* */ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { /* 62 */ super.onViewCreated(view, savedInstanceState); /* */ /* 64 */ FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.add_custom_stamp_fab); /* 65 */ fab.setOnClickListener(new View.OnClickListener() /* */ { /* */ public void onClick(View v) { /* 68 */ if (SavedSignaturePickerFragment.this.mOnSavedSignatureListener != null) { /* 69 */ SavedSignaturePickerFragment.this.mOnSavedSignatureListener.onCreateSignatureClicked(); /* */ } /* */ } /* */ }); /* */ /* 74 */ SimpleRecyclerView recyclerView = (SimpleRecyclerView)view.findViewById(R.id.stamp_list); /* 75 */ recyclerView.setLayoutManager((RecyclerView.LayoutManager)new GridLayoutManager(getContext(), 2)); /* */ /* 77 */ ItemClickHelper itemClickHelper = new ItemClickHelper(); /* 78 */ itemClickHelper.attachToRecyclerView((RecyclerView)recyclerView); /* 79 */ itemClickHelper.setOnItemClickListener(new ItemClickHelper.OnItemClickListener() /* */ { /* */ public void onItemClick(RecyclerView parent, View view, int position, long id) { /* 82 */ if (SavedSignaturePickerFragment.this.mActionMode == null) { /* 83 */ File file = SavedSignaturePickerFragment.this.mSavedSignatureAdapter.getItem(position); /* 84 */ if (SavedSignaturePickerFragment.this.mOnSavedSignatureListener != null && file != null) { /* 85 */ SavedSignaturePickerFragment.this.mOnSavedSignatureListener.onSignatureSelected(file.getAbsolutePath()); /* */ } /* */ } else { /* 88 */ SavedSignaturePickerFragment.this.mItemSelectionHelper.setItemChecked(position, !SavedSignaturePickerFragment.this.mItemSelectionHelper.isItemChecked(position)); /* 89 */ SavedSignaturePickerFragment.this.mActionMode.invalidate(); /* */ } /* */ } /* */ }); /* */ /* 94 */ itemClickHelper.setOnItemLongClickListener(new ItemClickHelper.OnItemLongClickListener() /* */ { /* */ public boolean onItemLongClick(RecyclerView recyclerView, View view, int position, long id) { /* 97 */ if (SavedSignaturePickerFragment.this.mActionMode == null) { /* 98 */ SavedSignaturePickerFragment.this.mItemSelectionHelper.setItemChecked(position, true); /* 99 */ SavedSignaturePickerFragment.this.mActionMode = new ToolbarActionMode(view.getContext(), SavedSignaturePickerFragment.this.mCabToolbar); /* 100 */ SavedSignaturePickerFragment.this.mActionMode.startActionMode(SavedSignaturePickerFragment.this.mActionModeCallback); /* 101 */ return true; /* */ } /* 103 */ return false; /* */ } /* */ }); /* */ /* 107 */ this.mItemSelectionHelper = new ItemSelectionHelper(); /* 108 */ this.mItemSelectionHelper.attachToRecyclerView((RecyclerView)recyclerView); /* 109 */ this.mItemSelectionHelper.setChoiceMode(2); /* */ /* 111 */ this.mSavedSignatureAdapter = new SavedSignatureAdapter(view.getContext(), (ViewHolderBindListener)this.mItemSelectionHelper); /* 112 */ this.mSavedSignatureAdapter.registerAdapterDataObserver(this.mItemSelectionHelper.getDataObserver()); /* 113 */ recyclerView.setAdapter((RecyclerView.Adapter)this.mSavedSignatureAdapter); /* */ /* 115 */ TextView emptyTextView = (TextView)view.findViewById(R.id.new_custom_stamp_guide_text_view); /* 116 */ emptyTextView.setText(R.string.signature_new_guide); /* */ /* 118 */ view.setOnKeyListener(new View.OnKeyListener() /* */ { /* */ public boolean onKey(View v, int keyCode, KeyEvent event) { /* 121 */ return (event.getAction() == 1 && keyCode == 4 && SavedSignaturePickerFragment.this /* 122 */ .onBackPressed()); /* */ } /* */ }); /* */ } /* */ /* */ /* */ public void onStop() { /* 129 */ super.onStop(); /* 130 */ this.mSavedSignatureAdapter.dispose(); /* */ } /* */ /* */ public void setOnSavedSignatureListener(OnSavedSignatureListener listener) { /* 134 */ this.mOnSavedSignatureListener = listener; /* */ } /* */ /* */ public void setToolbars(@NonNull Toolbar toolbar, @NonNull Toolbar cabToolbar) { /* 138 */ this.mToolbar = toolbar; /* 139 */ this.mCabToolbar = cabToolbar; /* */ } /* */ /* */ public void resetToolbar(final Context context) { /* 143 */ if (this.mToolbar != null) { /* 144 */ finishActionMode(); /* 145 */ this.mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() /* */ { /* */ public boolean onMenuItemClick(MenuItem item) /* */ { /* 149 */ if (SavedSignaturePickerFragment.this.mToolbar == null || SavedSignaturePickerFragment.this.mCabToolbar == null) { /* 150 */ return false; /* */ } /* */ /* 153 */ if (item.getItemId() == R.id.controls_action_edit) { /* */ /* 155 */ SavedSignaturePickerFragment.this.mActionMode = new ToolbarActionMode(context, SavedSignaturePickerFragment.this.mCabToolbar); /* 156 */ SavedSignaturePickerFragment.this.mActionMode.startActionMode(SavedSignaturePickerFragment.this.mActionModeCallback); /* 157 */ return true; /* */ } /* 159 */ return false; /* */ } /* */ }); /* */ } /* */ } /* */ /* 165 */ private ToolbarActionMode.Callback mActionModeCallback = new ToolbarActionMode.Callback() /* */ { /* */ public boolean onCreateActionMode(ToolbarActionMode mode, Menu menu) /* */ { /* 169 */ mode.inflateMenu(R.menu.cab_fragment_saved_signature); /* */ /* 171 */ if (SavedSignaturePickerFragment.this.mOnSavedSignatureListener != null) { /* 172 */ SavedSignaturePickerFragment.this.mOnSavedSignatureListener.onEditModeChanged(true); /* */ } /* */ /* 175 */ return true; /* */ } /* */ /* */ /* */ public boolean onActionItemClicked(ToolbarActionMode mode, MenuItem item) { /* 180 */ int id = item.getItemId(); /* */ /* 182 */ SparseBooleanArray selectedItems = SavedSignaturePickerFragment.this.mItemSelectionHelper.getCheckedItemPositions(); /* 183 */ int count = selectedItems.size(); /* 184 */ final List<Integer> indexes = new ArrayList<>(); /* 185 */ for (int i = 0; i < count; i++) { /* 186 */ if (selectedItems.valueAt(i)) { /* 187 */ indexes.add(Integer.valueOf(selectedItems.keyAt(i))); /* */ } /* */ } /* */ /* 191 */ if (indexes.size() == 0) { /* 192 */ return false; /* */ } /* */ /* 195 */ if (id == R.id.controls_signature_action_delete) { /* 196 */ AlertDialog.Builder builder = new AlertDialog.Builder(SavedSignaturePickerFragment.this.getContext()); /* 197 */ builder.setMessage(R.string.signature_dialog_delete_message) /* 198 */ .setTitle(R.string.signature_dialog_delete_title) /* 199 */ .setPositiveButton(R.string.tools_misc_yes, new DialogInterface.OnClickListener() /* */ { /* */ public void onClick(DialogInterface dialog, int which) /* */ { /* 203 */ Set<Integer> hs = new HashSet<>(indexes); /* 204 */ indexes.clear(); /* 205 */ indexes.addAll(hs); /* 206 */ Collections.sort(indexes); /* */ /* 208 */ for (int i = indexes.size() - 1; i >= 0; i--) { /* 209 */ int index = ((Integer)indexes.get(i)).intValue(); /* 210 */ SavedSignaturePickerFragment.this.mSavedSignatureAdapter.removeAt(index); /* 211 */ SavedSignaturePickerFragment.this.mSavedSignatureAdapter.notifyItemRemoved(index); /* */ } /* */ /* 214 */ SavedSignaturePickerFragment.this.clearSelectedList(); /* */ } /* 217 */ }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() /* */ { /* */ /* */ /* */ /* */ public void onClick(DialogInterface dialog, int which) {} /* 223 */ }).create() /* 224 */ .show(); /* */ } /* */ /* 227 */ return true; /* */ } /* */ /* */ /* */ public void onDestroyActionMode(ToolbarActionMode mode) { /* 232 */ SavedSignaturePickerFragment.this.mActionMode = null; /* 233 */ SavedSignaturePickerFragment.this.clearSelectedList(); /* */ /* 235 */ if (SavedSignaturePickerFragment.this.mOnSavedSignatureListener != null) { /* 236 */ SavedSignaturePickerFragment.this.mOnSavedSignatureListener.onEditModeChanged(false); /* */ } /* */ } /* */ /* */ /* */ public boolean onPrepareActionMode(ToolbarActionMode mode, Menu menu) { /* 242 */ if (Utils.isTablet(SavedSignaturePickerFragment.this.getContext()) || (SavedSignaturePickerFragment.this.getResources().getConfiguration()).orientation == 2) { /* 243 */ mode.setTitle(SavedSignaturePickerFragment.this.getString(R.string.controls_thumbnails_view_selected, new Object[] { /* 244 */ Utils.getLocaleDigits(Integer.toString(SavedSignaturePickerFragment.access$300(this.this$0).getCheckedItemCount())) })); /* */ } else { /* 246 */ mode.setTitle(Utils.getLocaleDigits(Integer.toString(SavedSignaturePickerFragment.this.mItemSelectionHelper.getCheckedItemCount()))); /* */ } /* 248 */ return true; /* */ } /* */ }; /* */ /* */ private boolean finishActionMode() { /* 253 */ boolean success = false; /* 254 */ if (this.mActionMode != null) { /* 255 */ success = true; /* 256 */ this.mActionMode.finish(); /* 257 */ this.mActionMode = null; /* */ } /* 259 */ clearSelectedList(); /* 260 */ return success; /* */ } /* */ /* */ private void clearSelectedList() { /* 264 */ if (this.mItemSelectionHelper != null) { /* 265 */ this.mItemSelectionHelper.clearChoices(); /* */ } /* 267 */ if (this.mActionMode != null) { /* 268 */ this.mActionMode.invalidate(); /* */ } /* */ } /* */ /* */ private boolean onBackPressed() { /* 273 */ if (!isAdded()) { /* 274 */ return false; /* */ } /* */ /* 277 */ boolean handled = false; /* 278 */ if (this.mActionMode != null) { /* 279 */ handled = finishActionMode(); /* */ } /* 281 */ return handled; /* */ } /* */ } /* Location: D:\ppt\library\pdftron.tool\jars\classes.jar!\com\pdftron\pdf\dialog\signature\SavedSignaturePickerFragment.class * Java compiler version: 7 (51.0) * JD-Core Version: 1.1.3 */
true
7e0ac0e99e5741c1a8f657a25d0bbde8cc5d2d91
Java
Wolffman/TheTravelingSalesman
/src/Answer.java
UTF-8
3,140
2.953125
3
[]
no_license
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * 
 * Created by student on 12/4/17. */ public class Answer { City[] cits = new City[20]; TestCities test = new TestCities(); City[] masterList = test.getCities(); public Answer(City[] cits) { this.cits = cits; } public Answer() { } public City[] getCits() { return cits; } public void create(City[] masterList) { List<City> copy = new ArrayList<City>(); for (int i = 0; i < masterList.length; i++) { copy.add(masterList[i]); } Answer x = new Answer(); for (int i = 0; i < masterList.length; i++) { int rand = (int) (Math.random() * copy.size()); x.getCits()[i] = copy.get(rand); copy.remove(rand); } this.setCits(x.getCits()); } public void setCits(City[] cits) { this.cits = cits; } public int getV() { int sum = 0; for (int i = 0; i < cits.length - 1; i++) { sum += cits[i].distanceTo(cits[i + 1]); } return sum; } public Answer[] mate(Answer other) { int pivot = cits.length / 2; Answer childr1 = new Answer(); Answer childr2 = new Answer(); for (int i = 0; i < cits.length; i++) { if (i < pivot) { childr1.getCits()[i] = cits[i]; childr2.getCits()[i + pivot] = other.getCits()[i]; } else { childr2.getCits()[i - pivot] = cits[i]; childr1.getCits()[i] = other.getCits()[i]; } } Answer[] offspring = new Answer[2]; childr1.clean(); childr2.clean(); offspring[0] = childr1; offspring[0] = childr2; return offspring; } public void clean() { List<City> dup = new ArrayList<>(); List<City> missing = new ArrayList<>(); List<City> copy = new ArrayList<>(); List<Integer> indexs = new ArrayList<>(); for (int i = 0; i < cits.length; i++) { copy.add(cits[i]); } for (int i = 0; i < copy.size(); i++) { if (copy.contains(copy.get(i)) && !dup.contains(copy.get(i))) { dup.add(copy.get(i)); indexs.add(i); } if (!copy.contains(masterList[i])) { missing.add(masterList[i]); } } for (int i = 0; i < dup.size(); i++) { copy.set(indexs.get(i), missing.get(i)); } indexs.clear(); missing.clear(); dup.clear(); for (int i = 0; i < copy.size(); i++) { cits[i] = copy.get(i); } copy.clear(); } public void mutate() { for (int i = 0; i < 2; i++) { int one = (int) (Math.random() * cits.length); int two = (int) (Math.random() * cits.length); City temp = cits[one]; cits[one] = cits[two]; cits[two] = temp; } } public void sort(){ } }
true
7ae333ebcc8268a4d591ab4443ba81e3b7581af6
Java
feirui/bagshow
/src/main/java/cn/feiruishu/service/ProductServiceImp.java
UTF-8
3,301
2.234375
2
[]
no_license
package cn.feiruishu.service; import cn.feiruishu.dao.FileDao; import cn.feiruishu.dao.ProductDao; import cn.feiruishu.pojo.FileForm; import cn.feiruishu.pojo.LayUiResult; import cn.feiruishu.pojo.Product; import cn.feiruishu.pojo.ProductForm; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; @Service public class ProductServiceImp implements ProductService { /** * */ @Autowired private ProductDao productDAO; @Autowired private FileDao fileDAO; @Override public LayUiResult findDatas(int page, int limit) { LayUiResult<ProductForm> result = new LayUiResult<>(); result.setCount(productDAO.countProductByPage()); List<Product> productList = productDAO.findAllProduct((page-1)*limit, page*limit); List<ProductForm> productFormList = new ArrayList<>(productList.size()); for(Product p : productList ){ ProductForm pf = new ProductForm(); BeanUtils.copyProperties(p,pf); List<FileForm> fileList = fileDAO.findFilesByProID(p.getId()); if(fileList.size()>0) { pf.setFileList(fileList); pf.setMainPic(fileList.get(0).getFileurl()); } productFormList.add(pf); } result.setData(productFormList); result.setMsg("查询成功。"); return result; } @Override public LayUiResult findData(Integer id) { LayUiResult<ProductForm> result = new LayUiResult<>(); Product p = productDAO.findProductById(id); if(p!=null) { ProductForm pf = new ProductForm(); BeanUtils.copyProperties(p, pf); pf.setFileList(fileDAO.findFilesByProID(p.getId())); result.setT(pf); result.setMsg("查询成功"); }else{ result.setMsg("没有查询到数据"); } result.setCount(1); return result; } @Override public LayUiResult findTopDatas(int page, int limit, String topshow) { LayUiResult<ProductForm> result = new LayUiResult<>(); result.setCount(productDAO.countTopProductByPage(topshow)); List<Product> productList = productDAO.findProduct((page-1)*limit, limit,topshow); List<ProductForm> productFormList = new ArrayList<>(productList.size()); for(Product p : productList ){ ProductForm pf = new ProductForm(); BeanUtils.copyProperties(p,pf); List<FileForm> fileList = fileDAO.findFilesByProID(p.getId()); if(fileList.size()>0) { pf.setFileList(fileList); pf.setMainPic(fileList.get(0).getFileurl()); } productFormList.add(pf); } result.setData(productFormList); return result; } @Override public int countTopDatas(String topshow) { return productDAO.countTopProductByPage(topshow); } @Override public LayUiResult addData(Object o) { Product p = (Product) o; productDAO.addProduct(p); LayUiResult result = new LayUiResult(); result.setT(p); result.setMsg("添加成功。"); return result; } @Override public LayUiResult modifyData(Object o) { Product p = (Product) o; productDAO.addProduct(p); LayUiResult result = new LayUiResult(); result.setCode(0); result.setMsg("修改成功"); result.setT(p); result.setCount(1); return result; } @Override public int deleteData(Integer id) { productDAO.deleteProduct(id); return id; } }
true
5870cbf4a626c613fbdf1fc8845edd8553838f7f
Java
Khalanirek/interviewApp
/src/main/java/com/example/interviewapp/repository/book/BookNotFoundException.java
UTF-8
297
2.1875
2
[]
no_license
package com.example.interviewapp.repository.book; import com.example.interviewapp.repository.EntityNotFoundException; public class BookNotFoundException extends EntityNotFoundException { public BookNotFoundException(Long id) { super(String.format("Book with id %d not found.", id)); } }
true
df3478dfab2d788acb5819bb8840c4e7648aafcf
Java
Tycdashuaige/common_parent
/bos_management/bos_management_service/src/main/java/com/tyc/bos/service/base/impl/FixedAreaServiceImpl.java
UTF-8
1,433
2.109375
2
[]
no_license
package com.tyc.bos.service.base.impl; import com.tyc.bos.dao.base.ICourierDao; import com.tyc.bos.dao.base.IFixedAreaDao; import com.tyc.bos.dao.base.ITakeTimeDao; import com.tyc.bos.domain.base.Courier; import com.tyc.bos.domain.base.FixedArea; import com.tyc.bos.domain.base.TakeTime; import com.tyc.bos.service.base.IFixedAreaService; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; @Service @Transactional public class FixedAreaServiceImpl implements IFixedAreaService { @Resource private IFixedAreaDao fixedAreaDao; @Resource private ICourierDao courierDao; @Resource private ITakeTimeDao takeTimeDao; @Override public void save(FixedArea model) { fixedAreaDao.save(model); } @Override public Page<FixedArea> pageQuery(Pageable pageable) { return fixedAreaDao.findAll(pageable); } @Override public void associationCourierToFixedArea(String id, Integer courierId, Integer takeTimeId) { Courier courier = courierDao.findOne(courierId); FixedArea fixedArea = fixedAreaDao.findOne(id); fixedArea.getCouriers().add(courier); TakeTime takeTime = takeTimeDao.findOne(takeTimeId); courier.setTakeTime(takeTime); } }
true
08a6a4370408545569c685983133d49b67ab417f
Java
marky24/TankShooter
/app/src/main/java/com/example/user/tankshooter/GlobalWars.java
UTF-8
404
1.828125
2
[]
no_license
package com.example.user.tankshooter; import android.graphics.Color; import android.graphics.Paint; /** * Created by user on 6/14/2016. */ public class GlobalWars { public static int W; public static int H; public static float A=0; public static float B=0; public static float D=0; public static float E=0; public static boolean C=true; public static double T=0; }
true
30bd1305a7ca2cc81997196a61ce297cfab2b9f6
Java
antobattista89/FuerzaArmada
/src/ar/edu/unlam/pb2/eva03/Anfibio.java
UTF-8
321
2.390625
2
[]
no_license
package ar.edu.unlam.pb2.eva03; public class Anfibio extends Acuatico{ private Double velocidad = 0.0; public Anfibio(Integer iD, String modelo) { super(iD, modelo); } public Double getVelocidad() { return velocidad; } public void setVelocidad(Double velocidad) { this.velocidad = velocidad; } }
true
cb428f28191fcc8060e3eaa6140d0f8a5937f8c0
Java
mandyGao/bcs_sdk_android
/src/main/java/com/baidu/inf/iis/bcs/utils/DateUtils.java
UTF-8
1,627
2.640625
3
[ "Apache-2.0" ]
permissive
package com.baidu.inf.iis.bcs.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.SimpleTimeZone; public class DateUtils { protected final SimpleDateFormat iso8601DateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); protected final SimpleDateFormat alternateIo8601DateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); protected final SimpleDateFormat rfc822DateParser = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); public DateUtils() { this.iso8601DateParser.setTimeZone(new SimpleTimeZone(0, "GMT")); this.rfc822DateParser.setTimeZone(new SimpleTimeZone(0, "GMT")); this.alternateIo8601DateParser.setTimeZone(new SimpleTimeZone(0, "GMT")); } public String formatIso8601Date(Date paramDate) { synchronized (this.iso8601DateParser) { return this.iso8601DateParser.format(paramDate); } } public String formatRfc822Date(Date paramDate) { synchronized (this.rfc822DateParser) { return this.rfc822DateParser.format(paramDate); } } public Date parseIso8601Date(String paramString) throws ParseException { try { synchronized (this.iso8601DateParser) { return this.iso8601DateParser.parse(paramString); } } catch (ParseException localParseException) { synchronized (this.alternateIo8601DateParser) { return this.alternateIo8601DateParser.parse(paramString); } } } public Date parseRfc822Date(String paramString) throws ParseException { synchronized (this.rfc822DateParser) { return this.rfc822DateParser.parse(paramString); } } }
true
5bba965f02bf66566880bb87668328c7a4a7563d
Java
skaraen/NPSC18
/app/src/main/java/com/nitt/karaens/npsc18/MyFirebaseMessagingService.java
UTF-8
1,720
1.921875
2
[]
no_license
package com.nitt.karaens.npsc18; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { Intent intent = new Intent(this,ScheduleActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this); notificationBuilder.setContentTitle(remoteMessage.getNotification().getTitle()); notificationBuilder.setContentText(remoteMessage.getNotification().getBody()); notificationBuilder.setAutoCancel(true); notificationBuilder.setSmallIcon(R.drawable.whiteicon).setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE) .setAutoCancel(true).setColor(getResources().getColor(R.color.maroon)); notificationBuilder.setContentIntent(pendingIntent).build(); NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0,notificationBuilder.build()); } @Override public void onNewToken(String s) { super.onNewToken(s); Log.d("TAG", s); } }
true
1492bf1e75bcd80a582a8c1f791d31480610dbe8
Java
artoro/Basics-of-programming
/Programming in JAVA/Lecture2-Spring_symulator_applet/Vector2D.java
UTF-8
684
3.546875
4
[]
no_license
public class Vector2D { public double x; public double y; public Vector2D() { x = 0; y = 0; } public Vector2D(double x, double y) { this.x = x; this.y = y; } public Vector2D add(Vector2D v) { return new Vector2D(x+v.x, y+v.y); } public Vector2D multiplyFactor(double d) { return new Vector2D(x*d, y*d); } public Vector2D sub(Vector2D v) { return new Vector2D(x-v.x, y-v.y); } public Vector2D norm() { //tworzy wersor Vector2D result = new Vector2D(x, y); if (x<0) result.x = -result.x; if (y<0) result.y = -result.y; return result; } public double length() { return Math.sqrt(x*x+y*y); } }
true
6fd410e497aaaaa27cbdabe67b11fbcc7f651564
Java
laizhiwei168/tank2
/src/main/java/com/cyws/tank/manager/dbutility/DbPoolConnection.java
UTF-8
1,971
2.265625
2
[]
no_license
package com.cyws.tank.manager.dbutility; import java.sql.SQLException; import java.util.Properties; //import org.apache.log4j.Logger; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.druid.pool.DruidPooledConnection; import com.cyws.tank.utils.common.PropertiesUtil; public class DbPoolConnection { //private static Logger logger = Logger.getLogger(DbPoolConnection.class); private static String dbtype = null; private static DruidDataSource dds = null; /* * static { Properties properties = loadPropertyFile("jdbc.properties"); try * { dds = (DruidDataSource) DruidDataSourceFactory * .createDataSource(properties); * * } catch (Exception e) { e.printStackTrace(); } } */ public static String getDbType() { if (dbtype == null) { Properties properties = PropertiesUtil.GetProperties("/resources/jdbc.properties");//resources/jdbc.properties dbtype = properties.get("dbType").toString(); } return dbtype; } public static String getDbType(String dbconfig) { Properties properties = PropertiesUtil.GetProperties(dbconfig); dbtype = properties.get("dbType").toString(); return dbtype; } public static Properties getProperties() { Properties properties=PropertiesUtil.GetProperties("/resources/jdbc.properties"); return properties; } public static DruidPooledConnection getConnection(String propertiesfile) { DruidPooledConnection dpc = null; if (propertiesfile == null || propertiesfile.equals("")) propertiesfile = "/resources/jdbc.properties"; Properties properties = PropertiesUtil.GetProperties(propertiesfile); try { if(dds==null){ dds = (DruidDataSource) DruidDataSourceFactory .createDataSource(properties); } dbtype = dds.getDbType(); } catch (Exception e) { e.printStackTrace(); } try { dpc = dds.getConnection(); } catch (SQLException ex) { ex.printStackTrace(); } return dpc; } }
true
8ea49c50e5561e3d664a221f772e2603f7663297
Java
terryaa/JAVA_SpringMVC_OracleDMBS_JavaScript_Servlet-jsp
/Java/Spring/spring02_13/src/aop/ex0/MessageImple.java
UHC
627
3
3
[]
no_license
package aop.ex0; public class MessageImple implements Messageinter { private String message; @Override public void print() { System.out.println("Print ޼ ȣ"); // TODO Auto-generated method stub } @Override public void print2() { System.out.println("print2ȣ"); // TODO Auto-generated method stub } @Override public void test() { System.out.println("test ޼尡 ȣ"); // TODO Auto-generated method stub } @Override public String message() { // TODO Auto-generated method stub System.out.println("$$$$$$$$$"); return "&&&&&&&&&&afterreturn"+message; } }
true
f5bf305241476e515980c894dbd69323756814f3
Java
cherryMaker/MAMA100_android
/src/com/mama100/android/member/bean/thirdparty/QQLoginBean.java
UTF-8
10,107
1.992188
2
[]
no_license
package com.mama100.android.member.bean.thirdparty; import java.util.ArrayList; import java.util.List; import android.net.Uri; import com.mama100.android.member.bean.ThirdPartyUser; import com.mama100.android.member.global.BasicApplication; import com.mama100.android.member.outwardWeibo.QQGetOpenIdRes; import com.mama100.android.member.outwardWeibo.QQPlatform; import com.mama100.android.member.outwardWeibo.QQUserRes; import com.mama100.android.member.util.LogUtils; /** * @author edwar * @version 创建时间:2012-09-26 17:55 * QQ聊天器帐号登录Bean */ public class QQLoginBean extends CommonBean { ////constant public static final String URL_ACTIVITY_CALLBACK = "http://www.mama100.com"; //网页授权后,返回的URL,此处自定义为letsgoweibo://AuthBackActivity.com public static final int REQ_AUTHOR=20; //请求授权,调用WebViewActivity的请求码 private static final String CONFIG_FILENAME="qqPlatformConfig"; /****************************************************************** * QQ专用字段 --START ******************************************************************/ private String figureurl;//figureurl: 大小为30×30像素的头像URL private String figureurl_1; //figureurl_1: 大小为50×50像素的头像URL private String figureurl_2; //figureurl_2: 大小为100×100像素的头像URL private String gender;//gender: 性别。如果获取不到则默认返回“男” private String vip;//vip: 标识用户是否为黄钻用户(0:不是;1:是) private String level; //level: 黄钻等级(如果是黄钻用户才返回此参数) /****************************************************************** * QQ专用字段 --END ******************************************************************/ private String TAG = this.getClass().getSimpleName(); //第三方的key private String secretKey; /**************************************************************** * Start 通用字段 ****************************************************************/ ////field protected static String accessToken; //授权密钥 protected static String expiresIn; //有效时间,单位秒 protected String uid; //授权的用户UID protected String nickname; //用户昵称 /****************** 关注妈妈100网 用到的变量******************************/ protected static boolean isFollowMama100; //是否关注妈妈100官方微博 public QQLoginBean(){ super(); secretKey = BasicApplication.getInstance().getQq_key(); // QQ登录操作之前,必须初始化 QQPlatform.getInstance().setConsumerConfig(secretKey); } //从本地拿数据 public void getValuesFromSharePreference(){ ThirdPartyUser item = BasicApplication.getInstance().getQqItems(); if(item!=null){ accessToken = item.getAccessToken(); expiresIn = item.getTokenExpireDate(); uid = item.getUid(); QQPlatform.getInstance().setAccessToken(accessToken); QQPlatform.getInstance().setExpiresIn(expiresIn); } // if (shareprefencefile != null) { // accessToken=shareprefencefile.getString(QQPlatform.TOKEN, ""); // expiresIn=shareprefencefile.getString(QQPlatform.EXPIRES, ""); // uid=shareprefencefile.getString(QQPlatform.OPEN_ID, ""); //相当于QQ的openId // nickname=shareprefencefile.getString(QQPlatform.NICKNAME, ""); // } } public void setValues(){ if (isAccessTokenValid()) { LogUtils.loge("TAG", ">Access_token : " + accessToken + " \n\n >Expires_in: " + expiresIn); // set token QQPlatform.getInstance().setAccessToken(accessToken); QQPlatform.getInstance().setExpiresIn(expiresIn); } if(isNicknameValid()){ LogUtils.loge("TAG","\n\n>你好,"+nickname); } } /** * 获取授权成功后的基本授权信息 * @param newS 第三方授权成功后返回的字符串 */ public void setValuesIntoSharedPreference(String newS){ Uri newUri = Uri.parse(newS); accessToken = newUri.getQueryParameter("access_token"); expiresIn = newUri.getQueryParameter("expires_in"); //set token QQPlatform.getInstance().setAccessToken(accessToken); QQPlatform.getInstance().setExpiresIn(expiresIn); // final Editor edit=shareprefencefile.edit(); // edit.putString(QQPlatform.TOKEN, accessToken); // edit.putString(QQPlatform.EXPIRES, expiresIn); // edit.commit(); ThirdPartyUser item = BasicApplication.getInstance().getQqItems(); item.setAccessToken(accessToken); item.setTokenExpireDate(expiresIn); BasicApplication.getInstance().setQqItems(item); } public static String authorUrl(){ String url=QQPlatform.URL_OAUTH2_ACCESS_AUTHORIZE + "?response_type=token&display=mobile&scope=get_user_info,get_simple_userinfo"+"&client_id="+ QQPlatform.getAppId()+"&redirect_uri="+URL_ACTIVITY_CALLBACK; return url; } /** * 获取第三方用户的 具体用户信息 * @param xRes 获取第三方信息获得的响应 */ public void setValuesIntoSharedPreference(QQUserRes qRes) { nickname=qRes.getNickname(); // figureurl = qRes.getFigureurl(); //获取用户的头像路径 // figureurl = qRes.getFigureurl_1(); //获取用户的头像路径 figureurl = qRes.getFigureurl_2(); //获取用户的头像路径 LogUtils.loge(TAG, "nickname from QQ - " + nickname + ",\n"+ "avatar_url from QQ - " + figureurl); // BasicApplication.getInstance().setNickname(nickname); BasicApplication.getInstance().setWeiboNickname(nickname); BasicApplication.getInstance().setWeiboAvatarUrl(figureurl); // final Editor edit=shareprefencefile.edit(); // edit.putString(QQPlatform.NICKNAME, nickname); // edit.putString(XWeibo.AVATAR_URL, figureurl); // edit.commit(); } /** * 获取授权成功后,第三方用户的 Uid * @param xRes 获取第三方信息获得的响应 */ public void setValuesIntoSharedPreference(QQGetOpenIdRes response) { uid=((QQGetOpenIdRes)response).getOpenid(); //QQ的uid用 openId代替 // final Editor edit=shareprefencefile.edit(); // edit.putString(QQPlatform.OPEN_ID, uid); // edit.commit(); ThirdPartyUser item = BasicApplication.getInstance().getQqItems(); item.setUid(uid); BasicApplication.getInstance().setQqItems(item); // added by edwar 2012-10-25, 解决同一个uid,仅第一次才进入个人信息界面 List<String> uidList = BasicApplication.getInstance().getQQUidList(); if (uidList == null) { uidList = new ArrayList<String>(); } if (uidList.isEmpty()) { uidList.add(uid); BasicApplication.getInstance().setNewQQUid(true); } else { if (!uidList.contains(uid)) { uidList.add(uid); BasicApplication.getInstance().setNewQQUid(true); }else{ BasicApplication.getInstance().setNewQQUid(false); } } BasicApplication.getInstance().setQQUidList(uidList);//更新列表 //added end 2012-10-25 LogUtils.loge(TAG, " - QQLoginBean uid= "+uid); } /*********************************************************************** * 基本的getter 和 setter 方法 **********************************************************************/ public String getFigureurl() { return figureurl; } public void setFigureurl(String figureurl) { this.figureurl = figureurl; } public String getFigureurl_1() { return figureurl_1; } public void setFigureurl_1(String figureurl_1) { this.figureurl_1 = figureurl_1; } public String getFigureurl_2() { return figureurl_2; } public void setFigureurl_2(String figureurl_2) { this.figureurl_2 = figureurl_2; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getVip() { return vip; } public void setVip(String vip) { this.vip = vip; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("==== QQ登录用户信息 START ===" + "\n"); sb.append("accessToken = "+ accessToken+ "\n"); sb.append("expiredTime = "+ expiresIn+ "\n"); sb.append("userId = "+ uid+ "\n"); sb.append("nickname = "+ nickname+ "\n"); sb.append("figureurl = "+ figureurl+ "\n"); sb.append("figureurl_1 = "+ figureurl_1+ "\n"); sb.append("figureurl_2 = "+ figureurl_2+ "\n"); sb.append("gender = "+ gender+ "\n"); sb.append("vip = "+ vip+ "\n"); sb.append("level = "+ level+ "\n"); sb.append("==== QQ登录用户信息 END ==="+ "\n"); return sb.toString(); } /*********************************************************************** * 基本的getter 和 setter 方法 **********************************************************************/ public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getExpiresIn() { return expiresIn; } public void setExpiresIn(String expiresIn) { this.expiresIn = expiresIn; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public static boolean isFollowMama100() { return isFollowMama100; } public static void setFollowMama100(boolean isFollowMama100) { isFollowMama100 = isFollowMama100; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public boolean isAccessTokenValid() { return accessToken!=null&&!accessToken.equals(""); } public boolean isUidValid() { return uid!=null&&!uid.equals(""); } public boolean isNicknameValid() { return nickname!=null&&!nickname.equals(""); } }
true
30ccd5ba77355a2348cc7342e295c7a469972dfb
Java
nyarikikevin/Conversational-AI-for-Farmers
/Android/MyApplication/app/src/main/java/e/chandrakumar/myapplication/Helper.java
UTF-8
6,744
2.796875
3
[]
no_license
package e.chandrakumar.myapplication; import android.util.Log; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class Helper { private String unzipedLocation; List<StationDetails> stationDetails=new ArrayList<>(); List<LatLng> historicalDataLatLng=new ArrayList<>(); List<PredictionResults> predictionResults=new ArrayList<>(); List<WeatherDetails> weatherDetails=new ArrayList<>(); Helper(String unzipedLocation){ this.unzipedLocation=unzipedLocation; getStationDetailsFromFile(); fedHistoricalData(); getPredictResults(); getWeatherDetails(); } private void getStationDetailsFromFile(){ InputStream index= null; try { index = new FileInputStream(unzipedLocation+"index.csv"); BufferedReader reader=new BufferedReader( new InputStreamReader(index, Charset.forName("UTF-8")) ); try { reader.readLine(); String line=""; while ((line=reader.readLine())!=null){ StationDetails details=new StationDetails(); String[] values=line.split(","); details.setName(values[0]); details.setLatitude(Double.parseDouble(values[1])); details.setLongitude(Double.parseDouble(values[2])); stationDetails.add(details); Log.d("Station name is",values[0]); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private void fedHistoricalData(){ for (StationDetails stationDetails:stationDetails){ LatLng latLng=new LatLng(); latLng.setLongitude(stationDetails.getLongitude()); latLng.setLatitude(stationDetails.getLatitude()); historicalDataLatLng.add(latLng); } } private void getWeatherDetails() { for (StationDetails stationDetails:stationDetails){ try { Log.d("Trying to open",stationDetails.getName()+".csv"); InputStream index = new FileInputStream(unzipedLocation+stationDetails.getName()+".csv"); Log.d(unzipedLocation+stationDetails.getName()+".csv","SUCCESS"); BufferedReader reader=new BufferedReader( new InputStreamReader(index, Charset.forName("UTF-8")) ); reader.readLine(); String line=""; List<Double> jan=new ArrayList<>() ,feb=new ArrayList<>() ,mar=new ArrayList<>() ,apr=new ArrayList<>() ,may=new ArrayList<>() ,jun=new ArrayList<>() ,jul=new ArrayList<>() ,aug=new ArrayList<>() ,sep=new ArrayList<>() ,oct=new ArrayList<>() ,nov=new ArrayList<>() , dec=new ArrayList<>(); int month=1; WeatherDetails details=new WeatherDetails(); while ((line=reader.readLine())!=null){ String[] value=line.split(","); jan.add(Double.parseDouble(value[month++])); feb.add(Double.parseDouble(value[month++])); mar.add(Double.parseDouble(value[month++])); apr.add(Double.parseDouble(value[month++])); may.add(Double.parseDouble(value[month++])); jun.add(Double.parseDouble(value[month++])); jul.add(Double.parseDouble(value[month++])); aug.add(Double.parseDouble(value[month++])); sep.add(Double.parseDouble(value[month++])); oct.add(Double.parseDouble(value[month++])); nov.add(Double.parseDouble(value[month++])); dec.add(Double.parseDouble(value[month])); month=1; } details.setId(stationDetails.getName()); details.setJan(jan); details.setFeb(feb); details.setMar(mar); details.setApr(apr); details.setMay(may); details.setJun(jun); details.setJul(jul); details.setAug(aug); details.setSep(sep); details.setOct(oct); details.setNov(nov); details.setDec(dec); weatherDetails.add(details); Log.d("Jan 2000 at "+stationDetails.getName(),weatherDetails.get(weatherDetails.size()-1).jan+""); } catch (Exception e) { Log.d(unzipedLocation+stationDetails.getName()+".csv","Failed"); e.printStackTrace(); } } } private void getPredictResults(){ for (StationDetails stationDetails:stationDetails){ try { InputStream index = new FileInputStream(unzipedLocation+stationDetails.getName()+"predict.txt"); Log.d(unzipedLocation+stationDetails.getName()+"predict.txt","SUCCESS"); BufferedReader reader=new BufferedReader( new InputStreamReader(index, Charset.forName("UTF-8")) ); try { PredictionResults results = new PredictionResults(); String line=""; List<Double> predict=new ArrayList<>(); int year=0; while ((line=reader.readLine())!=null) { String[] value=line.split(" "); year=Integer.parseInt(value[1]); predict.add(Double.parseDouble(value[2])); Log.d(stationDetails.getName(),value[2]+" "+year); } results.setName(stationDetails.getName()); results.setPredictVal(predict); results.setYear(year); predictionResults.add(results); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } } }
true
95defd9690f2d0ca8c22cebb028ba29c85989428
Java
javateaminiyan/newdemoService_V
/src/main/java/com/smw/velloredemo/repository/UserDaoImpl.java
UTF-8
6,200
2.09375
2
[]
no_license
package com.smw.velloredemo.repository; import com.smw.velloredemo.Pojo.User; import com.smw.velloredemo.Pojo.vehiclereportpojo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import java.sql.*; import java.util.List; @Repository public class UserDaoImpl { private final String INSERT_SQL = "INSERT INTO USERS(name,address,email) values(?,?,?)"; private final String FETCH_SQL = "select record_id, name, address, email from users"; private final String FETCH_SQL_BY_ID = "select * from users where record_id = ?"; private final String FETCH_RECORD = "select * from vehiclereport where Date(intime) BETWEEN ? AND ? "; private final String FETCH_VEHICLE_DATES = "select * from vehiclereport where vehicleno=? And Date(intime) BETWEEN ? AND ?"; private final String FETCH_RFID_DATE_UPDATE = "SELECT vehicleid from swm.vehiclereport where userid=? && UNIX_TIMESTAMP(intime) = UNIX_TIMESTAMP(outtime) && DATE(intime) =CURDATE() ORDER BY vehicleid Desc LIMIT 1"; private final String CHECK_INTERVAL_1HR = "select round(timestampdiff(second,UNIX_TIMESTAMP(intime), UNIX_TIMESTAMP(outtime))/3600)as hours from swm.vehiclereport "; private final String FETCH_RFID_UPDATE_TIMESTAMP = "update swm.vehiclereport set outtime=CURRENT_TIMESTAMP() where vehicleid=? && userid=?"; @Autowired private JdbcTemplate jdbcTemplate; public User create(final User user) { try { KeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, Statement.RETURN_GENERATED_KEYS); ps.setString(1, user.getName()); ps.setString(2, user.getAddress()); ps.setString(3, user.getEmail()); return ps; } }, holder); int newUserId = holder.getKey().intValue(); user.setId(newUserId); return user; } catch (EmptyResultDataAccessException e) { return null; } } public List findAll() { try { return jdbcTemplate.query(FETCH_SQL, new UserMapper()); } catch (EmptyResultDataAccessException e) { return null; } } public User findUserById(int id) { try { return (User) jdbcTemplate.queryForObject(FETCH_SQL_BY_ID, new Object[]{id}, new UserMapper()); } catch (EmptyResultDataAccessException e) { return null; } } public List responseEntity(String fromdate, String todate) { try { return jdbcTemplate.query(FETCH_RECORD, new Object[]{fromdate, todate}, new VehicleMapper()); } catch (EmptyResultDataAccessException e) { return null; } } public List responseEntitywithVehicle(String fromdate, String todate, String vehicleno) { try { return jdbcTemplate.query(FETCH_VEHICLE_DATES, new Object[]{vehicleno, fromdate, todate}, new VehicleMapper()); } catch (EmptyResultDataAccessException e) { return null; } } public String rfidcheckAlreadyLoggedornotVerify(String userid) { try { // String check= jdbcTemplate.queryForObject(CHECK_INTERVAL_1HR, new Object[]{userid}, String.class); // return check; return jdbcTemplate.queryForObject(FETCH_RFID_DATE_UPDATE, new Object[]{userid}, String.class); } catch (EmptyResultDataAccessException e) { return null; } } public String rfidupdate(long vehicleno, String userid) { try { //jdbcTemplate.update(FETCH_RFID_UPDATE_TIMESTAMP, new Object[]{vehicleno,userid}, Object.class); jdbcTemplate.update(FETCH_RFID_UPDATE_TIMESTAMP, vehicleno, userid); return "success"; } catch (EmptyResultDataAccessException e) { return null; } } } class UserMapper implements RowMapper { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("record_id")); user.setName(rs.getString("name")); user.setEmail(rs.getString("address")); user.setEmail(rs.getString("email")); return user; } } class VehicleMapper implements RowMapper { @Override public vehiclereportpojo mapRow(ResultSet rs, int rowNum) throws SQLException { vehiclereportpojo vehiclereportpojo = new vehiclereportpojo(); vehiclereportpojo. setVehicleid(rs.getString("vehicleid")) .setVehiclename(rs.getString("vehiclename")) .setVehiclecapacity(rs.getString("vehiclecapacity")) .setVehicleinformation(rs.getString("vehicleinformation")) .setUserid(rs.getString("userid")) .setMobileno(rs.getString("mobileno")) .setIntime(rs.getString("intime").replace(' ', 'T')) .setOuttime(rs.getString("outtime").replace(' ', 'T')) .setUpdateby(rs.getString("updateby")) .setRfid(rs.getString("rfid")) .setTotalquantity(rs.getString("totalquantity")) .setWet(rs.getString("wet")) .setDry(rs.getString("dry")) .setCreatedon(rs.getString("createdon")) .setEntrytype(rs.getString("entrytype")) .setVehicleno(rs.getString("vehicleno")); return vehiclereportpojo; } }
true
243256661c2959c819f455aa33e13226379a8174
Java
ishu2/DS-and-Algorithms
/_Arrays/ConstructArrayFromXORofAllElementsOfArrayExceptElementAtSameIndex.java
UTF-8
2,419
4.03125
4
[]
no_license
// Element at any index is equal to XOR of elements at its left and right. package GeeksForGeeks_Arrays; import java.util.Scanner; public class ConstructArrayFromXORofAllElementsOfArrayExceptElementAtSameIndex { public static void optimisedUsingExtraSpaceMethod(int[] arr) { if(arr.length==0) { System.out.println("No such array !!"); return ; } if(arr.length==1) { System.out.println("0"); return; } if(arr.length==2) { System.out.println(arr[1]+" , "+arr[0]); return; } int[] left=new int[arr.length]; int[] right=new int[arr.length]; left[0]=0; for(int i=1;i<arr.length;i++) { left[i]=left[i-1]^arr[i-1]; } right[arr.length-1]=0; for(int i=arr.length-2;i>=0;i--) { right[i]=right[i+1]^arr[i+1]; } for(int i=0;i<arr.length;i++) { System.out.print((left[i]^right[i])+" "); } System.out.println(); } public static void bruteForceMethod(int[] arr) { if(arr.length==0) { System.out.println("No such array !!"); return ; } if(arr.length==1) { System.out.println("0"); return; } if(arr.length==2) { System.out.println(arr[1]+" , "+arr[0]); return; } for(int i=0;i<arr.length;i++) { int res=0; for(int j=0;j<arr.length;j++) { if(i!=j) { res=res^arr[j]; } } System.out.print(res+" "); } System.out.println(); } public static void bestOptimisedMethod(int[] arr) { if(arr.length==0) { System.out.println("No such array !!"); return ; } if(arr.length==1) { System.out.println("0"); return; } if(arr.length==2) { System.out.println(arr[1]+" , "+arr[0]); return; } int xor=0; for(int i=0;i<arr.length;i++) { xor=xor^arr[i]; } int[] res=new int[arr.length]; for(int i=0;i<arr.length;i++) { res[i]=arr[i]^xor; } for(int i=0;i<res.length;i++) { System.out.print(res[i]+" "); } System.out.println(); } public static void main(String[] args) { Scanner s=new Scanner(System.in); System.out.println("Enter size of array :"); int n=s.nextInt(); int[] arr=new int[n]; System.out.println("Enter array elememnts :"); for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } System.out.println("New required array formed is :"); bruteForceMethod(arr); optimisedUsingExtraSpaceMethod(arr); bestOptimisedMethod(arr); } }
true
29c177c6e0966d880737d74aa6aae4ec4e3bdea6
Java
MummiSnow/Graphs
/src/graphs/TestIt.java
UTF-8
3,317
3.234375
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 graphs; import graphs.algorithms.BreadthFirst; import graphs.simpleimpl.GraphBuilderImpl; import import java.util.*; /** * * @author Mohammed Salameh * This will work with the books implementation of Graphs. */ public class TestIt { /*public static void main(String[] args) { GraphBuilder gb = new GraphBuilderImpl(); BuildNode a = gb.createNode("A"); BuildNode b = gb.createNode("B"); BuildNode c = gb.createNode("C"); BuildNode d = gb.createNode("D"); BuildNode e = gb.createNode("E"); gb.createEdge(a, b); gb.createEdge(b, a); gb.createEdge(a, d); gb.createEdge(d, a); gb.createEdge(b, c); gb.createEdge(c, d); gb.createEdge(c, c); gb.createEdge(c, e); gb.createEdge(e, d); Graph g = gb.build(); Iterable<Node> res = BreadthFirst.runBreadthFirst(g.findNode("A")); for(Node n : res) { System.out.println(n.getName()); } } */ } class CycleDetecton { private boolean[] marked; private int[] edgeTo; private Stack<Integer> cycle; //Determines whether the undirected graph has a cycle //NOTE: GRAPH is the BOOKS IMplEMENTATION public CycleDetecton(Graph G) { if (hasSelfLoop(G)) return; marked = new boolean[G.V()]; edgeTo = new int[G.V()]; for (int v = 0; v < G.V(); v++) if (!marked[v]) dfs(G, -1, v); } // does this graph have a self loop? // side effect: initialize cycle to be self loop private boolean hasSelfLoop(Graph G) { for (int v = 0; v < G.V(); v++) { for (int w : G.adj(v)) { if (v == w) { cycle = new Stack<Integer>(); cycle.push(v); cycle.push(v); return true; } } } return false; } //Returns true if the graph has a cycle. public boolean hasCycle() { return cycle != null; } //Returns a cycle in the graph public Iterable<Integer> cycle() { return cycle; } private void dfs(Graph G, int u, int v) { marked[v] = true; for (int w : G.adj(v)) { // short circuit if cycle already found if (cycle != null) return; if (!marked[w]) { edgeTo[w] = v; dfs(G, v, w); } // check for cycle (but disregard reverse of edge leading to v) else if (w != u) { cycle = new Stack<Integer>(); for (int x = v; x != w; x = edgeTo[x]) { cycle.push(x); } cycle.push(w); cycle.push(v); } } } }
true
85d322353af2ae110d495ce33111c4265c4e2129
Java
AnasHamed73/sources
/AndroidStudioProjects/CriminalIntent/app/src/main/java/com/example/kikuchio/criminalintent/CriminalIntentJsonSerializer.java
UTF-8
2,033
2.546875
3
[]
no_license
package com.example.kikuchio.criminalintent; import android.content.Context; import android.support.annotation.NonNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONTokener; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; public class CriminalIntentJsonSerializer { private Context mContext; private String mFileName; public CriminalIntentJsonSerializer(Context c, String fileName) { mContext = c; mFileName = fileName; } public void saveCrimes(List<Crime> crimes) throws IOException, JSONException { JSONArray jsonArray = new JSONArray(); for (Crime c : crimes) jsonArray.put(c.toJson()); try (Writer writer = getOutputStreamWriter()) { writer.write(jsonArray.toString()); } } public List<Crime> loadCrimes() throws IOException, JSONException { List<Crime> crimes = new ArrayList<>(); try(BufferedReader reader = new BufferedReader(new InputStreamReader(mContext.openFileInput(mFileName)))) { StringBuilder builder = new StringBuilder(); String line; while((line = reader.readLine()) != null) { builder.append(line); } JSONArray jsonArray = (JSONArray) new JSONTokener(builder.toString()).nextValue(); for(int i = 0; i < jsonArray.length(); i++) { crimes.add(new Crime(jsonArray.getJSONObject(i))); } } catch (FileNotFoundException e) { //ignored } return crimes; } @NonNull private OutputStreamWriter getOutputStreamWriter() throws FileNotFoundException { return new OutputStreamWriter(mContext.openFileOutput(mFileName, Context.MODE_PRIVATE)); } }
true
aaf33bd946b1aa879273920824d41dd9ee90b3ab
Java
potionk/baekjoon
/src/bj11048/Main.java
UTF-8
1,062
2.984375
3
[]
no_license
package bj11048; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { static int[][] graph, dp; static int xSize, ySize; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] size = br.readLine().split(" "); ySize = Integer.parseInt(size[0]); xSize = Integer.parseInt(size[1]); graph = new int[ySize + 1][xSize + 1]; dp = new int[ySize + 1][xSize + 1]; for (int i = 1; i <= ySize; i++) { String[] input = br.readLine().split(" "); for (int j = 1; j <= xSize; j++) { graph[i][j] = Integer.parseInt(input[j - 1]); } } for (int i = 1; i < ySize + 1; i++) { for (int j = 1; j < xSize + 1; j++) { dp[i][j] = Math.max(graph[i][j] + dp[i - 1][j], graph[i][j] + dp[i][j - 1]); } } System.out.println(dp[ySize][xSize]); } }
true
56588d4a6a6405eb04f968df4d7b983d32e645c6
Java
jessicanasr/IFT215-PROJET
/IFT215-JESSICA/src/ift215/jn/GUI.java
UTF-8
20,592
2.21875
2
[]
no_license
package ift215.jn; import javax.swing.JOptionPane; public class GUI extends javax.swing.JFrame { public GUI() { initComponents(); this.setLocationRelativeTo(this); cbxCountry.equals("Lebanon"); rbCash.setSelected(false); rbCard.setSelected(false); rootPane.setDefaultButton(btnSubmit); this.setTitle("Shipping Information"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup2 = new javax.swing.ButtonGroup(); pnlShippingInformation = new javax.swing.JPanel(); lblName = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); lblCountry = new javax.swing.JLabel(); lblAddress = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); txtAAddress = new javax.swing.JTextArea(); cbxCountry = new javax.swing.JComboBox(); jPanel1 = new javax.swing.JPanel(); lblExpirationDate = new javax.swing.JLabel(); btnSubmit = new javax.swing.JButton(); lblSecurityCode = new javax.swing.JLabel(); rbCard = new javax.swing.JRadioButton(); txtCard = new javax.swing.JTextField(); txtExpirationDate1 = new javax.swing.JTextField(); txtExpirationdate2 = new javax.swing.JTextField(); txtSecurityCode = new javax.swing.JTextField(); rbCash = new javax.swing.JRadioButton(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); txtAShippingInformation = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); pnlShippingInformation.setBorder(javax.swing.BorderFactory.createTitledBorder("Buyer Information")); lblName.setText("Name:"); txtName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNameActionPerformed(evt); } }); lblCountry.setText("Country:"); lblAddress.setText("Address:"); txtAAddress.setColumns(20); txtAAddress.setRows(5); jScrollPane1.setViewportView(txtAAddress); cbxCountry.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Lebanon", "USA", "France" })); cbxCountry.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbxCountryActionPerformed(evt); } }); javax.swing.GroupLayout pnlShippingInformationLayout = new javax.swing.GroupLayout(pnlShippingInformation); pnlShippingInformation.setLayout(pnlShippingInformationLayout); pnlShippingInformationLayout.setHorizontalGroup( pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlShippingInformationLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlShippingInformationLayout.createSequentialGroup() .addComponent(lblName) .addGap(51, 51, 51)) .addGroup(pnlShippingInformationLayout.createSequentialGroup() .addGroup(pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblAddress) .addComponent(lblCountry, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28))) .addGroup(pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbxCountry, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pnlShippingInformationLayout.setVerticalGroup( pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlShippingInformationLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblName) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblCountry) .addComponent(cbxCountry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlShippingInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblAddress) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Payment Method")); lblExpirationDate.setText("Expiration date "); btnSubmit.setText("Submit"); btnSubmit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSubmitActionPerformed(evt); } }); lblSecurityCode.setText("Security code "); buttonGroup2.add(rbCard); rbCard.setText("Card"); rbCard.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { rbCardStateChanged(evt); } }); txtCard.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N txtCard.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR)); txtSecurityCode.setText(" "); buttonGroup2.add(rbCash); rbCash.setText("Cash"); rbCash.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { rbCashStateChanged(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(186, 186, 186) .addComponent(btnSubmit) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(rbCash) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lblExpirationDate) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtExpirationDate1, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtExpirationdate2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(66, 66, 66) .addComponent(lblSecurityCode) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtSecurityCode, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(rbCard) .addGap(32, 32, 32) .addComponent(txtCard))) .addContainerGap(369, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(rbCash) .addGap(7, 7, 7) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rbCard) .addComponent(txtCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblExpirationDate) .addComponent(lblSecurityCode) .addComponent(txtExpirationDate1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtExpirationdate2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtSecurityCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(btnSubmit) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Shipping Information")); txtAShippingInformation.setEditable(false); txtAShippingInformation.setColumns(20); txtAShippingInformation.setRows(5); jScrollPane2.setViewportView(txtAShippingInformation); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(21, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(pnlShippingInformation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(pnlShippingInformation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtNameActionPerformed @SuppressWarnings("empty-statement") private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed // TODO add your handling code here: if(txtName.getText().trim().equals("")){ JOptionPane.showMessageDialog(this, "Please enter name","Waring",JOptionPane.INFORMATION_MESSAGE); } else{ int country = Integer.parseInt( cbxCountry.getSelectedItem().toString()); if(cbxCountry.equals ("Lebanon")){ rbCash.setSelected(true); rbCard.setSelected(false); } else if(cbxCountry.equals("USA")){ rbCard.setSelected(true); rbCash.setSelected(false); } else{ cbxCountry.equals("France"); rbCash.setSelected(true); rbCard.setSelected(true); } boolean cash; boolean card; card = rbCard.isSelected(); String name = txtName.getText(); String address = txtAAddress.getText(); ShippingInformation si = new ShippingInformation( country, name, address); txtAShippingInformation.setText(si.getShippingInformation()); } } private void changeCountryValues(String name){ cbxCountry.removeAllItems(); switch(name){ case"Cash": cbxCountry.addItem("Lebanon"); break; case "Card": cbxCountry.addItem("USA"); cbxCountry.addItem("France"); break; default: cbxCountry.addItem("France"); } }//GEN-LAST:event_btnSubmitActionPerformed private void rbCardStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_rbCardStateChanged // TODO add your handling code here: if (cbxCountry.equals("USA")){ rbCash.setSelected(true); txtCard.setText(" "); } }//GEN-LAST:event_rbCardStateChanged private void rbCashStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_rbCashStateChanged // TODO add your handling code here: if (cbxCountry.equals("Lebanon")){ rbCash.setSelected(true); } }//GEN-LAST:event_rbCashStateChanged private void cbxCountryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxCountryActionPerformed // TODO add your handling code here: if(cbxCountry.equals("Lebanon")){ rbCash.setSelected(true); } else{ if(cbxCountry.equals("USA")){ rbCard.setSelected(true); } else{cbxCountry.equals("France"); } } }//GEN-LAST:event_cbxCountryActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new GUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnSubmit; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.JComboBox cbxCountry; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel lblAddress; private javax.swing.JLabel lblCountry; private javax.swing.JLabel lblExpirationDate; private javax.swing.JLabel lblName; private javax.swing.JLabel lblSecurityCode; private javax.swing.JPanel pnlShippingInformation; private javax.swing.JRadioButton rbCard; private javax.swing.JRadioButton rbCash; private javax.swing.JTextArea txtAAddress; private javax.swing.JTextArea txtAShippingInformation; private javax.swing.JTextField txtCard; private javax.swing.JTextField txtExpirationDate1; private javax.swing.JTextField txtExpirationdate2; private javax.swing.JTextField txtName; private javax.swing.JTextField txtSecurityCode; // End of variables declaration//GEN-END:variables //private void changeCountryValues(String lebanon) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }
true
343997b7ba9bbd7b9a1ba30ae1edc840ab75d224
Java
toolisticon/annotation-constraints
/annotationconstraints-processor/src/test/java/io/toolisticon/annotationconstraints/processor/testconstraint/TestConstraintAnnotation.java
UTF-8
478
1.773438
2
[ "MIT" ]
permissive
package io.toolisticon.annotationconstraints.processor.testconstraint; import io.toolisticon.annotationconstraints.api.Constraint; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) @Constraint public @interface TestConstraintAnnotation { boolean shouldCompilationSucceed(); }
true
f8ca691e5920b6932f175796bddc142ad4cdcb8c
Java
wangjw0811/family
/src/main/java/com/family/entity/vo/PeopleVO.java
UTF-8
248
1.757813
2
[]
no_license
package com.family.entity.vo; import lombok.Builder; import lombok.Data; @Builder @Data public class PeopleVO{ /** * 代数 */ private Integer generation; /** * 代数说明 */ private String generationDesc; }
true
ab8637a20af374325caa9695356973b3bdf801e7
Java
CeliaBenquet/public
/exercises/requirements/solutions/cucumber/src/test/java/ch/sweng/inventory/StepDefinitions.java
UTF-8
1,766
2.875
3
[ "Apache-2.0" ]
permissive
package ch.sweng.inventory; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import static org.junit.Assert.*; public class StepDefinitions { private Inventory inventory; @Given("there are {int} sweaters in the inventory") public void withXSweatersInInventory(int nSweaters){ this.inventory = new Inventory(); for (int i = 0; i < nSweaters; i++) { this.inventory.add(Product.SWEATER); } } @Given("there are {int} t-shirts in the inventory") public void withXTshirtsInInventory(int ntshirts){ this.inventory = new Inventory(); for (int i = 0; i < ntshirts; i++) { this.inventory.add(Product.TSHIRT); } } @When("I add {int} sweaters to the inventory") public void addXSweatersToInventory(int nSweaters){ for (int i = 0; i < nSweaters; i++) { this.inventory.add(Product.SWEATER); } } @When("I remove {int} t-shirts from the inventory") public void addXTshirtsToInventory(int ntshirts){ for (int i = 0; i < ntshirts; i++) { this.inventory.remove(Product.TSHIRT); } } @When("I refund a client that bought a t-shirt") public void refundTshirt(){ this.inventory.returnAndRefund(Product.TSHIRT); } @Then("the inventory contains {int} t-shirts") public void checkInventoryContainsXTshirts(int nTshirts){ assertEquals(nTshirts, this.inventory.getProductQuantity(Product.TSHIRT)); } @Then("the inventory contains {int} sweaters") public void checkInventoryContainsXSweaters(int nSweaters){ assertEquals(nSweaters, this.inventory.getProductQuantity(Product.SWEATER)); } }
true
a883f6962bea3e46d50f4134c26ec434ebae3787
Java
orion-open-group/gateway
/gateway-dao/src/main/java/com/orion/mobile/gateway/enums/ServiceOperType.java
UTF-8
217
1.609375
2
[]
no_license
package com.orion.mobile.gateway.enums; /** * @Description TODO * @Author potsmart * @Date 2019/10/31 17:17 * @Version 1.0.0 */ public enum ServiceOperType { ADD, DELETE, MODIFY,DISABLE,ENABLE; }
true
5ea9ff37f53d205cb489b98e6443242233851dc7
Java
jfeliperc/japp-rep
/japp/JavaSource/com/module/ejb/EstoqueEjb.java
UTF-8
1,156
2.15625
2
[]
no_license
package com.module.ejb; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import com.module.ejb.contract.IEstoqueEjb; import com.module.faces.geral.UtilsJapp; import com.module.jpa.dao.EstoqueDao; import com.module.jpa.dao.MovimentoEstoqueDao; import com.module.jpa.model.Estoque; import com.module.jpa.model.EstoqueMovimento; import com.module.jpa.model.Produto; @Stateless public class EstoqueEjb implements IEstoqueEjb { @Override public void inserirProdutoEstoque(Produto produto) { if (!UtilsJapp.isNullOrZero(produto.getId())){ EstoqueDao dao = new EstoqueDao(); Estoque estoque = new Estoque(); estoque.setId(null); estoque.setProduto(produto); estoque.setQuantidade(0d); estoque.setStatus("1"); estoque.setDatacontagem(new Date()); dao.add(estoque); } } @Override public void inserirMovimentacaoEstoque(EstoqueMovimento movimentoEstoque) { MovimentoEstoqueDao dao = new MovimentoEstoqueDao(); } @Override public List<Estoque> buscarPosicaoEstoque(Estoque estoqueFiltro) { EstoqueDao dao = new EstoqueDao(); List<Estoque> ret = dao.getAll(); return ret; } }
true
3ffb03daf6c0c1b1d582ebca84b0ef9903ae02c6
Java
shariqmuhammad10/Automation
/POC/src/test/java/com/aptafund/test/features/login/PurchasingAndPayables/PurchaseRequisitionTest.java
UTF-8
46,904
1.65625
2
[]
no_license
package com.aptafund.test.features.login.PurchasingAndPayables; import com.aptafund.test.steps.HRPayrollESS.HRManagePayrollHomeSteps; import com.aptafund.test.steps.HRPayrollESS.ManagePayrollSteps; import com.aptafund.test.steps.MyAptaFund.MyAptaFundHomeSteps; import com.aptafund.test.steps.MyAptaFund.MyPRApprovalSteps; import com.aptafund.test.steps.PurchasingAndPayables.PurchaseRequisitionSteps; import com.aptafund.test.steps.PurchasingAndPayables.PurchasingAndPayableSteps; import com.aptafund.test.steps.commonSteps.AptaLoginSteps; import net.serenitybdd.junit.runners.SerenityRunner; import net.thucydides.core.annotations.Managed; import net.thucydides.core.annotations.Steps; import net.thucydides.core.annotations.WithTag; import net.thucydides.core.annotations.WithTags; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(SerenityRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class PurchaseRequisitionTest { private static final Logger Logger = LoggerFactory.getLogger(PurchaseRequisitionTest.class); @Managed WebDriver driver; @Steps AptaLoginSteps aptaLoginSteps; @Steps HRManagePayrollHomeSteps hrManagePayrollHomeSteps; @Steps ManagePayrollSteps managePayrollSteps; @Steps PurchasingAndPayableSteps purchasingAndPayableSteps; @Steps PurchaseRequisitionSteps purchaseRequisitionSteps; @Steps MyPRApprovalSteps myPRApprovalSteps; @Steps MyAptaFundHomeSteps myAptaFundHomeSteps; @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void verifyNavigateToPurchaseRequisition() { Logger.info ("<----------------------------------------------------->"); Logger.info ("<-- Verify Navigate to Purchase Requisition Link ----->"); Logger.info ("<----------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void addPurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<-- Add New Purchase Requisition -------------------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void addItemLineInPurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<------ Add New Item Line Purchase Requisition ------>"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void attachFileInPurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<------ Attach file in Purchase Requisition --------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.clickOnAttachedTab(); purchaseRequisitionSteps.clickOnAttachfileAdd(); purchaseRequisitionSteps.clickSelectFileToAttach(); purchaseRequisitionSteps.defineDescriptionInAttachedFiles(); purchaseRequisitionSteps.clickOnSaveButtonAfterAttachingFile(); purchaseRequisitionSteps.selectTheFileToAttach(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void addMultipleItemLineInPurchaseRequisition() { Logger.info ("<------------------------------------------------------>"); Logger.info ("<-- Add Multiple New Line Item Purchase Requisition --->"); Logger.info ("<------------------------------------------------------>"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.addMultipleLineitem(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void submitMultipleItemLineInPurchaseRequisition() { Logger.info ("<------------------------------------------------------>"); Logger.info ("<-- Submit Multiple Line Item Purchase Requisition ---->"); Logger.info ("<------------------------------------------------------>"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.addMultipleLineitem(); //purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.selectAllItemLineCheckbox(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void deleteItemLineInPurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<--- Delete Item Line Purchase Requisition ---------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.selectItemLineCheckBox(); purchaseRequisitionSteps.deletePRLineItem(); purchaseRequisitionSteps.confirmDeleteLI(); //purchaseRequisitionSteps.confirmSubmit(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void editItemLineInPurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<----- Edit Item Line Purchase Requisition ---------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.addPRTerms(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.selectItemLineCheckBox(); purchaseRequisitionSteps.editItemLine(); purchaseRequisitionSteps.updateItemDescription(); purchaseRequisitionSteps.savePRItemLine(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void cancelPurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<------------ Cancel Purchase Requisition ----------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsMyAdminReq1(); purchasingAndPayableSteps.navigateToPurchaseAndPayableForMyPRAdmin(); purchaseRequisitionSteps.navigateToPurchaseRequisitionForMyPRAdmin(); purchaseRequisitionSteps.addPurchaseRequisitonForMyPRAdmin(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.addReqNumInTerms(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePurchaseRequisitionPopup(); purchaseRequisitionSteps.searchNewlyCreatedPRForPRAdmin(); purchaseRequisitionSteps.applyCheckForSearch(); purchaseRequisitionSteps.clickOnMoreButton(); purchaseRequisitionSteps.cancelSubmittedPR(); purchaseRequisitionSteps.confirmCancelSubmit(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void submitPurchaseRequisition() { Logger.info("<---------------------------------------------------->"); Logger.info("<-- Submit Purchase Requisition --------------------->"); Logger.info("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); //purchaseRequisitionSteps.navigateToPurchaseRequisitionForReq(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePRPopUp(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void submitOverBudgetPurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<-- Submit Over Budget Purchase Requisition --------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendorForOb(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setOverBudgetAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.confirmOverBudget(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void addPurchaseRequisitionUsingDollarPRType() { Logger.info ("<----------------------------------------------------->"); Logger.info ("<-- Add New Purchase Requisition using Dollar PR Type->"); Logger.info ("<----------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addPRDollarPRtype(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.savePurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void editMyPurchaseRequisitionUsingDollarPRType() { Logger.info ("<-------------------------------------------------------->"); Logger.info ("<-- Edit New Purchase Requisition using Dollar PR Type -->"); Logger.info ("<-------------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addPRDollarPRtype(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.addReqNumInTerms(); purchaseRequisitionSteps.savePurchaseRequisition(); //purchaseRequisitionSteps.closePurchaseRequisitionPopup(); purchaseRequisitionSteps.searchNewlyCreatedPR(); purchaseRequisitionSteps.applyCheckForSearch(); purchaseRequisitionSteps.clickEditButton(); purchaseRequisitionSteps.addPRTerms(); purchaseRequisitionSteps.savePurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void deleteMyPurchaseRequisitionUsingDollarPRType() { aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addPRDollarPRtype(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.addReqNumInTerms(); purchaseRequisitionSteps.savePurchaseRequisition(); //purchaseRequisitionSteps.closePurchaseRequisitionPopup(); purchaseRequisitionSteps.searchNewlyCreatedPR(); purchaseRequisitionSteps.applyCheckForSearch(); purchaseRequisitionSteps.deletePurchaseRequisition(); purchaseRequisitionSteps.deletePRConfirmMessage(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void withdrawMyPurchaseRequisition() { aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); //purchaseRequisitionSteps.navigateToPurchaseRequisitionForReq(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); //purchaseRequisitionSteps.closePRPopUp(); //purchaseRequisitionSteps.searchSubmittedRecordsOnly(); //purchaseRequisitionSteps.searchNewlyCreatedPR(); //purchaseRequisitionSteps.sortRequestNo(); //purchaseRequisitionSteps.applyCheckForSearch(); purchaseRequisitionSteps.withdrawPurchaseRequisition(); purchaseRequisitionSteps.withdrawPRConfirmMessage(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void withdrawMyPurchaseRequisitionFromGrid() { aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.addReqNumInTerms(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePRPopUp(); purchaseRequisitionSteps.searchSubmittedRecordsOnly(); //purchaseRequisitionSteps.sortRequestNo(); purchaseRequisitionSteps.applyCheckForSearch(); purchaseRequisitionSteps.withdrawPurchaseRequisitionOutGrid(); purchaseRequisitionSteps.withdrawPRConfirmMessage(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void withdrawMyPurchaseRequisitionFromGrid1() { aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); //purchaseRequisitionSteps.addReqNumInTerms(); //purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.addReqNumInTerms(); //purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); //purchaseRequisitionSteps.savePurchaseRequisition(); //purchaseRequisitionSteps.closePRPopUp(); //purchaseRequisitionSteps.searchSubmittedRecordsOnly(); //purchaseRequisitionSteps.sortRequestNo(); //purchaseRequisitionSteps.applyCheckForSearch(); purchaseRequisitionSteps.withdrawPurchaseRequisition(); purchaseRequisitionSteps.withdrawPRConfirmMessage(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void copyMyPurchaseRequisition() { aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); //purchaseRequisitionSteps.navigateToPurchaseRequisitionForReq(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.copyPurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), } ) public void printMyPurchaseRequisition() { aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.printPurchaseRequisition(); purchaseRequisitionSteps.okPrintPurchaseRequisition(); purchaseRequisitionSteps.successMessage(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void approveLevel1PurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<-- Approval for Level 1 Purchase Requisition ------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePRPopUp(); aptaLoginSteps.logoutApplication(); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsApprover1(); myAptaFundHomeSteps.navigateToMyAptaFundForApp1(); myPRApprovalSteps.navigateToMyPRApprovals(); purchaseRequisitionSteps.searchNewlyCreatedPRForApp1(); purchaseRequisitionSteps.applyCheckForSearchForApp1(); purchaseRequisitionSteps.clickApproveUsingApp1(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void disapprovePurchaseRequisition() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<----------- Disapprove Purchase Requisition ------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePRPopUp(); aptaLoginSteps.logoutApplication(); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsApprover1(); myAptaFundHomeSteps.navigateToMyAptaFundForApp1(); myPRApprovalSteps.navigateToMyPRApprovals(); purchaseRequisitionSteps.searchNewlyCreatedPRForApp1(); purchaseRequisitionSteps.applyCheckForSearchForApp1(); purchaseRequisitionSteps.clickDisapproveUsingApp1(); purchaseRequisitionSteps.provideDisapproveComments(); purchaseRequisitionSteps.clickOkButtonAfterComments(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void resubmitAfterDisapprovePurchaseRequisition() { Logger.info ("<------------------------------------------------------------------->"); Logger.info ("<----------- Resubmit After Disapprove Purchase Requisition ------->"); Logger.info ("<------------------------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePRPopUp(); aptaLoginSteps.logoutApplication(); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsApprover1(); myAptaFundHomeSteps.navigateToMyAptaFundForApp1(); myPRApprovalSteps.navigateToMyPRApprovals(); purchaseRequisitionSteps.searchNewlyCreatedPRForApp1(); purchaseRequisitionSteps.applyCheckForSearchForApp1(); purchaseRequisitionSteps.clickDisapproveUsingApp1(); purchaseRequisitionSteps.provideDisapproveComments(); purchaseRequisitionSteps.clickOkButtonAfterComments(); aptaLoginSteps.logoutApplication(); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.searchNewlyCreatedPR(); purchaseRequisitionSteps.applyCheckForSearch(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void appL2AfterAppL1PurchaseRequisition() { Logger.info ("<--------------------------------------------------------------------------->"); Logger.info ("<-- Approval for Level 2 after Approval Level 1 Purchase Requisition ------->"); Logger.info ("<--------------------------------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePRPopUp(); aptaLoginSteps.logoutApplication(); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsApprover1(); myAptaFundHomeSteps.navigateToMyAptaFundForApp1(); myPRApprovalSteps.navigateToMyPRApprovals(); //purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.searchNewlyCreatedPRForApp1(); purchaseRequisitionSteps.applyCheckForSearchForApp1(); purchaseRequisitionSteps.clickApproveUsingApp1(); aptaLoginSteps.logoutApplication(); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsApprover2(); myAptaFundHomeSteps.navigateToMyAptaFundForApp2(); myPRApprovalSteps.navigateToMyPRApprovalsForApp2(); purchaseRequisitionSteps.searchNewlyCreatedPRForApp2(); purchaseRequisitionSteps.applyCheckForSearchForApp2(); purchaseRequisitionSteps.clickApproveUsingApp2(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void appL2PurchaseRequisitionWithoutLevel1Approval() { Logger.info ("<--------------------------------------------------------------------------->"); Logger.info ("<-- Approval for Level 2 Purchase Requisition without Level 1 Approval ----->"); Logger.info ("<--------------------------------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsRequisitionor(); purchasingAndPayableSteps.navigateToMyAptaFund(); purchaseRequisitionSteps.navigateToPurchaseRequisition(); purchaseRequisitionSteps.addPurchaseRequisiton(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.clickAddRequestedItem(); purchaseRequisitionSteps.setUnitPriceForLineItem(); purchaseRequisitionSteps.setAccountCode(); purchaseRequisitionSteps.setItemDescription(); purchaseRequisitionSteps.savePRItemLine(); purchaseRequisitionSteps.closeLineItemPopup(); purchaseRequisitionSteps.submitPR(); purchaseRequisitionSteps.confirmSubmit(); purchaseRequisitionSteps.closePRPopUp(); aptaLoginSteps.logoutApplication(); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsApprover2(); myAptaFundHomeSteps.navigateToMyAptaFundForApp2(); myPRApprovalSteps.navigateToMyPRApprovalsForApp2(); purchaseRequisitionSteps.searchNewlyCreatedPRForApp2(); purchaseRequisitionSteps.applyCheckForSearchForApp2(); purchaseRequisitionSteps.clickApproveUsingApp2(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void viewPurchaseRequisitionForAdmin() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<--View Purchase Requisition using Admin PR Account-->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsMyAdminReq1(); purchasingAndPayableSteps.navigateToAdminPR(); purchaseRequisitionSteps.navigateToPurchaseRequisitionForAdmin(); purchaseRequisitionSteps.addPurchaseRequisitonForMyPRAdmin(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.closePRPopUp(); purchaseRequisitionSteps.searchNewlyCreatedPRForPRAdmin(); purchaseRequisitionSteps.selectItemLineCheckBoxForAdminPR(); purchaseRequisitionSteps.viewForAdminPR(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void AddPurchaseRequisitionForAdmin() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<--------Add Purchase Requisition for Admin PR------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsMyAdminReq1(); purchasingAndPayableSteps.navigateToAdminPR(); purchaseRequisitionSteps.navigateToPurchaseRequisitionForAdmin(); purchaseRequisitionSteps.addPurchaseRequisitonForMyPRAdmin(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void editPurchaseRequisitionForAdmin() { Logger.info ("<---------------------------------------------------->"); Logger.info ("<-------Edit Purchase Requisition for Admin PR------->"); Logger.info ("<---------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsMyAdminReq1(); purchasingAndPayableSteps.navigateToAdminPR(); purchaseRequisitionSteps.navigateToPurchaseRequisitionForAdmin(); purchaseRequisitionSteps.addPurchaseRequisitonForMyPRAdmin(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.closePRPopUp(); purchaseRequisitionSteps.searchNewlyCreatedPRForPRAdmin(); purchaseRequisitionSteps.selectItemLineCheckBoxForAdminPR(); purchaseRequisitionSteps.editForAdminPR(); purchaseRequisitionSteps.updateQuoteBitNotes(); purchaseRequisitionSteps.savePurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void editAllPurchaseRequisitionForAdmin() { Logger.info ("<--------------------------------------------------------->"); Logger.info ("<--------Edit All Purchase Requisition for Admin PR------->"); Logger.info ("<--------------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsMyAdminReq1(); purchasingAndPayableSteps.navigateToAdminPR(); purchaseRequisitionSteps.navigateToPurchaseRequisitionForAdmin(); purchaseRequisitionSteps.selectAllPRRecordsToGetTotalNumberOfPRRecords(); purchaseRequisitionSteps.getTotalNumberOfPRRecords(); purchaseRequisitionSteps.selectAllPRRecordsToGetTotalNumberOfPRRecords(); purchaseRequisitionSteps.clickEditAllButton(); purchaseRequisitionSteps.getTotalNumberOfRecordsInPopUp(); purchaseRequisitionSteps.compareTotalRecordsCount(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void editPurchaseRequisitionForAdminUsingHyperLink() { Logger.info ("<--------------------------------------------------------------------->"); Logger.info ("<--------Edit Purchase Requisition for Admin PR using Hyperlink------->"); Logger.info ("<--------------------------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsMyAdminReq1(); purchasingAndPayableSteps.navigateToAdminPR(); purchaseRequisitionSteps.navigateToPurchaseRequisitionForAdmin(); purchaseRequisitionSteps.addPurchaseRequisitonForMyPRAdmin(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.closePRPopUp(); purchaseRequisitionSteps.searchNewlyCreatedPRForPRAdmin(); purchaseRequisitionSteps.clickOnHyperLinkToEdit(); //purchaseRequisitionSteps.editForAdminPR(); purchaseRequisitionSteps.updateQuoteBitNotesThroughHyperLink(); purchaseRequisitionSteps.savePurchaseRequisition(); } @Test @WithTags( {@WithTag(type = "release", name = "Regression Level 2"), @WithTag("Priority:High") } ) public void deletePurchaseRequisitionForAdminUsingHyperLink() { Logger.info ("<--------------------------------------------------------------------->"); Logger.info ("<----------- Delete Purchase Requisition for Admin PR ---------------->"); Logger.info ("<--------------------------------------------------------------------->"); aptaLoginSteps.navigateToLoginPage(); aptaLoginSteps.loginIntoAptaAsMyAdminReq1(); purchasingAndPayableSteps.navigateToAdminPR(); purchaseRequisitionSteps.navigateToPurchaseRequisitionForAdmin(); purchaseRequisitionSteps.addPurchaseRequisitonForMyPRAdmin(); purchaseRequisitionSteps.addSuggestedOrderingVendor(); purchaseRequisitionSteps.addComments(); purchaseRequisitionSteps.savePurchaseRequisition(); purchaseRequisitionSteps.getRequisitionNumberValue(); purchaseRequisitionSteps.closePRPopUp(); purchaseRequisitionSteps.searchNewlyCreatedPRForPRAdmin(); purchaseRequisitionSteps.selectItemLineCheckBoxForAdminPR(); purchaseRequisitionSteps.deletePRusingAdmin(); } }
true
3dcaaf7d973b8d734e40ac49bd80933956bdcef8
Java
suggitpe/java-sandbox
/patterns/src/main/java/org/suggs/sandbox/patterns/structural/decorator/beveragedecorator/Mocha.java
UTF-8
639
2.78125
3
[ "Apache-2.0" ]
permissive
/* * Mocha.java created on 29 Aug 2007 05:57:02 by suggitpe for project SandBox - Patterns * */ package org.suggs.sandbox.patterns.structural.decorator.beveragedecorator; import org.suggs.sandbox.patterns.structural.decorator.IBeverage; /** * Mocha decorator */ public class Mocha extends AbstractCondimentDecorator { public Mocha(IBeverage aBeverage) { super(aBeverage); } @Override public String getDescription() { return getBeverage().getDescription() + ", Mocha"; } @Override public double cost() { return 0.2d + getBeverage().cost(); } }
true
15486ff92efd2b436d6023adb5c58da2fac0a0a0
Java
Deepanshuchauhan123/Question-Answer-Platform-API
/src/main/java/io/java/questionanswerapi/repository/CompanyRepository.java
UTF-8
235
1.539063
2
[]
no_license
package io.java.questionanswerapi.repository; import org.springframework.data.repository.CrudRepository; import io.java.questionanswerapi.dto.Company; public interface CompanyRepository extends CrudRepository<Company, Integer> { }
true
667f5711de7d5c5fa8b6cc8d9131a7e24356a30b
Java
P79N6A/whatever
/sofa/src/main/java/com/alipay/remoting/DefaultConnectionManager.java
UTF-8
23,163
2.03125
2
[]
no_license
package com.alipay.remoting; import com.alipay.remoting.config.ConfigManager; import com.alipay.remoting.config.switches.GlobalSwitch; import com.alipay.remoting.connection.ConnectionFactory; import com.alipay.remoting.constant.Constants; import com.alipay.remoting.exception.RemotingException; import com.alipay.remoting.log.BoltLoggerFactory; import com.alipay.remoting.util.FutureTaskUtil; import com.alipay.remoting.util.RunStateRecordedFutureTask; import com.alipay.remoting.util.StringUtils; import org.slf4j.Logger; import java.util.*; import java.util.concurrent.*; public class DefaultConnectionManager extends AbstractLifeCycle implements ConnectionManager, ConnectionHeartbeatManager, Scannable, LifeCycle { private static final Logger logger = BoltLoggerFactory.getLogger("CommonDefault"); private ThreadPoolExecutor asyncCreateConnectionExecutor; private GlobalSwitch globalSwitch; protected ConcurrentHashMap<String, RunStateRecordedFutureTask<ConnectionPool>> connTasks; protected ConcurrentHashMap<String, FutureTask<Integer>> healTasks; protected ConnectionSelectStrategy connectionSelectStrategy; protected RemotingAddressParser addressParser; protected ConnectionFactory connectionFactory; protected ConnectionEventHandler connectionEventHandler; protected ConnectionEventListener connectionEventListener; public DefaultConnectionManager() { this.connTasks = new ConcurrentHashMap<>(); this.healTasks = new ConcurrentHashMap<String, FutureTask<Integer>>(); this.connectionSelectStrategy = new RandomSelectStrategy(globalSwitch); } public DefaultConnectionManager(ConnectionSelectStrategy connectionSelectStrategy) { this(); this.connectionSelectStrategy = connectionSelectStrategy; } public DefaultConnectionManager(ConnectionSelectStrategy connectionSelectStrategy, ConnectionFactory connectionFactory) { this(connectionSelectStrategy); this.connectionFactory = connectionFactory; } public DefaultConnectionManager(ConnectionFactory connectionFactory, RemotingAddressParser addressParser, ConnectionEventHandler connectionEventHandler) { this(new RandomSelectStrategy(null), connectionFactory); this.addressParser = addressParser; this.connectionEventHandler = connectionEventHandler; } public DefaultConnectionManager(ConnectionSelectStrategy connectionSelectStrategy, ConnectionFactory connectionFactory, ConnectionEventHandler connectionEventHandler, ConnectionEventListener connectionEventListener) { this(connectionSelectStrategy, connectionFactory); this.connectionEventHandler = connectionEventHandler; this.connectionEventListener = connectionEventListener; } public DefaultConnectionManager(ConnectionSelectStrategy connectionSelectStrategy, ConnectionFactory connectionFactory, ConnectionEventHandler connectionEventHandler, ConnectionEventListener connectionEventListener, GlobalSwitch globalSwitch) { this(connectionSelectStrategy, connectionFactory, connectionEventHandler, connectionEventListener); this.globalSwitch = globalSwitch; } @Override public void startup() throws LifeCycleException { super.startup(); long keepAliveTime = ConfigManager.conn_create_tp_keepalive(); int queueSize = ConfigManager.conn_create_tp_queue_size(); int minPoolSize = ConfigManager.conn_create_tp_min_size(); int maxPoolSize = ConfigManager.conn_create_tp_max_size(); this.asyncCreateConnectionExecutor = new ThreadPoolExecutor(minPoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize), new NamedThreadFactory("Bolt-conn-warmup-executor", true)); } @Override public void shutdown() throws LifeCycleException { super.shutdown(); if (asyncCreateConnectionExecutor != null) { asyncCreateConnectionExecutor.shutdown(); } if (null == this.connTasks || this.connTasks.isEmpty()) { return; } Iterator<String> iter = this.connTasks.keySet().iterator(); while (iter.hasNext()) { String poolKey = iter.next(); this.removeTask(poolKey); iter.remove(); } logger.warn("All connection pool and connections have been removed!"); } @Deprecated @Override public void init() { this.connectionEventHandler.setConnectionManager(this); this.connectionEventHandler.setConnectionEventListener(connectionEventListener); // 初始化 this.connectionFactory.init(connectionEventHandler); } @Override public void add(Connection connection) { Set<String> poolKeys = connection.getPoolKeys(); for (String poolKey : poolKeys) { this.add(connection, poolKey); } } @Override public void add(Connection connection, String poolKey) { ConnectionPool pool = null; try { pool = this.getConnectionPoolAndCreateIfAbsent(poolKey, new ConnectionPoolCall()); } catch (Exception e) { logger.error("[NOTIFYME] Exception occurred when getOrCreateIfAbsent an empty ConnectionPool!", e); } if (pool != null) { pool.add(connection); } else { logger.error("[NOTIFYME] Connection pool NULL!"); } } @Override public Connection get(String poolKey) { ConnectionPool pool = this.getConnectionPool(this.connTasks.get(poolKey)); return null == pool ? null : pool.get(); } @Override public List<Connection> getAll(String poolKey) { ConnectionPool pool = this.getConnectionPool(this.connTasks.get(poolKey)); return null == pool ? new ArrayList<Connection>() : pool.getAll(); } @Override public Map<String, List<Connection>> getAll() { Map<String, List<Connection>> allConnections = new HashMap<String, List<Connection>>(); Iterator<Map.Entry<String, RunStateRecordedFutureTask<ConnectionPool>>> iterator = this.getConnPools().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, RunStateRecordedFutureTask<ConnectionPool>> entry = iterator.next(); ConnectionPool pool = FutureTaskUtil.getFutureTaskResult(entry.getValue(), logger); if (null != pool) { allConnections.put(entry.getKey(), pool.getAll()); } } return allConnections; } @Override public void remove(Connection connection) { if (null == connection) { return; } Set<String> poolKeys = connection.getPoolKeys(); if (null == poolKeys || poolKeys.isEmpty()) { connection.close(); logger.warn("Remove and close a standalone connection."); } else { for (String poolKey : poolKeys) { this.remove(connection, poolKey); } } } @Override public void remove(Connection connection, String poolKey) { if (null == connection || StringUtils.isBlank(poolKey)) { return; } ConnectionPool pool = this.getConnectionPool(this.connTasks.get(poolKey)); if (null == pool) { connection.close(); logger.warn("Remove and close a standalone connection."); } else { pool.removeAndTryClose(connection); if (pool.isEmpty()) { this.removeTask(poolKey); logger.warn("Remove and close the last connection in ConnectionPool with poolKey {}", poolKey); } else { logger.warn("Remove and close a connection in ConnectionPool with poolKey {}, {} connections left.", poolKey, pool.size()); } } } @Override public void remove(String poolKey) { if (StringUtils.isBlank(poolKey)) { return; } RunStateRecordedFutureTask<ConnectionPool> task = this.connTasks.remove(poolKey); if (null != task) { ConnectionPool pool = this.getConnectionPool(task); if (null != pool) { pool.removeAllAndTryClose(); logger.warn("Remove and close all connections in ConnectionPool of poolKey={}", poolKey); } } } @Deprecated @Override public void removeAll() { if (null == this.connTasks || this.connTasks.isEmpty()) { return; } Iterator<String> iter = this.connTasks.keySet().iterator(); while (iter.hasNext()) { String poolKey = iter.next(); this.removeTask(poolKey); iter.remove(); } logger.warn("All connection pool and connections have been removed!"); } @Override public void check(Connection connection) throws RemotingException { if (connection == null) { throw new RemotingException("Connection is null when do check!"); } if (connection.getChannel() == null || !connection.getChannel().isActive()) { this.remove(connection); throw new RemotingException("Check connection failed for address: " + connection.getUrl()); } if (!connection.getChannel().isWritable()) { throw new RemotingException("Check connection failed for address: " + connection.getUrl() + ", maybe write overflow!"); } } @Override public int count(String poolKey) { if (StringUtils.isBlank(poolKey)) { return 0; } ConnectionPool pool = this.getConnectionPool(this.connTasks.get(poolKey)); if (null != pool) { return pool.size(); } else { return 0; } } @Override public void scan() { if (null != this.connTasks && !this.connTasks.isEmpty()) { Iterator<String> iter = this.connTasks.keySet().iterator(); while (iter.hasNext()) { String poolKey = iter.next(); ConnectionPool pool = this.getConnectionPool(this.connTasks.get(poolKey)); if (null != pool) { pool.scan(); if (pool.isEmpty()) { if ((System.currentTimeMillis() - pool.getLastAccessTimestamp()) > Constants.DEFAULT_EXPIRE_TIME) { iter.remove(); logger.warn("Remove expired pool task of poolKey {} which is empty.", poolKey); } } } } } } @Override public Connection getAndCreateIfAbsent(Url url) throws InterruptedException, RemotingException { // 获取连接池 ConnectionPool pool = this.getConnectionPoolAndCreateIfAbsent(url.getUniqueKey(), // Callable任务,获取连接池 new ConnectionPoolCall(url)); if (null != pool) { // 从连接池获取连接 return pool.get(); } else { logger.error("[NOTIFYME] bug detected! pool here must not be null!"); return null; } } @Override public void createConnectionAndHealIfNeed(Url url) throws InterruptedException, RemotingException { ConnectionPool pool = this.getConnectionPoolAndCreateIfAbsent(url.getUniqueKey(), new ConnectionPoolCall(url)); if (null != pool) { healIfNeed(pool, url); } else { logger.error("[NOTIFYME] bug detected! pool here must not be null!"); } } @Override public Connection create(Url url) throws RemotingException { Connection conn; try { // 连接工厂创建 conn = this.connectionFactory.createConnection(url); } catch (Exception e) { throw new RemotingException("Create connection failed. The address is " + url.getOriginUrl(), e); } return conn; } @Override public Connection create(String ip, int port, int connectTimeout) throws RemotingException { try { return this.connectionFactory.createConnection(ip, port, connectTimeout); } catch (Exception e) { throw new RemotingException("Create connection failed. The address is " + ip + ":" + port, e); } } @Override public Connection create(String address, int connectTimeout) throws RemotingException { Url url = this.addressParser.parse(address); url.setConnectTimeout(connectTimeout); return create(url); } @Override public void disableHeartbeat(Connection connection) { if (null != connection) { connection.getChannel().attr(Connection.HEARTBEAT_SWITCH).set(false); } } @Override public void enableHeartbeat(Connection connection) { if (null != connection) { connection.getChannel().attr(Connection.HEARTBEAT_SWITCH).set(true); } } private ConnectionPool getConnectionPool(RunStateRecordedFutureTask<ConnectionPool> task) { return FutureTaskUtil.getFutureTaskResult(task, logger); } /** * 获取连接池 */ private ConnectionPool getConnectionPoolAndCreateIfAbsent(String poolKey, Callable<ConnectionPool> callable) throws RemotingException, InterruptedException { // RunStateRecordedFutureTask<ConnectionPool> initialTask; // 连接池 ConnectionPool pool = null; // 重试次数 int retry = Constants.DEFAULT_RETRY_TIMES; int timesOfResultNull = 0; int timesOfInterrupt = 0; // 重试 for (int i = 0; (i < retry) && (pool == null); ++i) { // 每个key一个任务 initialTask = this.connTasks.get(poolKey); if (null == initialTask) { // 没有就创建 RunStateRecordedFutureTask<ConnectionPool> newTask = new RunStateRecordedFutureTask<ConnectionPool>(callable); initialTask = this.connTasks.putIfAbsent(poolKey, newTask); if (null == initialTask) { initialTask = newTask; // 执行Callable任务 initialTask.run(); } } try { // 阻塞获取连接池 pool = initialTask.get(); if (null == pool) { if (i + 1 < retry) { timesOfResultNull++; continue; } this.connTasks.remove(poolKey); String errMsg = "Get future task result null for poolKey [" + poolKey + "] after [" + (timesOfResultNull + 1) + "] times try."; throw new RemotingException(errMsg); } } catch (InterruptedException e) { if (i + 1 < retry) { timesOfInterrupt++; continue; } this.connTasks.remove(poolKey); logger.warn("Future task of poolKey {} interrupted {} times. InterruptedException thrown and stop retry.", poolKey, (timesOfInterrupt + 1), e); throw e; } catch (ExecutionException e) { this.connTasks.remove(poolKey); Throwable cause = e.getCause(); if (cause instanceof RemotingException) { throw (RemotingException) cause; } else { FutureTaskUtil.launderThrowable(cause); } } } return pool; } protected void removeTask(String poolKey) { RunStateRecordedFutureTask<ConnectionPool> task = this.connTasks.remove(poolKey); if (null != task) { ConnectionPool pool = FutureTaskUtil.getFutureTaskResult(task, logger); if (null != pool) { pool.removeAllAndTryClose(); } } } private void healIfNeed(ConnectionPool pool, Url url) throws RemotingException, InterruptedException { String poolKey = url.getUniqueKey(); if (pool.isAsyncCreationDone() && pool.size() < url.getConnNum()) { FutureTask<Integer> task = this.healTasks.get(poolKey); if (null == task) { FutureTask<Integer> newTask = new FutureTask<Integer>(new HealConnectionCall(url, pool)); task = this.healTasks.putIfAbsent(poolKey, newTask); if (null == task) { task = newTask; task.run(); } } try { int numAfterHeal = task.get(); if (logger.isDebugEnabled()) { logger.debug("[NOTIFYME] - conn num after heal {}, expected {}, warmup {}", numAfterHeal, url.getConnNum(), url.isConnWarmup()); } } catch (InterruptedException e) { this.healTasks.remove(poolKey); throw e; } catch (ExecutionException e) { this.healTasks.remove(poolKey); Throwable cause = e.getCause(); if (cause instanceof RemotingException) { throw (RemotingException) cause; } else { FutureTaskUtil.launderThrowable(cause); } } this.healTasks.remove(poolKey); } } /** * 包装获取连接池的操作 */ private class ConnectionPoolCall implements Callable<ConnectionPool> { private boolean whetherInitConnection; private Url url; public ConnectionPoolCall() { this.whetherInitConnection = false; } public ConnectionPoolCall(Url url) { this.whetherInitConnection = true; this.url = url; } @Override public ConnectionPool call() throws Exception { final ConnectionPool pool = new ConnectionPool(connectionSelectStrategy); if (whetherInitConnection) { try { doCreate(this.url, pool, this.getClass().getSimpleName(), 1); } catch (Exception e) { pool.removeAllAndTryClose(); throw e; } } return pool; } } private class HealConnectionCall implements Callable<Integer> { private Url url; private ConnectionPool pool; public HealConnectionCall(Url url, ConnectionPool pool) { this.url = url; this.pool = pool; } @Override public Integer call() throws Exception { doCreate(this.url, this.pool, this.getClass().getSimpleName(), 0); return this.pool.size(); } } private void doCreate(final Url url, final ConnectionPool pool, final String taskName, final int syncCreateNumWhenNotWarmup) throws RemotingException { // 现存连接数 final int actualNum = pool.size(); // 期望连接数 final int expectNum = url.getConnNum(); if (actualNum >= expectNum) { return; } if (logger.isDebugEnabled()) { logger.debug("actual num {}, expect num {}, task name {}", actualNum, expectNum, taskName); } // 连接热身 if (url.isConnWarmup()) { for (int i = actualNum; i < expectNum; ++i) { // 马上创建连接 Connection connection = create(url); pool.add(connection); } } // 异步创建 else { if (syncCreateNumWhenNotWarmup < 0 || syncCreateNumWhenNotWarmup > url.getConnNum()) { throw new IllegalArgumentException("sync create number when not warmup should be [0," + url.getConnNum() + "]"); } if (syncCreateNumWhenNotWarmup > 0) { for (int i = 0; i < syncCreateNumWhenNotWarmup; ++i) { // 先创建需要同步创建的 Connection connection = create(url); pool.add(connection); } // 够了 if (syncCreateNumWhenNotWarmup >= url.getConnNum()) { return; } } // 标记异步创建开始 pool.markAsyncCreationStart(); try { // 线程池执行 this.asyncCreateConnectionExecutor.execute(new Runnable() { @Override public void run() { try { for (int i = pool.size(); i < url.getConnNum(); ++i) { Connection conn = null; try { conn = create(url); } catch (RemotingException e) { logger.error("Exception occurred in async create connection thread for {}, taskName {}", url.getUniqueKey(), taskName, e); } pool.add(conn); } } finally { // 标记异步创建结束 pool.markAsyncCreationDone(); } } }); } catch (RejectedExecutionException e) { pool.markAsyncCreationDone(); throw e; } } } public ConnectionSelectStrategy getConnectionSelectStrategy() { return connectionSelectStrategy; } public void setConnectionSelectStrategy(ConnectionSelectStrategy connectionSelectStrategy) { this.connectionSelectStrategy = connectionSelectStrategy; } public RemotingAddressParser getAddressParser() { return addressParser; } public void setAddressParser(RemotingAddressParser addressParser) { this.addressParser = addressParser; } public ConnectionFactory getConnectionFactory() { return connectionFactory; } public void setConnectionFactory(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public ConnectionEventHandler getConnectionEventHandler() { return connectionEventHandler; } public void setConnectionEventHandler(ConnectionEventHandler connectionEventHandler) { this.connectionEventHandler = connectionEventHandler; } public ConnectionEventListener getConnectionEventListener() { return connectionEventListener; } public void setConnectionEventListener(ConnectionEventListener connectionEventListener) { this.connectionEventListener = connectionEventListener; } public ConcurrentHashMap<String, RunStateRecordedFutureTask<ConnectionPool>> getConnPools() { return this.connTasks; } }
true
22c41cf53c204b2bc24720de87ab30e656614022
Java
soumay10495/chadDarby-spring-xmlConfigurationDemo
/src/main/java/com/spring/xmlConfigurationDemo/HappyFortuneService.java
UTF-8
767
3.125
3
[]
no_license
package com.spring.xmlConfigurationDemo; import java.util.ArrayList; import java.util.Random; public class HappyFortuneService implements FortuneService { private ArrayList<String> fortuneList; public HappyFortuneService() { System.out.println("Inside HappyFortuneService constructor"); fortuneList = new ArrayList<>(); fortuneList.add("Today is your lucky day"); fortuneList.add("Today is going to be difficult for you"); fortuneList.add("Today will be a new experience for you"); fortuneList.add("Today you will learn a lot"); } @Override public String getFortune() { Random random = new Random(); int index = random.nextInt(4); return fortuneList.get(index); } }
true
fea8980497056cbf92f9c237a80fd9770786b519
Java
plotor/algorithm
/src/main/java/org/zhenchao/algorithm/oj/leetcode/medium/UniquePathsII.java
UTF-8
1,564
3.625
4
[]
no_license
package org.zhenchao.algorithm.oj.leetcode.medium; /** * No.63 Unique Paths II * * @author zhenchao.wang 2017-06-04 15:36 * @version 1.0.0 */ public class UniquePathsII { /** * 思路同UniquePaths,只是遇到障碍时,需要将对应的值设为0 * * @param obstacleGrid * @return */ public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] dp = new int[m][n]; int num = 1 - obstacleGrid[0][0]; for (int i = 0; i < m; i++) { // 如果只有一列,有障碍就到达不到终点,所以障碍之后的值都是0 num = 0 == num ? 0 : 1 - obstacleGrid[i][0]; dp[i][0] = num; } num = 1 - obstacleGrid[0][0]; for (int i = 0; i < n; i++) { // 如果只有一行,有障碍就到达不到终点,所以障碍之后的值都是0 num = 0 == num ? 0 : 1 - obstacleGrid[0][i]; dp[0][i] = num; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { // 障碍的位置置为0,其余与UniquePaths计算方式相同 dp[i][j] = 1 == obstacleGrid[i][j] ? 0 : dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; } public static void main(String[] args) { UniquePathsII up = new UniquePathsII(); int[][] obstacleGrid = {{0}}; System.out.println(up.uniquePathsWithObstacles(obstacleGrid)); } }
true
155af4f28b387724950defce32c0faeb5d8fcb46
Java
moutainhigh/vn
/services/hfepay-scancode/trunk/hfepay-scancode/hfepay-scancode-service-impl/src/main/java/com/hfepay/scancode/service/channel/impl/ChannelRoleServiceImpl.java
UTF-8
6,314
1.9375
2
[]
no_license
package com.hfepay.scancode.service.channel.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.hfepay.commons.base.lang.Strings; import com.hfepay.commons.criteria.Cnd; import com.hfepay.commons.criteria.Criteria; import com.hfepay.commons.criteria.CriteriaBuilder; import com.hfepay.commons.criteria.Order; import com.hfepay.commons.utils.PagingResult; import com.hfepay.scancode.commons.condition.ChannelRoleCondition; import com.hfepay.scancode.commons.dao.channel.ChannelRoleDAO; import com.hfepay.scancode.commons.dao.channel.ChannelRoleResourceDAO; import com.hfepay.scancode.commons.entity.ChannelRole; import com.hfepay.scancode.commons.entity.ChannelRoleResource; import com.hfepay.scancode.service.channel.ChannelRoleService; import com.hfepay.scancode.service.commons.ScanCodeConstants; @Service("channelRoleService") public class ChannelRoleServiceImpl implements ChannelRoleService { @Autowired private ChannelRoleDAO channelRoleDao; @Autowired private ChannelRoleResourceDAO channelRoleResourceDAO; /** * 角色列表 */ @Override public PagingResult<ChannelRole> findAll(ChannelRoleCondition condition) { CriteriaBuilder cb = Cnd.builder(ChannelRole.class); if(!Strings.isEmpty(condition.getDescription())){ cb.andLike("description", condition.getDescription()); } if(!Strings.isEmpty(condition.getRoleName())){ cb.andLike("roleName", condition.getRoleName()); } if(!Strings.isEmpty(condition.getChannelName())){ cb.andEQ("channelName", condition.getChannelName()); } if(!Strings.isEmpty(condition.getChannelCode())){ cb.andEQ("channelCode", condition.getChannelCode()); } cb.orderBy("createTime", Order.DESC); Criteria buildCriteria = cb.buildCriteria(); buildCriteria.limit(Long.valueOf(condition.getFirst()), Long.valueOf(condition.getLast())); return channelRoleDao.findPagingResult(buildCriteria); } /** * 角色列表 */ @Override public List<ChannelRole> findAllNoPage(ChannelRoleCondition condition) { CriteriaBuilder cb = Cnd.builder(ChannelRole.class); if(!Strings.isEmpty(condition.getDescription())){ cb.andLike("description", condition.getDescription()); } if(!Strings.isEmpty(condition.getRoleLevel())){ cb.andEQ("roleLevel", condition.getRoleLevel()); } List<String> list = new ArrayList<String>(); list.add(ScanCodeConstants.ROLE_TYPE_CHANNEL); list.add(ScanCodeConstants.ROLE_TYPE_AGENT); list.add(ScanCodeConstants.ROLE_TYPE_MERCHANT); if(!Strings.isEmpty(condition.getChannelCode())){ list.add(condition.getChannelCode()); } cb.andIn("channelCode", list); cb.orderBy("createTime", Order.DESC); Criteria buildCriteria = cb.buildCriteria(); return channelRoleDao.findByCriteria(buildCriteria); } /** * 修改权限 */ @Override @Transactional public String saveRoles(String ids, String roleId) { try { deleteChannelRoleResourceByRoleId(roleId);//roleResourceMapper.deleteByRoleId(roleId); List<ChannelRoleResource> list = new ArrayList<>(); String[] idArray = ids.split(","); for (String id : idArray) { ChannelRoleResource r = new ChannelRoleResource(); r.setId(Strings.getUUID());//id由java类生成 r.setResourceId(id); r.setRoleId(roleId); r.setCreateTime(new Date()); list.add(r); } channelRoleResourceDAO.insert(list); } catch (Exception e) { return ""; } return "success"; } /** * 新增 * @param ChannelRoleCondition * * @author panq * @date CreateDate : 2016-06-06 10:35:30 */ @Override public long saveRole(ChannelRoleCondition condition) { ChannelRole role = new ChannelRole(); BeanUtils.copyProperties(condition,role); return channelRoleDao.insert(role); } /** * 根据角色ID查询角色信息 */ @Override public ChannelRole findRoleById(String id) { // TODO Auto-generated method stub return channelRoleDao.get(id); } /** * 删除角色同时删除角色之源关系 */ @Override public long deleteRole(String roleId) { // TODO Auto-generated method stub long result = channelRoleDao.deleteById(roleId);//删除角色 if(result>0){ deleteChannelRoleResourceByRoleId(roleId);//删除角色资源关系 }else{ throw new RuntimeException("删除失败"); } return result; } private Long deleteChannelRoleResourceByRoleId(String roleId){ long result = channelRoleResourceDAO.deleteChannelRoleResourceByRoleId(roleId); return result; } @Override public long update(ChannelRoleCondition condition) { ChannelRole entity = new ChannelRole(); BeanUtils.copyProperties(condition,entity); return channelRoleDao.update(entity); } @Override public int findExeits(String column, String value) { CriteriaBuilder cb = Cnd.builder(ChannelRole.class); cb.andEQ(column, value); Criteria buildCriteria = cb.buildCriteria(); return channelRoleDao.countByCriteria(buildCriteria); } @Override public ChannelRole findRoleByChannelCode(String channelCode) { CriteriaBuilder cb = Cnd.builder(ChannelRole.class); cb.andEQ("channelCode", channelCode); Criteria buildCriteria = cb.buildCriteria(); return channelRoleDao.findOneByCriteria(buildCriteria); } @Override public ChannelRole findByCondition(ChannelRoleCondition condition) { CriteriaBuilder cb = Cnd.builder(ChannelRole.class); if(!Strings.isEmpty(condition.getDescription())){ cb.andLike("description", condition.getDescription()); } if(!Strings.isEmpty(condition.getRoleName())){ cb.andLike("roleName", condition.getRoleName()); } if(!Strings.isEmpty(condition.getChannelName())){ cb.andEQ("channelName", condition.getChannelName()); } if(!Strings.isEmpty(condition.getChannelCode())){ cb.andEQ("channelCode", condition.getChannelCode()); } Criteria buildCriteria = cb.buildCriteria(); return channelRoleDao.findOneByCriteria(buildCriteria); } }
true
5d9836934d4ba87ed039ac209a682d087b8e5840
Java
kaiyan910/PikaPlus
/app/src/main/java/com/crookk/pikaplus/module/map/presenter/MapPresenter.java
UTF-8
4,608
1.914063
2
[]
no_license
package com.crookk.pikaplus.module.map.presenter; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import com.crookk.pikaplus.Preference_; import com.crookk.pikaplus.core.presenter.BasePresenter; import com.crookk.pikaplus.core.utils.LogUtils; import com.crookk.pikaplus.local.bean.DatabaseManager; import com.crookk.pikaplus.local.bean.FileManager; import com.crookk.pikaplus.local.bean.BasicPokemonManager; import com.crookk.pikaplus.local.bean.MockPokemonManager; import com.crookk.pikaplus.local.bean.PokemonManager; import com.crookk.pikaplus.local.model.api.SpawnResultWrapper; import com.crookk.pikaplus.local.model.db.Pokemon; import com.crookk.pikaplus.local.model.db.Spawn; import com.crookk.pikaplus.module.map.model.PokemonMarker; import com.crookk.pikaplus.module.map.service.MapService; import com.crookk.pikaplus.module.map.service.MockMapService; import com.crookk.pikaplus.module.map.ui.view.MapView; import com.google.android.gms.maps.model.LatLngBounds; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.sharedpreferences.Pref; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; @EBean public class MapPresenter implements BasePresenter<MapView> { @Bean(MockMapService.class) MapService mMapService; @Bean DatabaseManager mDatabaseManager; @Bean(MockPokemonManager.class) PokemonManager mPokemonManager; @Bean FileManager mFileManager; @Pref Preference_ mPreference; private MapView mView; private Long mLastRequestTime = 0L; private List<Pokemon> mBlacklist = new ArrayList<>(); @AfterInject void afterInject() { mLastRequestTime = mPreference.lastRequestTime().get(); LogUtils.d(this, "Last Request Time=[%d]", mLastRequestTime); } @Override public void attach(MapView view) { mView = view; createBlacklist(); } @Background public void fetchPokemonFromServer(LatLngBounds bounds) { if (mView == null) throw new RuntimeException("no view is attached to MapPresenter"); SpawnResultWrapper result = mMapService.getRawData(mLastRequestTime, bounds); if (result != null) { mLastRequestTime = result.getTime(); mPreference.edit().lastRequestTime().put(mLastRequestTime).apply(); List<Spawn> spawnList = Spawn.convert(result.getSpawnResultList()); LogUtils.d(this, "Fetched Pokemon from server=[%d]", spawnList.size()); if (spawnList.size() > 0) { mDatabaseManager.insert(spawnList); } mView.onPokemonFound(filter(spawnList), mLastRequestTime * 1000L, true); } else { mView.onPokemonFound(new ArrayList<Spawn>(), new Date().getTime(), true); } } @Background public void checkIV(PokemonMarker marker) { List<Spawn> spawnList = new ArrayList<>(); spawnList.add(marker.getSpawn()); mPokemonManager.checkIndividualValue(spawnList); } @Background public void saveSnapshot(Bitmap bitmap) { if (mView == null) throw new RuntimeException("no view is attached to MapPresenter"); File file = mFileManager.saveBitmap(bitmap); if (file != null) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); mView.onSnapshotSaved(intent); } } @Background public void fetchPokemonFromDatabase() { if (mView == null) throw new RuntimeException("no view is attached to MapPresenter"); List<Spawn> spawnList = mDatabaseManager.querySpawns(); LogUtils.d(this, "Fetched Pokemon from database=[%d]", spawnList.size()); mView.onPokemonFound(spawnList, new Date().getTime(), false); } public void refresh() { createBlacklist(); } private List<Spawn> filter(List<Spawn> spawnList) { List<Spawn> result = new ArrayList<>(); for(Spawn spawn : spawnList) { if(!mBlacklist.contains(spawn.getPokemon())) { result.add(spawn); } } return result; } private void createBlacklist() { mBlacklist.clear(); mBlacklist = mDatabaseManager.queryBlacklistPokemonList(); } }
true
d43479c300ccdff8bf2a10a476967257d275b757
Java
openflexo-team/openflexo-core
/flexo-foundation/src/main/java/org/openflexo/foundation/fml/rt/logging/FMLConsole.java
UTF-8
10,426
2.015625
2
[]
no_license
/** * * Copyright (c) 2014, Openflexo * * This file is part of Flexo-foundation, a component of the software infrastructure * developed at Openflexo. * * * Openflexo is dual-licensed under the European Union Public License (EUPL, either * version 1.1 of the License, or any later version ), which is available at * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * and the GNU General Public License (GPL, either version 3 of the License, or any * later version), which is available at http://www.gnu.org/licenses/gpl.html . * * You can redistribute it and/or modify under the terms of either of these licenses * * If you choose to redistribute it and/or modify under the terms of the GNU GPL, you * must include the following additional permission. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with software containing parts covered by the terms * of EPL 1.0, the licensors of this Program grant you additional permission * to convey the resulting work. * * * This software is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.openflexo.org/license.html for details. * * * Please contact Openflexo (openflexo-contacts@openflexo.org) * or visit www.openflexo.org if you need additional information. * */ package org.openflexo.foundation.fml.rt.logging; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.openflexo.foundation.FlexoEditor; import org.openflexo.foundation.fml.FlexoBehaviour; import org.openflexo.foundation.fml.rt.FlexoConceptInstance; import org.openflexo.foundation.fml.rt.logging.FMLLoggingFilter.FilterType; import org.openflexo.toolbox.PropertyChangedSupportDefaultImplementation; /** * Represent the console related to the execution of FML inside a {@link FlexoEditor} (related to a project) * * @author sylvain * */ public class FMLConsole extends PropertyChangedSupportDefaultImplementation { /** * Send supplied logString to log console, with supplied log level * * @param aLogString * @param logLevel */ // public void log(String aLogString, LogLevel logLevel, FlexoConceptInstance fci, FlexoBehaviour behaviour); public static enum LogLevel { SEVERE, WARNING, INFO, FINE, FINER, FINEST, DEBUG } private FlexoEditor editor; private FMLConsole.LogLevel monitoredLogLevel = FMLConsole.LogLevel.INFO; private boolean keepLogTrace = true; private int maxLogCount = -1; // -1 means infinite private final LinkedList<FMLLogRecord> allRecords; private final ArrayList<FMLLogRecord> filteredRecords = new ArrayList<>(); private List<FMLLogRecord> records; private int totalLogs = 0; private int totalWarningLogs = 0; private int totalSevereLogs = 0; private int logCount = 0; private int warningCount = 0; private int severeCount = 0; private boolean filtersApplied = false; private boolean textSearchApplied = false; private FMLLoggingFormatter formatter; public FMLConsole(FlexoEditor editor) { this.editor = editor; allRecords = new LinkedList<>(); records = allRecords; formatter = new FMLLoggingFormatter(); } public FlexoEditor getFlexoEditor() { return editor; } /** * Receive aLogString as debug in console * * @param aLogString */ public void debug(String aLogString, FlexoConceptInstance fci, FlexoBehaviour behaviour) { FMLLogRecord logRecord = new FMLLogRecord(aLogString, FMLConsole.LogLevel.DEBUG, fci, behaviour, this); add(logRecord); System.out.println(formatter.format(logRecord)); } /** * Send supplied logString to log console, with supplied log level * * @param aLogString * @param logLevel */ public void log(String aLogString, FMLConsole.LogLevel logLevel, FlexoConceptInstance fci, FlexoBehaviour behaviour) { if (getMonitoredLogLevel().ordinal() >= logLevel.ordinal()) { FMLLogRecord logRecord = new FMLLogRecord(aLogString, logLevel, fci, behaviour, this); add(logRecord); System.out.println(formatter.format(logRecord)); } } public FMLConsole.LogLevel getMonitoredLogLevel() { return monitoredLogLevel; } public void setMonitoredLogLevel(FMLConsole.LogLevel monitoredLogLevel) { if ((monitoredLogLevel == null && this.monitoredLogLevel != null) || (monitoredLogLevel != null && !monitoredLogLevel.equals(this.monitoredLogLevel))) { FMLConsole.LogLevel oldValue = this.monitoredLogLevel; this.monitoredLogLevel = monitoredLogLevel; getPropertyChangeSupport().firePropertyChange("monitoredLogLevel", oldValue, monitoredLogLevel); } } private boolean showDebug = true; public boolean isShowDebug() { return showDebug; } public void setShowDebug(boolean showDebug) { if (showDebug != this.showDebug) { boolean oldValue = this.showDebug; this.showDebug = showDebug; getPropertyChangeSupport().firePropertyChange("showDebug", oldValue, showDebug); } } public boolean getKeepLogTrace() { return keepLogTrace; } public void setKeepLogTrace(boolean keepLogTrace) { if (keepLogTrace != this.keepLogTrace) { boolean oldValue = this.keepLogTrace; this.keepLogTrace = keepLogTrace; getPropertyChangeSupport().firePropertyChange("keepLogTrace", oldValue, keepLogTrace); } } public int getMaxLogCount() { return maxLogCount; } public void setMaxLogCount(int maxLogCount) { if (maxLogCount != this.maxLogCount) { int oldValue = this.maxLogCount; this.maxLogCount = maxLogCount; getPropertyChangeSupport().firePropertyChange("maxLogCount", oldValue, maxLogCount); } } private boolean isNotifying = false; private void add(FMLLogRecord record) { synchronized (allRecords) { if (getMaxLogCount() > -1 && allRecords.size() > getMaxLogCount()) { allRecords.remove(0); } allRecords.add(record); if (record.level == FMLConsole.LogLevel.WARNING) { totalWarningLogs++; getPropertyChangeSupport().firePropertyChange("warningLogs", null, record); } if (record.level == FMLConsole.LogLevel.SEVERE) { totalSevereLogs++; getPropertyChangeSupport().firePropertyChange("severeLogs", null, record); } totalLogs++; if (!isNotifying) { isNotifying = true; getPropertyChangeSupport().firePropertyChange("records", null, record); getPropertyChangeSupport().firePropertyChange("totalLogs", null, record); getPropertyChangeSupport().firePropertyChange("logCount", null, record); isNotifying = false; } } } public FMLLogRecord elementAt(int row) { return allRecords.get(row); } public List<FMLLogRecord> getRecords() { return records; } public void setRecords(List<FMLLogRecord> records) { this.records = records; } public void addToRecords(FMLLogRecord record) { records.add(record); } public void removeFromRecords(FMLLogRecord record) { records.remove(record); } public void clearRecords() { logCount = 0; warningCount = 0; severeCount = 0; totalLogs = 0; totalWarningLogs = 0; totalSevereLogs = 0; allRecords.clear(); dismissFilters(); notifyFilteringChange(); } public int getTotalLogs() { return totalLogs; } public int getWarningLogs() { return totalWarningLogs; } public int getSevereLogs() { return totalSevereLogs; } public int getLogCount() { if (!filtersApplied && !textSearchApplied) { return totalLogs; } return logCount; } public int getWarningCount() { if (!filtersApplied && !textSearchApplied) { return totalWarningLogs; } return warningCount; } public int getSevereCount() { if (!filtersApplied && !textSearchApplied) { return totalSevereLogs; } return severeCount; } public void applyFilters(List<FMLLoggingFilter> filters) { logCount = 0; warningCount = 0; severeCount = 0; filtersApplied = true; filteredRecords.clear(); boolean onlyKeep = false; for (FMLLoggingFilter f : filters) { if (f.type == FilterType.OnlyKeep) { onlyKeep = true; } } for (FMLLogRecord r : allRecords) { boolean keepRecord = !onlyKeep; for (FMLLoggingFilter f : filters) { if (f.filterDoesApply(r)) { if (f.type == FilterType.OnlyKeep) { keepRecord = true; } } } for (FMLLoggingFilter f : filters) { if (f.filterDoesApply(r)) { if (f.type == FilterType.Dismiss) { keepRecord = false; } } } if (keepRecord) { filteredRecords.add(r); logCount++; if (r.level == FMLConsole.LogLevel.WARNING) { warningCount++; } else if (r.level == FMLConsole.LogLevel.SEVERE) { severeCount++; } } } records = filteredRecords; notifyFilteringChange(); } public void dismissFilters() { filtersApplied = false; records = allRecords; notifyFilteringChange(); } public void searchText(String someText) { logCount = 0; warningCount = 0; severeCount = 0; textSearchApplied = true; records = new ArrayList<>(); FMLLoggingFilter f = new FMLLoggingFilter("search"); f.setHasFilteredMessage(true); f.filteredContent = someText; for (FMLLogRecord r : filtersApplied() ? filteredRecords : allRecords) { if (f.filterDoesApply(r)) { records.add(r); logCount++; if (r.level == FMLConsole.LogLevel.WARNING) { warningCount++; } else if (r.level == FMLConsole.LogLevel.SEVERE) { severeCount++; } } } notifyFilteringChange(); } public void dismissSearchText() { textSearchApplied = false; if (filtersApplied()) { records = filteredRecords; notifyFilteringChange(); } else { records = allRecords; notifyFilteringChange(); } } private void notifyFilteringChange() { getPropertyChangeSupport().firePropertyChange("logCount", -1, logCount); getPropertyChangeSupport().firePropertyChange("warningCount", -1, warningCount); getPropertyChangeSupport().firePropertyChange("severeCount", -1, severeCount); getPropertyChangeSupport().firePropertyChange("records", null, records); getPropertyChangeSupport().firePropertyChange("filtersApplied", false, true); getPropertyChangeSupport().firePropertyChange("textSearchApplied", false, true); } public boolean filtersApplied() { return filtersApplied; } public boolean textSearchApplied() { return textSearchApplied; } }
true
ed6b9e9322e2b92d6dba511ecbda884395c1190c
Java
SaeedHyder/GymBuzzUser
/app/src/main/java/com/app/gymbuzz/entities/GymDetailModel.java
UTF-8
6,430
1.914063
2
[]
no_license
package com.app.gymbuzz.entities; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class GymDetailModel { @Expose @SerializedName("isDeleted") private boolean isdeleted; @Expose @SerializedName("isActive") private boolean isactive; @Expose @SerializedName("lastUpdatedDate") private String lastupdateddate; @Expose @SerializedName("updatedIp") private String updatedip; @Expose @SerializedName("updatedBy") private String updatedby; @Expose @SerializedName("createdDate") private String createddate; @Expose @SerializedName("gymCMS") private ArrayList<GymCMS> gymcms; @Expose @SerializedName("gymImages") private ArrayList<GymImages> gymimages ; @Expose @SerializedName("gymQrCode") private String gymqrcode; @Expose @SerializedName("logoPath") private String logopath; @Expose @SerializedName("description") private String description; @Expose @SerializedName("countryCode") private int countrycode; @Expose @SerializedName("city") private String city; @Expose @SerializedName("address") private String address; @Expose @SerializedName("phoneNumber") private String phonenumber; @Expose @SerializedName("email") private String email; @Expose @SerializedName("gymName") private String gymname; @Expose @SerializedName("gymID") private int gymid; public boolean getIsdeleted() { return isdeleted; } public boolean getIsactive() { return isactive; } public String getLastupdateddate() { return lastupdateddate; } public String getUpdatedip() { return updatedip; } public String getUpdatedby() { return updatedby; } public String getCreateddate() { return createddate; } public ArrayList<GymCMS> getGymcms() { return gymcms; } public ArrayList<GymImages> getGymimages() { return gymimages==null?new ArrayList<>():gymimages; } public String getGymqrcode() { return gymqrcode; } public String getLogopath() { return logopath; } public String getDescription() { return description; } public int getCountrycode() { return countrycode; } public String getCity() { return city; } public String getAddress() { return address; } public String getPhonenumber() { return phonenumber; } public String getEmail() { return email; } public String getGymname() { return gymname; } public int getGymid() { return gymid; } public static class GymCMS { @Expose @SerializedName("isDeleted") private boolean isdeleted; @Expose @SerializedName("isActive") private boolean isactive; @Expose @SerializedName("lastUpdatedDate") private String lastupdateddate; @Expose @SerializedName("updatedIp") private String updatedip; @Expose @SerializedName("updatedBy") private String updatedby; @Expose @SerializedName("createdDate") private String createddate; @Expose @SerializedName("createdBy") private String createdby; @Expose @SerializedName("description") private String description; @Expose @SerializedName("cmsType") private int cmstype; @Expose @SerializedName("gymID") private int gymid; @Expose @SerializedName("gymCMSID") private int gymcmsid; public boolean getIsdeleted() { return isdeleted; } public boolean getIsactive() { return isactive; } public String getLastupdateddate() { return lastupdateddate; } public String getUpdatedip() { return updatedip; } public String getUpdatedby() { return updatedby; } public String getCreateddate() { return createddate; } public String getCreatedby() { return createdby; } public String getDescription() { return description; } public int getCmstype() { return cmstype; } public int getGymid() { return gymid; } public int getGymcmsid() { return gymcmsid; } } public static class GymImages { @Expose @SerializedName("isDeleted") private boolean isdeleted; @Expose @SerializedName("isActive") private boolean isactive; @Expose @SerializedName("lastUpdatedDate") private String lastupdateddate; @Expose @SerializedName("updatedIp") private String updatedip; @Expose @SerializedName("updatedBy") private String updatedby; @Expose @SerializedName("createdDate") private String createddate; @Expose @SerializedName("createdBy") private String createdby; @Expose @SerializedName("imagePath") private String imagepath; @Expose @SerializedName("gymId") private int gymid; @Expose @SerializedName("gymImagesId") private int gymimagesid; public boolean getIsdeleted() { return isdeleted; } public boolean getIsactive() { return isactive; } public String getLastupdateddate() { return lastupdateddate; } public String getUpdatedip() { return updatedip; } public String getUpdatedby() { return updatedby; } public String getCreateddate() { return createddate; } public String getCreatedby() { return createdby; } public String getImagepath() { return imagepath; } public int getGymid() { return gymid; } public int getGymimagesid() { return gymimagesid; } } }
true
3074b6565639ef1831080bcbf9b25d019887d17e
Java
SSSOy/2018_JAVA
/Test4.java
UTF-8
185
2.09375
2
[]
no_license
class Test4.java public static void main(String ar[]) { int kor = 89; int eng = 80; int math = 90; int total = 0; int avg = 0; System.out.println(total = kor + eng + math); }
true
f336ada2d741cbca1a4c7f289a423c9f9d84cea5
Java
tzl520/stack
/stack/src/com/edu/service/AdminService.java
UTF-8
373
1.554688
2
[]
no_license
package com.edu.service; import java.sql.SQLException; import com.edu.bean.Admin; public interface AdminService { Admin isLogin(String name, String pwd); int getIdByTime() throws SQLException; int getIdCount() throws SQLException; int getSnackCount() throws SQLException; int getmenuCount() throws SQLException; int getforeignCount() throws SQLException; }
true
9ac4f9e5c234938d479d207ad8702d2086162605
Java
aosapp/account-service
/accountservice/src/main/java/com/advantage/accountsoap/util/UrlResources.java
UTF-8
4,948
1.945313
2
[]
no_license
package com.advantage.accountsoap.util; import com.advantage.accountsoap.config.SmokingGunInit; import com.advantage.common.Constants; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import javax.inject.Inject; import java.net.URL; @Configuration public class UrlResources { private static URL urlPrefixCatalog; private static URL urlPrefixMasterCredit; private static URL urlPrefixOrder; private static URL urlPrefixSafePay; private static URL urlPrefixSoapAccount; private static URL urlPrefixSoapShipEx; public static URL getUrlSoapAccount() { return urlPrefixSoapAccount; } public static URL getUrlCatalog() { return urlPrefixCatalog; } public static URL getUrlMasterCredit() { return urlPrefixMasterCredit; } public static URL getUrlOrder() { return urlPrefixOrder; } public static URL getUrlSafePay() { return urlPrefixSafePay; } public static URL getUrlSoapShipEx() { return urlPrefixSoapShipEx; } private static final Logger logger = LogManager.getLogger(UrlResources.class); @Inject private Environment env; @Bean public int setConfiguration(){ urlPrefixCatalog = generateUrlPrefix("Catalog"); urlPrefixMasterCredit = generateUrlPrefix("MasterCredit"); urlPrefixOrder = generateUrlPrefix("Order"); urlPrefixSafePay = generateUrlPrefix("SafePay"); //urlPrefixService = generateUrlPrefix("Service"); urlPrefixSoapAccount = generateUrlSoapPrefix("Account"); urlPrefixSoapShipEx = generateUrlSoapPrefix("ShipEx"); if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder("Url_resources: ").append(System.lineSeparator()); sb.append(" Catalog=\'" + getUrlCatalog() + "\'").append(System.lineSeparator()); sb.append(" MasterCredit=\'" + getUrlMasterCredit() + "\'").append(System.lineSeparator()); sb.append(" Order=\'" + getUrlOrder() + "\'").append(System.lineSeparator()); sb.append(" SafePay=\'" + getUrlSafePay() + "\'").append(System.lineSeparator()); sb.append(" Account (SOAP)=\'" + getUrlSoapAccount() + "\'").append(System.lineSeparator()); sb.append(" ShipEx (SOAP)=\'" + getUrlSoapShipEx() + "\'"); logger.info(sb.toString()); } return 1; } public URL generateUrlPrefix(String serviceName) { URL url = null; try { String schema = Constants.URI_SCHEMA; String host = ""; if(env.getProperty(Constants.SINGLE_MACHINE_DEPLOYMENT).equals("true")){ host = "localhost"; } else{ host = env.getProperty(serviceName.toLowerCase() + ".service.url.host"); } String isAOSDomain = env.getProperty("AOS.Domain.url.host"); int port = (isAOSDomain != null && isAOSDomain.equalsIgnoreCase("Yes")) || host.charAt(0) == '@' ? 80 : Integer.parseInt(env.getProperty(serviceName.toLowerCase() + ".service.url.port")); String suffix = '/' + env.getProperty(serviceName.toLowerCase() + ".service.url.suffix") + "/"; host = host.charAt(0) == '@' ? "localhost" : host; url = new URL(schema, host, port, suffix); } catch (Throwable e) { logger.fatal("Wrong properties file", e); } logger.debug("URL = " + url.toString()); return url; } public URL generateUrlSoapPrefix(String serviceName) { URL urlWithWsdl = null; try { String schema = Constants.URI_SCHEMA; String host = ""; if(env.getProperty(Constants.SINGLE_MACHINE_DEPLOYMENT).equals("true")){ host = "localhost"; } else{ host = env.getProperty(serviceName.toLowerCase() + ".soapservice.url.host"); } int port = host.charAt(0) == '@' ? 80 : Integer.parseInt(env.getProperty(serviceName.toLowerCase() + ".soapservice.url.port")); String suffix = env.getProperty(serviceName.toLowerCase() + ".soapservice.url.suffix"); String wsdl = env.getProperty(serviceName.toLowerCase() + ".soapservice.url.wsdl"); if (! wsdl.contains("/")) { suffix += '/'; } host = host.charAt(0) == '@' ? "localhost" : host; urlWithWsdl = new URL(new URL(schema, host, port, suffix), suffix + wsdl); } catch (Throwable e) { logger.fatal("Wrong properties file", e); } logger.debug("URL = " + urlWithWsdl.toString()); return urlWithWsdl; } }
true
5862238616b6882b7bc15a36605f3bf003694238
Java
codehaus/service-conduit
/sca4j/modules/tags/sca4j-modules-parent-pom-0.1.1/extension/binding/sca4j-binding-jms/src/main/java/org/sca4j/binding/jms/introspection/JmsLoaderHelper.java
UTF-8
4,233
2.046875
2
[]
no_license
/* * SCA4J * Copyright (c) 2008-2012 Service Symphony Limited * * This proprietary software may be used only in connection with the SCA4J license * (the ?License?), a copy of which is included in the software or may be obtained * at: http://www.servicesymphony.com/licenses/license.html. * * Software distributed under the License is distributed on an as is basis, without * warranties or conditions of any kind. See the License for the specific language * governing permissions and limitations of use of the software. This software is * distributed in conjunction with other software licensed under different terms. * See the separate licenses for those programs included in the distribution for the * permitted and restricted uses of such software. * */ package org.sca4j.binding.jms.introspection; import java.util.Map; import org.sca4j.binding.jms.common.ConnectionFactoryDefinition; import org.sca4j.binding.jms.common.CreateOption; import org.sca4j.binding.jms.common.DestinationDefinition; import org.sca4j.binding.jms.common.DestinationType; import org.sca4j.binding.jms.common.JmsBindingMetadata; import org.sca4j.binding.jms.common.JmsURIMetadata; import org.sca4j.binding.jms.common.ResponseDefinition; /** * Helper class for JMS loader. */ public class JmsLoaderHelper { private static final String DEFAULT_CLIENT_QUEUE = "clientQueue"; /** * Jndi name for default ConnectionFactory */ private static final String DEFAULT_JMS_CONNECTION_FACTORY = "connectionFactory"; private JmsLoaderHelper() { } /** * Transform a JmsURIMetadata object to a JmsBindingMetadata. * * @param uriMeta JmsURIMetadata * @return a equivalent JmsURIMetadata object */ static JmsBindingMetadata getJmsMetadataFromURI(JmsURIMetadata uriMeta) { JmsBindingMetadata result = new JmsBindingMetadata(); Map<String, String> uriProperties = uriMeta.getProperties(); // Destination DestinationDefinition destination = new DestinationDefinition(); String destinationType = uriProperties.get(JmsURIMetadata.DESTINATIONTYPE); if ("topic".equalsIgnoreCase(destinationType)) { destination.setDestinationType(DestinationType.topic); } destination.setName(uriMeta.getDestination()); destination.setCreate(CreateOption.never); // always assume the destination already exists result.setDestination(destination); // ConnectionFactory ConnectionFactoryDefinition connectionFactory = new ConnectionFactoryDefinition(); String connectionFactoryName = uriProperties .get(JmsURIMetadata.CONNECTIONFACORYNAME); if (connectionFactoryName == null) { connectionFactory.setName(DEFAULT_JMS_CONNECTION_FACTORY); } else { connectionFactory.setName(connectionFactoryName); } connectionFactory.setCreate(CreateOption.never); result.setConnectionFactory(connectionFactory); // Response copy configuration of request ResponseDefinition response = new ResponseDefinition(); response.setConnectionFactory(connectionFactory); DestinationDefinition responseDestinationDef = new DestinationDefinition(); String responseDestination = uriProperties.get(JmsURIMetadata.RESPONSEDESTINAT); if (responseDestination != null) { responseDestinationDef.setName(responseDestination); } else { responseDestinationDef.setName(DEFAULT_CLIENT_QUEUE); } responseDestinationDef.setCreate(CreateOption.never); response.setDestination(responseDestinationDef); result.setResponse(response); return result; } /** * Generate an URI from JmsBindingMetadata. This may be removed when call eliminate dependency on binding's URI. */ static String generateURI(JmsBindingMetadata metadata) { StringBuilder builder = new StringBuilder(); builder.append("jms:").append(metadata.getDestination().getName()) .append("?connectionFactory=").append( metadata.getConnectionFactory().getName()); return builder.toString(); } }
true
cad21c8bdabfd7565d0204e04867231c124e6ca7
Java
KonstantinKovtun/KovtunK
/chapter_002/src/test/java/ru/job4j/singleton/TrackerSingleFourthTest.java
UTF-8
425
2.4375
2
[ "Apache-2.0" ]
permissive
package ru.job4j.singleton; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class TrackerSingleFourthTest { @Test public void whenFirstSingleton() { TrackerSingleFourth tracker1 = TrackerSingleFourth.getInstance(); TrackerSingleFourth tracker2 = TrackerSingleFourth.getInstance(); assertThat(tracker1, is(tracker2)); } }
true
4eb1237a8daedff1c071f87471001d60b0ca7bb6
Java
337/dataloader_etl
/src/main/java/com/xingcloud/dataloader/dao/MessageQueue.java
UTF-8
3,953
2.359375
2
[]
no_license
package com.xingcloud.dataloader.dao; import com.xingcloud.dataloader.server.message.DataLoaderMessage; import com.xingcloud.dataloader.server.message.MessageFactory; import com.xingcloud.dataloader.server.message.NullMessage; import com.xingcloud.redis.RedisResourceManager; import com.xingcloud.util.Constants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import redis.clients.jedis.Jedis; import java.util.List; /** * Dataloader Task Queue. backed by redis * Author: qiujiawei * Date: 12-5-16 */ public class MessageQueue { public Log LOG = LogFactory.getLog(MessageQueue.class); static final int dbNumber = Constants.REDIS_DB_NUM; private String ip; public MessageQueue(String ip) { this.ip = ip; } private String getNextEvent(Jedis jedis) { List<String> re = jedis.blpop(100000, ip); return re.get(1); } public DataLoaderMessage getNextMassage() { Jedis jedis = null; try { jedis = initJedis(); return MessageFactory.getMessage(getNextEvent(jedis)); } catch (Exception e) { LOG.error("get next message catch exception", e); if (jedis != null) { RedisResourceManager.getInstance().returnBrokenResource(jedis); jedis = null; } } finally { if (jedis != null) { RedisResourceManager.getInstance().returnResource(jedis); } } return new NullMessage(); } public boolean addMessageFirst(DataLoaderMessage message) { boolean returnResult = false; for (int i = 0; i < 3; i++) { Jedis jedis = null; try { jedis = initJedis(); jedis.lpush(ip, message.toString()); returnResult = true; break; } catch (Exception e) { if (jedis != null) { RedisResourceManager.getInstance().returnBrokenResource(jedis); jedis = null; } if (i >= 2) { LOG.error("addMessageFirst catch exception", e); } } finally { if (jedis != null) { RedisResourceManager.getInstance().returnResource(jedis); } } } return returnResult; } public boolean addMessageLast(DataLoaderMessage message) { Jedis jedis = null; try { jedis = initJedis(); jedis.rpush(ip, message.toString()); return true; } catch (Exception e) { LOG.error("addMessageLast catch exception", e); if (jedis != null) { RedisResourceManager.getInstance().returnBrokenResource(jedis); jedis = null; } } finally { if (jedis != null) { RedisResourceManager.getInstance().returnResource(jedis); } } return false; } public String getAllMessage() { Jedis jedis = null; try { jedis = initJedis(); return (jedis.lrange(ip, 0, 1)).toString(); } catch (Exception e) { LOG.error("getAllMessage catch exception", e); if (jedis != null) { RedisResourceManager.getInstance().returnBrokenResource(jedis); jedis = null; } return ""; } finally { if (jedis != null) { RedisResourceManager.getInstance().returnResource(jedis); } } } private Jedis initJedis() { Jedis jedis = RedisResourceManager.getInstance().getCache(); jedis.select(dbNumber); return jedis; } }
true
f9c4e5764649b079e971c8689c1605ef5e56714d
Java
Owhab/Java-OOP-Simple-Projects
/StaticMethod.java
UTF-8
455
3.34375
3
[]
no_license
class StaticmethodDemo{ void Owhab(){ System.out.println("This is an example of Non- Static Method"); } static void Owhab2(){ System.out.println("This is an example of Static Method"); } } public class StaticMethod{ public static void main(String [] args) { StaticmethodDemo s1 = new StaticmethodDemo(); s1.Owhab(); StaticmethodDemo.Owhab2(); } }
true
42f870f09c60e0ae040d418dbbb28f74668b46a7
Java
wojciechh-kainos/tdp-recruitment
/src/main/java/domain/InterviewType.java
UTF-8
66
1.851563
2
[]
no_license
package domain; public enum InterviewType { Full, Init }
true
ccdecc0b0c538af200e6821564e430536df90477
Java
yejineer/Study
/PS/BOJ/Code/Q1789.java
UTF-8
556
2.953125
3
[]
no_license
package Greedy; /* [문제] 수들의 합 [분류] 수학, 그리디 알고리즘 [날짜] 2021-12-17 */ import java.io.*; public class Q1789 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long S = Long.parseLong(br.readLine()); int i = 0; long sum = 0; while (true) { sum += i; if (sum > S) break; i++; } System.out.println(--i); } }
true
ebe005ebfc5f1f4aa57d66c0999fae7d32ce9f99
Java
khmaies5/Cyberdev-covoituragetn
/src/edu/esprit/pi/services/UserFavorisService.java
UTF-8
5,225
2.171875
2
[]
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 edu.esprit.pi.services; import edu.esprit.pi.iservices.IService; import edu.esprit.pi.models.User; import edu.esprit.pi.technique.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.List; import edu.esprit.pi.models.UserFavoris; import java.sql.ResultSet; import java.util.ArrayList; import edu.esprit.pi.iservices.IUserFavorisService; /** * * @author Nacef Fethi */ public class UserFavorisService implements IUserFavorisService { private Connection connection; private PreparedStatement ps; public UserFavorisService() { connection = DataSource.getInstance().getConnection(); } @Override public void add(UserFavoris userFavoris) { String req = "insert into user_favoris (iduser_recommendes,id_userconnect) values (?,?)"; try { ps = connection.prepareStatement(req); ps.setInt(1, userFavoris.getUserRecommendes().getId()); ps.setInt(2,userFavoris.getUserConnect().getId()); // ps.setInt(3,userFavoris.getNbrRecommendation()); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } @Override public void delete(Integer idUserFavoris) { String req = "delete from user_favoris where id =?"; try { ps = connection.prepareStatement(req); ps.setInt(1, idUserFavoris); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } @Override public List<UserFavoris> getAll() { String req = "select * from user_favoris"; List<UserFavoris> listpub_f = new ArrayList<>(); try { ps = connection.prepareStatement(req); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { UserFavoris userFavoris = new UserFavoris(resultSet.getInt(1),resultSet.getDate(2),new UserService().findById(resultSet.getInt(3)),new UserService().findById(resultSet.getInt(4))); listpub_f.add(userFavoris); } } catch (Exception e) { e.printStackTrace(); } return listpub_f; } // @Override // public UserFavoris findById(Integer iduser_connect) { // String req = "select * from user_favoris where id_userconnect = ?"; // UserFavoris user_favoris = null; // List <UserRecommendes>users= new ArrayList<>(); // // try { // ps = connection.prepareStatement(req); // // ps.setInt(1, iduser_connect); // ResultSet resultSet = ps.executeQuery(); // while (resultSet.next()) { // // user_favoris = new UserFavoris(resultSet.getInt(1),new User(resultSet.getInt(2)),new User(resultSet.getInt(3)),resultSet.getInt(4)); // users.add(user_favoris); // } // // } catch (Exception e) { // e.printStackTrace(); // } // //return user_favoris; //} @Override public List<UserFavoris> findByIduserconnecter(Integer idUserConnect) { String req = "select * from user_favoris where id_userconnect = ?"; UserFavoris user_favoris = null; List <UserFavoris>users= new ArrayList<>(); try { ps = connection.prepareStatement(req); ps.setInt(1, idUserConnect); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { UserFavoris userFavoris = new UserFavoris(resultSet.getInt(1),resultSet.getDate(2),new UserService().findById(resultSet.getInt(3)),new UserService().findById(resultSet.getInt(4))); // user_favoris=new UserFavoris(resultSet.getInt(1), resultSet.getDate(2), new User(resultSet.getInt(3)), userConnect); users.add(userFavoris); } } catch (Exception e) { e.printStackTrace(); } return users; } @Override public List<User> findByIduserconnecte(Integer idUserConnect) { String req = "select * from user_favoris where id_userconnect = ?"; UserFavoris userFavoris = null; List <UserFavoris>users= new ArrayList<>(); List <User>users2= new ArrayList<>(); try { ps = connection.prepareStatement(req); ps.setInt(1, idUserConnect); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { userFavoris = new UserFavoris(resultSet.getInt(1),resultSet.getDate(2),new UserService().findById(resultSet.getInt(3)),new UserService().findById(resultSet.getInt(4))); users.add(userFavoris); } } catch (Exception e) { } for (UserFavoris us : users) { users2.add(new UserService().findById(us.getUserRecommendes().getId())); } return users2; } }
true
010a1b01042e023cbf140796f2f327a21538864a
Java
c-j-j/HttpServer
/src/main/java/http/request/builder/RequestHeaderBuilder.java
UTF-8
1,951
2.265625
2
[]
no_license
package http.request.builder; import http.request.ByteRange; import http.request.HTTPAction; import http.request.RequestHeader; import http.request.auth.AuthenticationHeader; import java.util.Optional; public class RequestHeaderBuilder { private String uri; private HTTPAction httpAction = HTTPAction.GET; private Optional<AuthenticationHeader> authenticationHeader = Optional.<AuthenticationHeader>empty(); private String requestPayload; private long contentLength; private Optional<String> ifMatchValue; private Optional<ByteRange> range = Optional.empty(); public RequestHeaderBuilder withURI(String uri) { this.uri = uri; return this; } public RequestHeaderBuilder withHTTPAction(HTTPAction httpAction) { this.httpAction = httpAction; return this; } public RequestHeaderBuilder withAuthenticationHeader(Optional<AuthenticationHeader> authenticationHeader) { this.authenticationHeader = authenticationHeader; return this; } public RequestHeaderBuilder withAuthenticationHeader(AuthenticationHeader authenticationHeader) { return withAuthenticationHeader(Optional.of(authenticationHeader)); } public RequestHeaderBuilder withRequestPayload(String requestPayload) { this.requestPayload = requestPayload; return this; } public RequestHeaderBuilder withContentLength(long contentLength) { this.contentLength = contentLength; return this; } public RequestHeaderBuilder withIfMatchValue(Optional<String> ifMatch) { this.ifMatchValue = ifMatch; return this; } public RequestHeaderBuilder withRange(Optional<ByteRange> range) { this.range = range; return this; } public RequestHeader build() { return new RequestHeader(httpAction, uri, authenticationHeader, range, requestPayload, contentLength, ifMatchValue); } }
true
7ac0e4861414933bea1363872a5bf3afeceaf5e2
Java
szymongajek/HSSDR
/HSSDR-trunk/src/hyperGraphs/HyperRelation.java
UTF-8
2,673
2.796875
3
[ "Apache-2.0" ]
permissive
package hyperGraphs; import java.awt.Point; import java.util.ArrayList; import java.util.List; public class HyperRelation extends RelationHE { // Incidence matrics - Macierz incydencji private ArrayList<Node> incidents = new ArrayList<Node>(); // dla kolejnych wezlow w realcji punkt zaczenienia relacji w obszarze private ArrayList<Point> hyperRelHookPointSequence = new ArrayList<Point>(); public HyperRelation(ObjectHE parent, Node source, Node target, String relKind) { incidents.add(source); incidents.add(target); this.setParentEdge(parent); this.setAttribute(HLH.KIND, relKind); source.addRelation(this); target.addRelation(this); parent.addChildElement(this); } public HyperRelation(ObjectHE parent, Node[] elements, String relKind) { this.setParentEdge(parent); this.setAttribute(HLH.KIND, relKind); for (Node node : elements) { incidents.add(node); node.addRelation(this); } parent.addChildElement(this); } public void addNodeToRelation(Node newNode) { incidents.add(newNode); newNode.addRelation(this); } void remove() { getParentEdge().removeRelation(this); incidents.clear(); } public Node getFirstNode() { return incidents.get(0); } public Node getSecondNode() { return incidents.get(1); } public List<Node> getIncidentNodes() { return incidents; } /** * check if this hyper rel contains in its connected node a node from both * of given floors * * @param floor1 * @param floor2 * @return */ public boolean containsNodeFromFloor(int floor) { for (Node node : incidents) { if (node.getFloor() == floor) { return true; } } return false; } @Override public boolean isLinkingNodes(Node node1, Node node2) { return (incidents.contains(node1) && incidents.contains(node2)); } @Override public void reconnectNodes(Node oldNode, Node newNode) { for (int i = 0; i < incidents.size(); i++) { if (incidents.get(i)== oldNode){ incidents.set(i, newNode); } } newNode.addRelation(this); oldNode.removeConnection(this); } @Override public Point getInterFloorRelationHookPointforNode(Node node){ for (int i = 0; i < incidents.size(); i++) { if (incidents.get(i)== node){ return hyperRelHookPointSequence.get(i); } } throw new RuntimeException("checking node not connected to relation"); } public void setHyperRelHookPointSequence(ArrayList<Point> multiFloorRelHookPointSequence) { this.hyperRelHookPointSequence=multiFloorRelHookPointSequence; } }
true
3b54ad5e0734ec37a3dd3ad22c87d5b992fe70ea
Java
pheyse/FileSystemFacade
/framework/FSF-Core/src/main/java/de/bright_side/filesystemfacade/remotefs/RemoteFSServletConnectionProvider.java
UTF-8
3,247
2.421875
2
[ "Apache-2.0" ]
permissive
package de.bright_side.filesystemfacade.remotefs; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import de.bright_side.filesystemfacade.util.FSFFileUtil; /** * @author Philip Heyse * */ public class RemoteFSServletConnectionProvider implements RemoteFSConnectionProvider{ private String servletURL; private URL url; private URLConnection connection; public RemoteFSServletConnectionProvider(String servletURL) throws Exception { this.servletURL = servletURL; try { url = new URL(servletURL); } catch (MalformedURLException e) { throw new Exception("Wrong URL: '" + servletURL + "'"); } } @Override public InputStream getInputStream() throws Exception { return connection.getInputStream(); } @Override public OutputStream getOutputStream() throws IOException { try { connection = url.openConnection(); } catch (MalformedURLException e) { throw new IOException("Could not access URL: '" + servletURL + "'"); } connection.setDoOutput(true); return connection.getOutputStream(); } @Override public int compareLocation(RemoteFSConnectionProvider other) { if (other == null) { return 1; } if (!(other instanceof RemoteFSServletConnectionProvider)) { return getClass().getName().compareTo(other.getClass().getName()); } RemoteFSServletConnectionProvider otherProvider = (RemoteFSServletConnectionProvider)other; int result = 0; result = FSFFileUtil.compareString(servletURL, otherProvider.servletURL); if (result != 0){ return result; } return 0; } // @Override // public RemoteFSResponse handle(String command, InputStream payload, Object... parameters) throws Exception { // URL url; // try { // url = new URL(servletURL); // } catch (MalformedURLException e) { // throw new Exception("Wrong URL: '" + servletURL + "'"); // } // // try { // URLConnection connection = url.openConnection(); // connection.setDoOutput(true); // // // // OutputStream outputStream = connection.getOutputStream(); // GZIPOutputStream zipOutputStream = new GZIPOutputStream(outputStream); // // FSFFileUtil.writeStringWithLengthInfo(zipOutputStream, app); // FSFFileUtil.writeStringWithLengthInfo(zipOutputStream, tennant); // FSFFileUtil.writeStringWithLengthInfo(zipOutputStream, username); // FSFFileUtil.writeStringWithLengthInfo(zipOutputStream, password); // // RemoteFSUtil.writeHandleRequestToStream(zipOutputStream, command, payload, parameters); // zipOutputStream.finish(); // zipOutputStream.flush(); // zipOutputStream.close(); // // InputStream inputStream = connection.getInputStream(); // GZIPInputStream gzipin = new GZIPInputStream(inputStream); // // RemoteFSResponse result = RemoteFSUtil.readRemoteFileResponseFromStream(gzipin); // result.setByteResponseInputStream(gzipin); // return result; // } catch (UnknownHostException e) { // throw e; // } // } }
true
3e488f46970bb544ea3f7e9df68e6537e8dcac50
Java
datnguyen84/AppGrab
/Front-end/Drive_MyGrab/Drive_MyGrab/app/src/main/java/deadline/ntn/drive_mygrab/Information_Account.java
UTF-8
6,152
1.828125
2
[]
no_license
package deadline.ntn.drive_mygrab; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.RequestFuture; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Information_Account extends AppCompatActivity { TextView id, hoten, ngaysinh, socmnd, gioitinh, sdt, diachi, loaixe, Soxe, usernameshow_infor; String Username_Infor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_information_account); id = (TextView) findViewById(R.id.txt_showid_infor); hoten = (TextView) findViewById(R.id.txt_showhovaten_infor); ngaysinh = (TextView) findViewById(R.id.txt_showngaysinh_infor); socmnd = (TextView) findViewById(R.id.txt_showsocmnd_infor); gioitinh = (TextView) findViewById(R.id.txt_showgioitinh_infor); sdt = (TextView) findViewById(R.id.txt_showsodt_infor); diachi = (TextView) findViewById(R.id.txt_showdiachi_infor); loaixe = (TextView) findViewById(R.id.txt_showloaixe_infor); Soxe = (TextView) findViewById(R.id.txt_showsoxe_infor); usernameshow_infor = (TextView) findViewById(R.id.txt_showusername_infor); Intent intent_infor = this.getIntent(); String username_textshow = intent_infor.getStringExtra("USERNAME1"); Log.d("xxxxxx", username_textshow); usernameshow_infor.setText(username_textshow); //Can lay cac thong tin va hien thi no len cac bien tren Username_Infor = usernameshow_infor.getText().toString(); } @Override protected void onStart() { super.onStart(); String url = getResources().getString(R.string.Server_Address) + "TaiXe/" + Username_Infor; url = url.replace(" ", "%20"); RequestQueue queue = Volley.newRequestQueue(this); Log.d("xxxx", url); //RequestQueue queue; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { JSONObject json = null; try { json = new JSONObject(response); Log.d("xxxx", "vo duoc"); String test = json.getString("HoTen"); Log.d("xxxx", "vo duoc"); hoten.setText(json.getString("HoTen")); ngaysinh.setText(json.getString("NgaySinh")); socmnd.setText(json.getString("CMND")); gioitinh.setText(json.getString("GioiTinh")); sdt.setText(json.getString("SoDT")); diachi.setText(json.getString("DiaChi")); //txtJson.setText(cityName); } catch (JSONException e) { e.printStackTrace(); Log.d("errror", e.toString());// Not getting any error } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //txtJson.setText("That didn't work!"); } }); queue.add(stringRequest); // String url1 = getResources().getString(R.string.Server_Address) + "TaiXe/Xe/" + Username_Infor; url1 = url1.replace(" ", "%20"); Log.d("xxxxxxx", url1); RequestQueue queue1 = Volley.newRequestQueue(this); StringRequest stringRequest1 = new StringRequest(Request.Method.GET, url1, new Response.Listener<String>() { @Override public void onResponse(String response) { JSONObject json2 = null; try { json2 = new JSONObject(response); Soxe.setText(json2.getString("BienSoXe")); loaixe.setText(json2.getString("LoaiXe")); Log.d("xxxx", "vo duoc"); } catch (JSONException e) { e.printStackTrace(); Log.d("errror", e.toString());// Not getting any error } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //txtJson.setText("That didn't work!"); } }); queue1.add(stringRequest1); } //Ham thay doi mk public void ToChangePassWord(View view) { Intent intent_changepass = new Intent(Information_Account.this, Change_Password.class); intent_changepass.putExtra("USERNAME3", Username_Infor); startActivity(intent_changepass); } //Khi user muon chinh sua bam vao day public void toEditInformation(View view) { Intent intent_main = new Intent(Information_Account.this, Change_Information_Account.class); intent_main.putExtra("USERNAME2", Username_Infor); startActivity(intent_main); } public void ToChangeAvatar(View view) { } //Tro ve app truoc public void ToBackIt(View view){ this.finish(); } }
true
9efc764946913858ed20b76f2ec0d8c369b09116
Java
HoekoS/Capstone-Frontend
/app/src/main/java/com/rajendra/vacationtourapp/AppController.java
UTF-8
817
2.046875
2
[]
no_license
package com.rajendra.vacationtourapp; import android.app.Application; import android.content.Context; import android.database.SQLException; import com.rajendra.vacationtourapp.model.Rest.RestSingleTon; public class AppController extends Application { private RestSingleTon rest; private static AppController instance; @Override public void onTerminate(){ super.onTerminate(); } @Override protected void attachBaseContext(Context base) {super.attachBaseContext(base);} public static synchronized AppController getInstance() {return instance;} public static synchronized RestSingleTon getRest() {return instance.rest;} @Override public void onCreate(){ super.onCreate(); rest = new RestSingleTon(this); instance = this; } }
true
b17db7cba521e7c65572c1c852afdb5b26a1314b
Java
Justin-Schneider/TA-Java
/CSCE145_Lab20/src/SlopedLine.java
UTF-8
356
3.296875
3
[]
no_license
public class SlopedLine implements Line { private double slope; public SlopedLine() { this.slope = 0.0; } public SlopedLine(double slope) { this.slope = slope; } public double getSlope() { return slope; } public void setSlope(double slope) { this.slope = slope; } public double getYPoint(double x) { return (slope*x); } }
true
304184e4e87193c5e1e750431bc1c73fc22cb09a
Java
mingyuanZang/Educational-Management-System
/Educational Management System/src/main/java/application/view/TeacherSearchView.java
UTF-8
6,182
2.765625
3
[]
no_license
package application.view; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import application.controller.TeacherSearchController; import application.model.Course; import application.model.Person; public class TeacherSearchView extends JFrame { private static final long serialVersionUID = -6170452136485764396L; // graphical widgets private JButton btnBack; private JList searchByFirstNameResultsList; private JList searchByLastNameResultsList; private JTextField searchBar; // keep reference to controller private TeacherSearchController controller; // constructor of view delegates the initializations of the GUI public TeacherSearchView(TeacherSearchController controller) { this.controller = controller; initGUI(); } private void initGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); // set to fixed dimension setTitle("Search"); setLayout(new GridBagLayout()); // recommended GridBagConstraints gbc = new GridBagConstraints(); btnBack = new JButton("Back to List"); btnBack.addActionListener(new ActionListener() { @Override // used anonymous classes because this is done only once, is waiting for clicks public void actionPerformed(ActionEvent e) { controller.backtoTeacherList(); } }); final JScrollPane sp = new JScrollPane(); searchBar = new JTextField(15); JButton btnSearchByFirstname = new JButton("Search By First Name"); btnSearchByFirstname.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (searchBar.getText().isEmpty()) { JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Cannot search, no keyword provided.", "Empty Search Error", JOptionPane.ERROR_MESSAGE); } else { searchByFirstNameResultsList = new JList<>( controller.returnSearchByFirstNameResultsList(searchBar.getText()).toArray()); sp.getViewport().add(searchByFirstNameResultsList); sp.revalidate(); sp.repaint(); } } }); JButton btnSearchByLastname = new JButton("Search By Last Name"); btnSearchByLastname.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (searchBar.getText().isEmpty()) { JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Cannot search, no keyword provided.", "Empty Search Error", JOptionPane.ERROR_MESSAGE); } else { searchByLastNameResultsList = new JList<>( controller.returnSearchByLastNameResultsList(searchBar.getText()).toArray()); sp.getViewport().add(searchByLastNameResultsList); sp.revalidate(); sp.repaint(); } } }); JButton btnSearchByEmail = new JButton("Search By Email"); btnSearchByEmail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (searchBar.getText().isEmpty()) { JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Cannot search, no number provided.", "Empty Search Error", JOptionPane.ERROR_MESSAGE); } else { Person searchByEmailResult = controller.returnSearchByEmailResult(searchBar.getText()); ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add(searchByEmailResult.getFirstName() + " " + searchByEmailResult.getLastName()); JList list = new JList<>(arrayList.toArray()); sp.getViewport().add(list); sp.revalidate(); sp.repaint(); } } }); JButton btnSearchBySerialNumber = new JButton("Search By Serial Number"); btnSearchBySerialNumber.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (searchBar.getText().isEmpty()) { JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Cannot search, no number provided.", "Empty Search Error", JOptionPane.ERROR_MESSAGE); } else { Person searchBySerialNumberResult = controller .returnSearchBySerialNumberResult(Integer.parseInt(searchBar.getText())); ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add(searchBySerialNumberResult.getFirstName() + " " + searchBySerialNumberResult.getLastName()); JList list = new JList<>(arrayList.toArray()); sp.getViewport().add(list); sp.revalidate(); sp.repaint(); } } }); gbc.insets = new Insets(10, 10, 10, 10); JLabel searchLabel = new JLabel("Search: "); add(searchLabel, gbc); gbc.gridx = 1; gbc.gridy = 0; add(searchBar, gbc); gbc.gridx = 2; gbc.gridy = 0; add(btnBack, gbc); JLabel results = new JLabel("Search Results"); GridBagConstraints lgbc = new GridBagConstraints(); lgbc.gridx = 1; lgbc.gridy = 1; lgbc.insets = new Insets(20, 10, 10, 0); add(results, lgbc); gbc.gridx = 1; gbc.gridy = 2; gbc.insets = new Insets(0, 10, 10, 10); sp.setPreferredSize(new Dimension(200, 200)); add(sp, gbc); //Add JScrollPane JPanel buttonPanel = new JPanel(new GridBagLayout()); GridBagConstraints bpgbc = new GridBagConstraints(); bpgbc.gridx = 0; bpgbc.gridy = 0; bpgbc.insets = new Insets(10, 10, 10, 10); buttonPanel.add(btnSearchByFirstname, bpgbc); bpgbc.gridx = 0; bpgbc.gridy = 1; bpgbc.insets = new Insets(10, 10, 10, 10); buttonPanel.add(btnSearchByLastname, bpgbc); bpgbc.gridx = 0; bpgbc.gridy = 2; bpgbc.insets = new Insets(10, 10, 10, 10); buttonPanel.add(btnSearchByEmail, bpgbc); bpgbc.gridx = 0; bpgbc.gridy = 3; bpgbc.insets = new Insets(10, 10, 10, 10); buttonPanel.add(btnSearchBySerialNumber, bpgbc); gbc.gridx = 2; gbc.gridy = 2; gbc.insets = new Insets(0, 10, 10, 10); add(buttonPanel, gbc); pack(); setLocationRelativeTo(null); } }
true
0abad985205235f0d2c1e033530696d6b281c68d
Java
joshmarinacci/aminojava
/src/org/joshy/gfx/stage/jogl/JOGLStage.java
UTF-8
8,303
2.234375
2
[]
no_license
package org.joshy.gfx.stage.jogl; import com.sun.opengl.util.FPSAnimator; import org.joshy.gfx.node.Node; import org.joshy.gfx.node.control.Control; import org.joshy.gfx.node.layout.Container; import org.joshy.gfx.node.layout.Panel; import org.joshy.gfx.stage.AWTEventPublisher; import org.joshy.gfx.stage.Camera; import org.joshy.gfx.stage.OrthoCamera; import org.joshy.gfx.stage.Stage; import org.joshy.gfx.util.PerformanceTracker; import org.joshy.gfx.util.u; import javax.media.opengl.*; import javax.media.opengl.awt.GLCanvas; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * A stage implementation for the JOGL graphics stack */ public class JOGLStage extends Stage { GLCanvas canvas; private JOGLFrame frame; private FPSAnimator animator; private AWTEventPublisher publisher; Container parent; private GLCapabilities caps; protected Node content; private int minimumWidth; private int minimumHeight; boolean use3DCamera = false; Camera camera = new OrthoCamera(); public JOGLStage(boolean use3DCamera) { this.use3DCamera = use3DCamera; parent = new Panel() { public Stage getStage() { return JOGLStage.this; } }; frame = new JOGLFrame(this); frame.setSize(500,500); caps = new GLCapabilities(null); //turn on anti-aliasing full screen //caps.setSampleBuffers(true); //caps.setNumSamples(4); canvas = new GLCanvas(caps); canvas.addGLEventListener(frame); publisher = new AWTEventPublisher(parent); canvas.addMouseListener(publisher); canvas.addMouseMotionListener(publisher); canvas.addKeyListener(publisher); canvas.requestFocus(); frame.add(canvas); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); animator = new FPSAnimator(canvas,60, true); animator.setRunAsFastAsPossible(false); animator.start(); } public JOGLStage() { this(false); } @Override public void setContent(Node node) { this.content = node; parent.add(node); } @Override public Node getContent() { return this.content; } @Override public void setCamera(Camera camera) { this.camera = camera; } @Override public void setWidth(double width) { this.frame.setSize((int)width,this.frame.getHeight()); } @Override public void setHeight(double height) { this.frame.setSize(this.frame.getWidth(), (int) height); } @Override public double getX() { return frame.getX(); } @Override public void setX(double v) { //To change body of implemented methods use File | Settings | File Templates. } @Override public double getY() { return frame.getY(); } @Override public void setY(double v) { //To change body of implemented methods use File | Settings | File Templates. } @Override public double getWidth() { return 0; } @Override public void setMinimumWidth(double width) { this.minimumWidth = (int) width; this.frame.setMinimumSize(new Dimension(minimumWidth,minimumHeight)); } @Override public void setMinimumHeight(double height) { this.minimumHeight = (int) height; this.frame.setMinimumSize(new Dimension(minimumWidth,minimumHeight)); } @Override public Container getPopupLayer() { return null; } @Override public Object getNativeWindow() { return frame; } @Override public void setTitle(CharSequence title) { frame.setTitle(title.toString()); } @Override public void setUndecorated(boolean undecorated) { } @Override public void hide() { frame.setVisible(false); } @Override public void raiseToTop() { frame.setVisible(true); frame.toFront(); } @Override public Stage setId(String id) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void centerOnScreen() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void setFullScreen(boolean fullScreen) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void setOpacity(double v) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void setAlwaysOnTop(boolean b) { //To change body of implemented methods use File | Settings | File Templates. } @Override public double getHeight() { return 0; } } class JOGLFrame extends Frame implements GLEventListener { private JOGLStage stage; private boolean layoutDirty; private boolean skinsDirty = true; JOGLFrame(JOGLStage stage) throws HeadlessException { this.stage = stage; } private void doSkins() { PerformanceTracker.getInstance().skinStart(); if(stage.content != null) { if(stage.content instanceof Control) { Control c = (Control) stage.content; c.doSkins(); } } PerformanceTracker.getInstance().skinEnd(); } private void doGFXLayout(int width, int height) { PerformanceTracker.getInstance().layoutStart(); if(stage.content != null) { if(stage.content instanceof Control) { Control c = (Control) stage.content; c.setWidth(width); c.setHeight(height); c.doLayout(); } } PerformanceTracker.getInstance().layoutEnd(); } public void init(GLAutoDrawable glAutoDrawable) { glAutoDrawable.getGL().setSwapInterval(1); glAutoDrawable.setAutoSwapBufferMode(true); GL2 gl = glAutoDrawable.getGL().getGL2(); double w = getWidth(); double h = getHeight()-getInsets().top; stage.camera.configureDisplay(gl,stage,w,h); //turn on anti-aliasing for smooth lines gl.glEnable(GL.GL_LINE_SMOOTH); gl.glEnable(GL2.GL_POLYGON_SMOOTH); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendFunc(GL.GL_LINE_SMOOTH_HINT, GL.GL_DONT_CARE); } public void display(GLAutoDrawable drawable) { PerformanceTracker.getInstance().drawStart(); if(skinsDirty) { doSkins(); skinsDirty = false; } if(layoutDirty) { doGFXLayout(stage.canvas.getWidth(),stage.canvas.getHeight()); layoutDirty = false; } //clear the screen GL2 gl = drawable.getGL().getGL2(); //gl.glEnable(GL.GL_DEPTH_TEST); //gl.glClear(GL.GL_COLOR_BUFFER_BIT); //set up normal projection mode //gl.glMatrixMode(GL2ES1.GL_PROJECTION); //gl.glLoadIdentity(); double w = getWidth(); double h = getHeight()-getInsets().top; stage.camera.configureDisplay(gl,stage,w,h); if(stage.content != null) { JOGLGFX gfx = new JOGLGFX(drawable); stage.content.draw(gfx); gfx.dispose(); } PerformanceTracker.getInstance().drawEnd(); } public void reshape(GLAutoDrawable glAutoDrawable, int x, int y, int width, int height) { u.p("reshape called"); GL2 gl = glAutoDrawable.getGL().getGL2(); stage.camera.configureDisplay(gl,stage,width,height); /* gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL2ES1.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(0.0, getWidth(), getHeight(), 0.0, -100.0, 100.0); gl.glMatrixMode(GL2ES1.GL_MODELVIEW); gl.glLoadIdentity();*/ layoutDirty = true; } public void dispose(GLAutoDrawable glAutoDrawable) { } }
true
f8b7f88ef52559573ebf9c51960b4414a1b4130c
Java
confuse0/kaffatech-latte
/code/src/main/java/com/kaffatech/latte/ctx/id/sharding/impl/DbShardingIdGetter.java
UTF-8
2,571
2.296875
2
[]
no_license
package com.kaffatech.latte.ctx.id.sharding.impl; import com.kaffatech.latte.commons.bean.model.type.BooleanType; import com.kaffatech.latte.commons.net.util.IpAddressUtils; import com.kaffatech.latte.commons.toolkit.base.StringUtils; import com.kaffatech.latte.ctx.base.SystemProperties; import com.kaffatech.latte.ctx.id.model.ShardingId; import com.kaffatech.latte.ctx.id.sharding.ShardingIdGetter; import com.kaffatech.latte.ctx.id.util.IdGeneratorUtils; import com.kaffatech.latte.db.accessor.DbAccessor; import javax.annotation.Resource; import java.util.Date; /** * @author lingzhen on 16/11/24. */ public class DbShardingIdGetter implements ShardingIdGetter { @Resource private DbAccessor dbAccessor; private static final String QUERY_SHARDING_ID_SQL = "select * from SHARDING_ID where CLUSTER_NAME = ? and SERVER_NAME = ?"; private static final String INSERT_SHARDING_ID_SQL = "insert into SHARDING_ID (ID, CLUSTER_NAME, SERVER_NAME, CREATE_TIME, UPDATE_TIME, DELETE_FLAG) values (?, ?, ?, ?, ?, ?)"; @Override public long getShardingId() { Object[] queryParameter = new Object[]{getClusterName(), IpAddressUtils.getHostAddress()}; ShardingId shardingId = dbAccessor.queryForObject(QUERY_SHARDING_ID_SQL, queryParameter, ShardingId.class); if (shardingId == null) { // 以前没有过,需要产生新的ID shardingId = generate(); } IdGeneratorUtils.validateShardingId(shardingId.getId()); return shardingId.getId(); } /** * 产生新的ID(需要在一个事务里) * * @return */ private ShardingId generate() { ShardingId shardingId = new ShardingId(); shardingId.setClusterName(getClusterName()); shardingId.setServerName(IpAddressUtils.getHostAddress()); long nextSequence = dbAccessor.nextSequence("SEQ_SHARDING_ID"); shardingId.setId(nextSequence); shardingId.setCreateTime(new Date()); shardingId.setUpdateTime(shardingId.getCreateTime()); shardingId.setDeleteFlag(BooleanType.NO); // 插入数据 dbAccessor.update(INSERT_SHARDING_ID_SQL, shardingId.getId(), shardingId.getClusterName(), shardingId.getServerName(), shardingId.getCreateTime(), shardingId.getUpdateTime(), shardingId.getDeleteFlag().getCode()); return shardingId; } private String getClusterName() { String clusterName = SystemProperties.getClusterName(); return StringUtils.isEmpty(clusterName) ? "ANONYMITY" : clusterName; } }
true
5a0397acda07a2748ce4a9c2ce983a8979a67077
Java
sky027/request-java
/src/main/java/com/school/controller/DepartmentController.java
UTF-8
1,010
2.375
2
[]
no_license
package com.school.controller; import com.school.service.DepartmentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class DepartmentController { @Autowired private DepartmentService departmentService; @GetMapping("/department/{id}") @CrossOrigin("*") /*public ResponseEntity<Department> getDepartment(@PathVariable Integer id) { Department department = departmentService.getDepartmentByID(id) .orElseThrow(DepartmentService.DepartmentNotFoundException::new); return ResponseEntity.ok(department); }*/ public String getDepartment(@PathVariable Integer id) { return "123"; } } /* departmentService.xxx(); 正常代码执行流程 */
true
7d54a3a103e13e352ec0eb7b7b02f2b2fd64bdfa
Java
Bielsaar/backMilharinfra
/src/main/java/br/edu/ifpb/bielsaar/milharinfra/services/CarrinhoService.java
UTF-8
1,862
2.40625
2
[]
no_license
package br.edu.ifpb.bielsaar.milharinfra.services; import br.edu.ifpb.bielsaar.milharinfra.model.Carrinho; import br.edu.ifpb.bielsaar.milharinfra.repositories.CarrinhoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; @Service public class CarrinhoService { @Autowired private CarrinhoRepository carrinhoRepository; public List<Carrinho> getCarrinho(){ List<Carrinho> aux = this.carrinhoRepository.findAll(); return aux ; } public Carrinho getCarrinhoPorId(Long idProdutoCarrinho) { return this.carrinhoRepository.findById(idProdutoCarrinho).orElse(null); } public boolean existeProdutoCarrinho(Long idProdutoCarrinho) { return this.carrinhoRepository.existsById(idProdutoCarrinho); } @Transactional public Carrinho inserirAoCarrinho (Carrinho carrinho) { Carrinho produtoCarrinho = this.carrinhoRepository.findByNome(carrinho.getNome()); System.out.println("carrinho"); if (produtoCarrinho != null){ produtoCarrinho.adicionarQuantidadeCarrinho(); } Carrinho carrinhoInserido = this.carrinhoRepository.save(carrinho); return carrinhoInserido; } @Transactional public Carrinho atualizarProdutoCarrinho (Carrinho carrinho){ System.out.println(carrinho.getQuantCarrinho()); Carrinho produtoCarrinho = this.carrinhoRepository.findByNome(carrinho.getNome()); if (produtoCarrinho == null){ throw new RuntimeException("Não existe esse produto no carrinho"); } return this.carrinhoRepository.save(carrinho); } public void apagarProdutoCarrinhoPorId (Long id) { this.carrinhoRepository.deleteById(id); } }
true
9af85397c49a692f79ff8e5b1f285dafe5fb2bdf
Java
DmitryDudin/JavaLibraries
/JavaClassParsers/src/test/java/ua/com/javatraining/ReflectionsTest.java
UTF-8
1,401
2.140625
2
[]
no_license
package ua.com.javatraining; import org.junit.Test; import org.reflections.ReflectionUtils; import org.reflections.Reflections; import org.reflections.serializers.JavaCodeSerializer; import java.io.IOException; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; public class ReflectionsTest { @Test public void name() throws IOException, ClassNotFoundException { Reflections reflections = new Reflections(TestClassForParsing.class); System.out.println(reflections.toString()); // String str = reflections.; // reflections.save("D:\\projects\\archive\\JavaLibraries\\JavaClassParsers\\/ReflectionsTestFile.txt"); reflections.save("D:\\projects\\archive\\JavaLibraries\\JavaClassParsers\\/ReflectionsTestJava", new JavaCodeSerializer()); // final Class<?> aClass = JavaCodeSerializer.resolveClass(TestClassForParsing.class); // final Class<?> aClass = JavaCodeSerializer.resolveClassOf(TestClassForParsing.class); // System.out.println(aClass); // System.out.println(new JavaCodeSerializer().toString(reflections)); } @Test public void reflectionUtilsTests() { final Set<Method> allMethods = ReflectionUtils.getAllMethods(TestClassForParsing.class); System.out.println(allMethods); } }
true
88828b3eb295f3c015135525b1d24fe0b70cc6e5
Java
veronicaMG4/examen-prueba_java
/examenprueba/src/examenprueba/E4_TrainnMetodosForma1.java
ISO-8859-1
3,243
3.609375
4
[]
no_license
package examenprueba; public class E4_TrainnMetodosForma1 { private static final String String = null; // ATRIBUTOS private String tipo; private String referencia; private int asientosOcupados; private int aosActivo; // CONSTRUCTOR para pasar valores al main public E4_TrainnMetodosForma1(String tipo, String referencia, int asientosOcupados, int aosActivo) { this.tipo = tipo; this.referencia = referencia; this.asientosOcupados = asientosOcupados; this.aosActivo = aosActivo; } // METODO PARA MOSTRAR LO QUE HAY EN EL CONSTRUCTOR //___________________________________________________________________________________________________________________ public void mostrarDatos() { System.out.println("DATOS TREN: " + "TIPO:" + tipo + " REFERENCIA:" + referencia + " OCUPADOS:" + asientosOcupados + " AOS TRABAJADOS:" + aosActivo); } public String mostrarDatos2() { return "Tren [tipo=" + tipo + "referencia=" + referencia + ", asientosOcupados=" + asientosOcupados + ", aosActivo=" + aosActivo + "]"; } public void mostrarDatos3() { System.out.println("DATOS TREN: " + "TIPO:" + tipo + " REFERENCIA:" + referencia + " OCUPADOS:" + asientosOcupados + " AOS TRABAJADOS:" + aosActivo); } // GETTERS Y SETTERS para establecer valores y mostrarlos en el main public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public String getReferencia() { return referencia; } public void setReferencia(String referencia) { this.referencia = referencia; } public int getAsientosOcupados() { return asientosOcupados; } public void setAsientosOcupados(int asientosOcupados) { this.asientosOcupados = asientosOcupados; } public int getAosActivo() { return aosActivo; } public void setAosActivo(int aosActivo) { this.aosActivo = aosActivo; } // METODO PARA SABER SI ESTA LLENO. ESTA LLENO SI LLEGA A 400. //_____________________________________________________________________________________________________ //forma1 public boolean trenlleno() { boolean resul; if (this.asientosOcupados > 400) { resul = true; } else { resul = false; } return resul; } //forma2 public String trenlleno2() { String lleno; if (this.asientosOcupados > 400) { lleno = "El tren esta al completo**"; } else { lleno = "El tren no esta al completo**"; } return lleno; } //AOS TRABAJADOS POR EL TREN //___________________________________________________________________________________________ public String aostrabajados() { String aos; if (this.aosActivo > 40) { aos = "El tren es viejo y esta fuera de circulacion*"; } else { aos = "El tren es joven y esta en circulacion*"; } return aos; } public void aostrabajados2() { if (this.aosActivo > 40) { System.out.println("VIEJO"); } else { System.out.println("JOVEN"); } System.out.println("fdfdsfsfdsf"); }//main }//class
true
47226805f5635718d127ecafe2dd8853287c936d
Java
BonDyka/sarafan
/src/main/java/loc/abondare/sarafan/service/config/SarafanDelegatingOAut2UserService.java
UTF-8
1,800
2.234375
2
[ "Apache-2.0" ]
permissive
package loc.abondare.sarafan.service.config; import loc.abondare.sarafan.domain.User; import loc.abondare.sarafan.repo.UserDetailsRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.client.userinfo.DelegatingOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.user.OAuth2User; import java.time.LocalDateTime; import java.util.List; import java.util.Objects; public class SarafanDelegatingOAut2UserService extends DelegatingOAuth2UserService { @Autowired private UserDetailsRepo userDetailsRepo; /** * Constructs a {@code DelegatingOAuth2UserService} using the provided parameters. * * @param oAuth2UserService a {@code List} of {@link OAuth2UserService}(s) */ public SarafanDelegatingOAut2UserService(List oAuth2UserService) { super(oAuth2UserService); } @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); String id = Objects.requireNonNull(oAuth2User.getAttribute("sub")); User user = userDetailsRepo.findById(id).orElseGet(() -> { User newUser = new User(); newUser.setId(id); newUser.setName(oAuth2User.getAttribute("name")); newUser.setEmail(oAuth2User.getAttribute("email")); return newUser; }); user.setLastVisit(LocalDateTime.now()); userDetailsRepo.save(user); return oAuth2User; } }
true
a94d4733a6799a9d5ef3fdb6e6a582c954f3421d
Java
Vughalla/ORT-TPI
/src/unidad2_ej1/Persona.java
UTF-8
1,391
3.46875
3
[]
no_license
package unidad2_ej1; import java.util.ArrayList; public class Persona { private String nombre; private String apellido; private ArrayList<NumeroTelefonico> telefonos; private ArrayList<Email> mails; public Persona(String nombre, String apellido) { setNombre(nombre); setApellido(apellido); telefonos = new ArrayList<NumeroTelefonico>(); mails = new ArrayList<Email>(); } public void mostrarTodo() { System.out.println(this.getApellido() + ", " + this.getNombre() + "\nTelefonos:"); for (NumeroTelefonico tel: telefonos) { String tipoTel = ""; if (tel.getTipoLinea() == TipoDeLinea.CELULAR) { tipoTel = "Celular"; } else if (tel.getTipoLinea() == TipoDeLinea.FIJO) { tipoTel = "Fijo"; } else if (tel.getTipoLinea() == TipoDeLinea.FAX) { tipoTel = "Fax"; } System.out.print(tipoTel + ": " +tel.getValor() + " "); } for (Email mail: mails) { System.out.print("email: " +mail.getValor() + " "); } } public void agregarCorreo(Email email) { mails.add(email); } public void agregarTelefono(NumeroTelefonico telefono) { telefonos.add(telefono); } private void setNombre(String nombre) { this.nombre = nombre; } private void setApellido(String apellido) { this.apellido = apellido; } private String getNombre() { return this.nombre; } private String getApellido() { return this.apellido; } }
true
b72df2741139d72a522c3cb3c293b9dc9d0415ea
Java
bennysch/accessability
/src/com/btp/accessability/data/Item.java
UTF-8
339
1.5
2
[]
no_license
package com.btp.accessability.data; public class Item { public int itemId; public int duplicateId; public String canDuplicate; public int sheetId; public int sectionId; public String itemShortText; public String ItemLongText; public String takin; public String ItemComment; public boolean doPhoto; public boolean doMeasure; }
true
07de5ccb2cbac6733785e35ce720e87e8a803f7e
Java
rahulreddy99/public
/pa/src/main/java/SampleProject/Son.java
UTF-8
387
2.375
2
[]
no_license
package SampleProject; public class Son extends GrandFather { public static void main(String[] args) { // TODO Auto-generated method stub Son s = new Son(); s.city(); System.out.println(s); s.country(); System.out.println(s); System.out.println(s.i); } public void cityactivited(){ System.out.println("cityactivites"); } }
true
926e3e7f761df0e3a909ff264e5acae8965cfa79
Java
Trixyz28/ing-sw-2020-Yang-Yu-Zhu
/src/test/java/it/polimi/ingsw/model/God/MinotaurTest.java
UTF-8
2,231
2.75
3
[]
no_license
package it.polimi.ingsw.model.God; import it.polimi.ingsw.model.Board; import it.polimi.ingsw.model.Player; import it.polimi.ingsw.model.Tile; import it.polimi.ingsw.model.Turn; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; public class MinotaurTest extends TestCase { Conditions conditions = new Conditions(); Board board = new Board(); ArrayList<UndecoratedWorker> totalWorkerList = new ArrayList<>(); Minotaur worker = new Minotaur(new NoGod(1, conditions),totalWorkerList); UndecoratedWorker minotaur; UndecoratedWorker athena; @Before public void initialize() { athena = new Athena(new NoGod(0, conditions)); minotaur = new Minotaur(new NoGod(1, conditions),totalWorkerList); totalWorkerList.add(worker); totalWorkerList.add(minotaur); totalWorkerList.add(athena); worker.setPosition(board.getTile(2,2)); minotaur.setPosition(board.getTile(1,2)); athena.setPosition(board.getTile(3,3)); } @Test public void testCanMove() { initialize(); Assert.assertTrue(worker.canMove(board.getTile(1,1))); /* worker (2,2) can push athena to (4,4) */ Assert.assertTrue(worker.canMove(athena.getPosition())); /* minotaur worker cannot push another minotaur worker */ Assert.assertFalse(worker.canMove(minotaur.getPosition())); /* set forcedTile not available to move */ board.getTile(4,4).setDomePresence(true); /* athena can't be pushed */ Assert.assertFalse(worker.canMove(athena.getPosition())); /* change athena position */ athena.setPosition(board.getTile(0,2)); /* athena can't be pushed -> forced tile doesn't exist */ Assert.assertFalse(minotaur.canMove(athena.getPosition())); } @Test public void testMove() { initialize(); /* worker (2,2) moves to (3,3), athena must be pushed to (4,4) */ worker.move(athena.getPosition()); Assert.assertEquals(board.getTile(4,4),athena.getPosition()); Assert.assertEquals(board.getTile(3,3),worker.getPosition()); } }
true
507c2ffa338337470f8c8640affbb0deb0de0781
Java
ProisSimon97/Template-Method-Composite
/ejercicio3/ar/unrn/tp5/modelo/Gestion.java
UTF-8
295
2.078125
2
[]
no_license
package ar.unrn.tp5.modelo; public interface Gestion { public double calcularCostoDePaquete(); public void agregarSeguro(Gestion seguro); public int contarSeguros(); public double calcularCostoSinDescuento(); double calcularCostoConDescuentoDePaqueteDePaquetes(); }
true
08dfc7267af9bbc5b1c50be66a8cec2bd635f8a9
Java
Melick237/Pizzaria_Management_System
/gui/de/thb/dim/pizzaProntoGUI/view/SidePanelButton.java
UTF-8
756
2.40625
2
[]
no_license
package de.thb.dim.pizzaProntoGUI.view; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JButton; @SuppressWarnings("serial") public class SidePanelButton extends JButton{ public SidePanelButton(String text, String img) { setText(text); setIcon(new ImageIcon(img)); setOpaque(true); setBorderPainted(false); setFocusPainted(false); setFont(new Font("Arial", Font.PLAIN, 14)); setForeground(new Color(0x999999)); setVerticalTextPosition(AbstractButton.BOTTOM); setHorizontalTextPosition(AbstractButton.CENTER); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); setContentAreaFilled(false); setIconTextGap(16); } }
true
e5782dc091ee307419dd0d2d20641f922480f7e9
Java
malinghan/interview
/springs/src/main/java/com/someecho/spring03/Test.java
UTF-8
374
2.078125
2
[]
no_license
package com.someecho.spring03; /** * @author : linghan.ma * @Package com.someecho.spring03 * @Description: * @date Date : 2020年11月17日 4:25 AM **/ public interface Test { @Transaction public void method1(); @Log public void method2(); @Transaction @Log public void method3(); @Log @Transaction public void method4(); }
true
7dabedceeffe599a5ddfdd164aa03bcbb2c26f65
Java
davajdosvidaniya/CraiglistCrawler
/MarijuanaCrawler/src/marijuanaCrawler/CraiglistLocationLinkCrawl.java
UTF-8
3,996
2.578125
3
[]
no_license
package marijuanaCrawler; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import commonlib.Globals; import commonlib.Location; import commonlib.NetworkingFunctions; import dbconnection.DAOFactory; import dbconnection.LocationLink; import dbconnection.LocationLinkDAO; import dbconnection.LocationLinkDAOJDBC; public class CraiglistLocationLinkCrawl { private final int numRetryDownloadPage = 2; private final String startLink = "http://www.craigslist.org/about/sites"; private Map<String, Location> linkToLocationMap = null; public CraiglistLocationLinkCrawl() { this.linkToLocationMap = new HashMap<String, Location>(); } public Map<String, Location> getLinkToLocationMap() { return this.linkToLocationMap; } public boolean getLink() throws Exception { Document doc = NetworkingFunctions.downloadHtmlContentToDoc(this.startLink, this.numRetryDownloadPage); if (doc == null) { return false; } Elements countryElems = doc.select("div[class=colmask]"); // Return if the page has no country div if (countryElems.size() == 0) { Globals.crawlerLogManager.writeLog("No country element"); return false; } // US elem is the first one Element usCountryElem = countryElems.get(0); Elements stateNameElems = usCountryElem.select("h4"); Elements stateCitiesElems = usCountryElem.select("ul"); Globals.crawlerLogManager.writeLog("Found " + stateNameElems.size() + " state names and " + stateCitiesElems.size() + " state elems"); if (stateNameElems.size() != stateCitiesElems.size()) return false; if (stateNameElems.size() == 0) return false; int numStates = stateNameElems.size(); // Iterate through each state listed in craiglist for (int i = 0; i < numStates; i++) { String stateName = stateNameElems.get(i).text().trim(); Globals.crawlerLogManager.writeLog("State "+stateName + ":"); Elements citiesElems = stateCitiesElems.get(i).select("li"); int numCitiesInStates = citiesElems.size(); Globals.crawlerLogManager.writeLog("Has "+numCitiesInStates+" cities/locations"); // Iterate through each city of the current state for (int j = 0; j < numCitiesInStates; j++) { // TODO use city name when we have location based index String cityName = citiesElems.get(j).text().trim(); String link = citiesElems.get(j).select("a").attr("href") .toString(); Globals.crawlerLogManager.writeLog(cityName + ": " + link); Location loc = new Location(); loc.country = "US"; loc.state = stateName; loc.city = cityName; this.linkToLocationMap.put(link, loc); } } return true; } public static void main(String[] args) throws Exception { CraiglistLocationLinkCrawl crawler = new CraiglistLocationLinkCrawl(); // Fail to get the craiglist location links try { if (!crawler.getLink()) { return; } } catch (IOException e) { Globals.crawlerLogManager.writeLog("Throw Exception " + e.getMessage()); return; } Map<String, Location> linkToLocationMap = crawler.getLinkToLocationMap(); if (linkToLocationMap == null) { return; } LocationLinkDAO locationLinkDAO = new LocationLinkDAOJDBC(DAOFactory.getInstance( Globals.username, Globals.password, Globals.server + Globals.database)); for (Map.Entry<String, Location> entry : linkToLocationMap.entrySet()) { String link = entry.getKey(); Location location = entry.getValue(); LocationLink locationLink = new LocationLink(); locationLink.setLink(link); locationLink.setCountry(location.country); locationLink.setState(location.state); locationLink.setCity(location.city); locationLinkDAO.create(locationLink); } } }
true
99976ddfd92380a94af8eae1d1e8243b79e09166
Java
sacchin/ToyBox
/TottoriCompass/src/com/gmail/sachin/tottoricompass/Constatns.java
UTF-8
380
1.828125
2
[]
no_license
package com.gmail.sachin.tottoricompass; public class Constatns { public final static double TOTTORI_LAT = 35.2912; public final static double TOTTORI_LNG = 134.1346; public final static int RIGHT = 200; public final static int LEFT = 240; public final static int CENTER = 83; public final static int IMAGE_HEIGHT = 301; public final static int IMAGE_WIDTH = 520; }
true
91dbd038c506142ca781a995c5e7b7257fffe6ee
Java
doobo/consoleshop
/src/com/qrsx/shop/dao/GoodsDao.java
UTF-8
435
1.757813
2
[]
no_license
package com.qrsx.shop.dao; import java.util.List; import com.qrsx.shop.vo.Goods; public interface GoodsDao { boolean initGoodsDao(); boolean addGoods(Goods goods); boolean isExitGoods(Goods goods); boolean saveGoods(); boolean updateGoods(Goods goods); boolean delGoods(Goods goods); Goods getGoodsById(int id); Goods getGoodsByName(String name); List<Goods> getAllGoods(); void sortById(); int getNextId(); }
true
a621bbcda875fa5df20728e2db44508ac982172e
Java
abhishekDautomator/JavaProgramsPractice
/practice/src/abundantNumber/AbundantNumber.java
UTF-8
562
3.640625
4
[]
no_license
package abundantNumber; import java.util.Scanner; public class AbundantNumber { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Enter an integer"); Scanner scn=new Scanner(System.in); int num=scn.nextInt(); int count=1,sum=0; while(count<=(num/2)) { if(num%count==0) sum+=count; count++; } if(sum>num) System.out.println("Entered no. is an abundant number"); else System.out.println("Entered no. is not an abundant number"); scn.close(); } }
true
8b18e45b7478eaff5f5f7810810da11715f0cf1e
Java
qi777zh/springcloud-2020
/cloud-feign-order80/src/main/java/com/qizhihen/springcloud/service/PaymentFeignService.java
UTF-8
675
1.859375
2
[]
no_license
package com.qizhihen.springcloud.service; import com.qizhihen.springcloud.controller.OrderFeignController; import com.qizhiheng.springcloud.entities.CommonResult; import com.qizhiheng.springcloud.entities.Payment; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Component @FeignClient(value = "CLOUD-SERVICE",fallback = OrderFeignController.class) public interface PaymentFeignService { @GetMapping("/payment/get/{id}") CommonResult<Payment> getPayment(@PathVariable("id") Long id); }
true
ff52649d8a9b7b96af2065f69ad4149f3832089a
Java
alasrati/mooc-java-part-1
/week1-012.SumOfTheAges/src/SumOfTheAges.java
UTF-8
871
4.03125
4
[]
no_license
import java.util.Scanner; public class SumOfTheAges { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Type your name: "); String name1 = reader.nextLine(); System.out.print("\n"); System.out.print("Type your age: "); int age1 = Integer.parseInt(reader.nextLine()); System.out.print("\n"); System.out.print("\n"); System.out.print("Type your name: "); String name2 = reader.nextLine(); System.out.print("\n"); System.out.print("Type your age: "); int age2 = Integer.parseInt(reader.nextLine()); int totalAge = age1 + age2; System.out.print("\n"); System.out.print("\n"); System.out.print(String.format("%s and %s are %s years old in total.", name1, name2, totalAge)); } }
true
7b1bb2731bf4f656f5308a8d2dacd3ff982c2937
Java
XCaine/MedicalPoint_app
/src/main/java/com/medical/json/deserializers/MedicalUnitDeserializer.java
UTF-8
1,457
2.734375
3
[]
no_license
package com.medical.json.deserializers; import com.google.gson.*; import com.medical.domain.MedicalUnit; import com.medical.domain.Specialty; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Set; public class MedicalUnitDeserializer implements JsonDeserializer<MedicalUnit> { @Override public MedicalUnit deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); MedicalUnit medicalUnit = new MedicalUnit(); if(jsonObject.get("id") != null) medicalUnit.setId(jsonObject.get("id").getAsInt()); if(jsonObject.get("name") != null) medicalUnit.setName(jsonObject.get("name").getAsString()); if(jsonObject.get("phoneNumber") != null) medicalUnit.setPhoneNumber(jsonObject.get("phoneNumber").getAsString()); if(jsonObject.get("specialties") != null){ Set<Specialty> specialties = new HashSet<Specialty>(); JsonArray specialtiesJsonArray = jsonObject.getAsJsonArray("specialties"); for(int i = 0; i<specialtiesJsonArray.size(); i++){ Specialty specialty = context.deserialize(specialtiesJsonArray.get(i), Specialty.class); specialties.add(specialty); } medicalUnit.setSpecialties(specialties); } return medicalUnit; } }
true
4d6e584830b3b2bfd31bcbf6a1b04db8c36e6686
Java
dqbigd/Penjualan-barang
/src/view/EntriPenjualan.java
UTF-8
18,700
1.960938
2
[]
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 view; import controller.Penjualanctrl; import controller.config; import java.sql.Connection; import javax.swing.DefaultListModel; /** * * @author kindreal */ public class EntriPenjualan extends javax.swing.JFrame { /** * Creates new form TambahBrg */ public EntriPenjualan() { initComponents(); listModel(); } Penjualanctrl pc = new Penjualanctrl(); int total = 0, subtot = 0, getrow; String kondisi = ""; private DefaultListModel listModel; /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); txtKodeBrg = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); txtNamaBrg = new javax.swing.JTextField(); txtHrgJual = new javax.swing.JTextField(); txtJumlahBrg = new javax.swing.JTextField(); btnTambah = new javax.swing.JButton(); txtKodeJual = new javax.swing.JTextField(); txtTglJual = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); btnSimpan = new javax.swing.JButton(); btnBatal = new javax.swing.JButton(); btnClose = new javax.swing.JButton(); lblTotalPenjualan = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList<>(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Cantarell", 1, 20)); // NOI18N jLabel1.setText("Entri Penjualan"); jLabel2.setText("Kode Penjualan"); jLabel3.setText("Tanggal Penjualan"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Barang")); jPanel1.setForeground(new java.awt.Color(37, 188, 238)); jLabel4.setText("Kode Barang"); jLabel5.setText("Nama Barang"); jLabel6.setText("Harga Jual"); jLabel7.setText("Jumlah"); btnTambah.setText("Tambah"); btnTambah.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnTambahActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7)) .addGap(58, 58, 58) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnTambah, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) .addComponent(txtJumlahBrg, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) .addComponent(txtKodeBrg) .addComponent(txtNamaBrg) .addComponent(txtHrgJual)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtKodeBrg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtNamaBrg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtHrgJual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtJumlahBrg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnTambah) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel8.setText("Total Penjualan"); btnSimpan.setText("Simpan"); btnSimpan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSimpanActionPerformed(evt); } }); btnBatal.setText("Batal"); btnBatal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBatalActionPerformed(evt); } }); btnClose.setText("Close"); btnClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCloseActionPerformed(evt); } }); lblTotalPenjualan.setFont(new java.awt.Font("Cantarell", 1, 18)); // NOI18N lblTotalPenjualan.setText("Rp. -"); jList1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jList1MouseClicked(evt); } }); jScrollPane1.setViewportView(jList1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(btnSimpan, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnBatal, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(110, 110, 110) .addComponent(btnClose, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblTotalPenjualan))))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(51, 51, 51) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtTglJual, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtKodeJual, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 263, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtKodeJual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtTglJual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addComponent(lblTotalPenjualan)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSimpan) .addComponent(btnBatal) .addComponent(btnClose)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed this.setVisible(false); Main mn = new Main(); mn.setVisible(true); }//GEN-LAST:event_btnCloseActionPerformed private void btnBatalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBatalActionPerformed bersihlah(); }//GEN-LAST:event_btnBatalActionPerformed private void btnSimpanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSimpanActionPerformed pc.simpan(txtKodeJual.getText(), txtTglJual.getText(),total ); bersihlah(); lblTotalPenjualan.setText("Rp.-"); }//GEN-LAST:event_btnSimpanActionPerformed private void btnTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTambahActionPerformed subtot = Integer.parseInt(txtHrgJual.getText()) * Integer.parseInt(txtJumlahBrg.getText()); pc.simpan_detail(txtKodeJual.getText(), txtKodeBrg.getText(), Integer.parseInt(txtHrgJual.getText()), Integer.parseInt(txtJumlahBrg.getText()), subtot); if (!kondisi.equals(txtKodeJual.getText())) { total = subtot; }else{ total = subtot + total; subtot = total; } kondisi = txtKodeJual.getText(); lblTotalPenjualan.setText("Rp."+total); txtKodeBrg.setText(""); txtNamaBrg.setText(""); txtHrgJual.setText(""); txtJumlahBrg.setText(""); }//GEN-LAST:event_btnTambahActionPerformed private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked getrow = jList1.getSelectedIndex(); //coming soon, mohon maaf pak }//GEN-LAST:event_jList1MouseClicked private void bersihlah(){ txtKodeJual.setText(""); txtTglJual.setText(""); txtKodeBrg.setText(""); txtNamaBrg.setText(""); txtHrgJual.setText(""); txtJumlahBrg.setText(""); } private void listModel(){ listModel = new DefaultListModel(); try { String sql = "select * from barang"; java.sql.Connection conn=(Connection)config.configDB(); java.sql.Statement stm=conn.createStatement(); java.sql.ResultSet res=stm.executeQuery(sql); while(res.next()){ listModel.addElement(res.getString("id")+" - "+res.getString("nama")+" Rp."+res.getString("hrg_jual")); } jList1.setModel(listModel); } catch (Exception e) { } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EntriPenjualan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EntriPenjualan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EntriPenjualan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EntriPenjualan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EntriPenjualan().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBatal; private javax.swing.JButton btnClose; private javax.swing.JButton btnSimpan; private javax.swing.JButton btnTambah; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JList<String> jList1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblTotalPenjualan; private javax.swing.JTextField txtHrgJual; private javax.swing.JTextField txtJumlahBrg; private javax.swing.JTextField txtKodeBrg; private javax.swing.JTextField txtKodeJual; private javax.swing.JTextField txtNamaBrg; private javax.swing.JTextField txtTglJual; // End of variables declaration//GEN-END:variables }
true
db73d8b3e3dd6f2dd1a93e9dcffdbee4efa202fc
Java
dpeworch/socialNetwork
/User.java
UTF-8
3,020
3.1875
3
[]
no_license
package socialnetwork; import java.util.ArrayList; import java.util.Iterator; public class User { private int id; private String username; private String password; private String email; private ArrayList<Integer> subscriptions; public User(int id, String username, String password, String email, ArrayList<Integer> subscriptions) { this.id = id; this.username = username; this.password = password; this.email = email; this.subscriptions = subscriptions; } /** * Access the user's ID. * @return the user's ID */ public int getUserId() { return id; } /** * Access the user's username. * @return the user's username */ public String getUsername() { return username; } /** * Access the user's password. * @return the user's password */ public String getPassword() { return password; } /** * Access the user's email address. * @return the user's email address */ public String getEmail() { return email; } /** * Access the user's subscriptions. * @return the user's subscriptions, as an ArrayList */ public ArrayList<Integer> getSubsAsArrayList() { return subscriptions; } /** * Access the user's subscriptions. * @param numSubs the number of subscriptions wanted (takes most recent) * @return the user's subscriptions, as an array */ public int[] getSubsAsArray(int numSubs) { int[] allSubs = new int[subscriptions.size()]; int counter = allSubs.length - 1; Iterator<Integer> i = subscriptions.listIterator(); while (i.hasNext()) { allSubs[counter] = i.next(); counter --; } int[] subs = new int[numSubs]; while (counter < numSubs && counter < allSubs.length) { subs[counter] = allSubs[counter]; counter ++; } return subs; } /** * Determines if the user has subscribed to a specified user. * @param userID the specified user's ID * @return true if the user has subscribed to the specified user, otherwise false */ public boolean subscribesTo(int userID) { Iterator<Integer> i = subscriptions.listIterator(); while (i.hasNext()) { if (i.next() == userID) { return true; } } return false; } //moved to database public void addSub(int subid){ subscriptions.ensureCapacity(subscriptions.size() + 1); subscriptions.add(subid); } //moved to database public void addManySubs(int[] subids){ subscriptions.ensureCapacity(subscriptions.size() + subids.length); for(int i=0; i<subids.length; i++){ subscriptions.add(subids[i]); } } }
true
71faf1bf80787810fc9c50afe400979ffb1cd3af
Java
vinicius3333/CodeFights
/The_Core/At_the_Crossroads/Reach_Next_Level.java
UTF-8
1,490
3.59375
4
[]
no_license
package CodeFights.The_Core.At_the_Crossroads; /*** ---Pergunta/ Question--- You are playing an RPG game. Currently your experience points (XP) total is equal to experience. To reach the next level your XP should be at least at threshold. If you kill the monster in front of you, you will gain more experience points in the amount of the reward. Given values experience, threshold and reward, check if you reach the next level after killing the monster. Você está jogando um jogo de RPG. Atualmente, seu total de pontos de experiência (XP) é igual a experiência. Para alcançar o próximo nível, seu XP deve estar pelo menos no limiar. Se você matar o monstro à sua frente, você ganhará mais pontos de experiência no valor da recompensa. Dados valores, experiência, limite e recompensa, verifique se você alcança o próximo nível depois de matar o monstro. ---Comentários/ Comments--- Make an algorithm that returns if it is possible to pass the number of the threshold variable with the variable experience and reward together. Faça um algoritmo que retorne se é possível passar o número da váriavel threshold com a variável experience e reward juntas. ***/ public class Reach_Next_Level { public static void main(String[] args){ System.out.println(reachNextLevel(10, 15, 5)); } static boolean reachNextLevel(int experience, int threshold, int reward) { return experience + reward >= threshold; } }
true
fdac0ba31030786f88bf6edbab39b8820e9b160a
Java
pspiu/coding_area
/springMVCPractice/mvc-model-view-controller-project/src/com/home/mycafe/controller/MyCafeController.java
UTF-8
962
2.609375
3
[]
no_license
package com.home.mycafe.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyCafeController { @RequestMapping("/cafe") public String showWelcomePage(Model model) { /*priya: example to send data to view * sending data to view (jsp page)*/ /* String myName="Priya"; String cafeName="Mom's Cafe"; model.addAttribute("myNameValue",myName); model.addAttribute("myCafeName",cafeName); */ return "welcome-page"; } @RequestMapping("/processOrder") public String processOrder(HttpServletRequest request,Model model) { //set user data using Model data ans send it to concerned view String userInput=request.getParameter("foodType"); //same as input name in welcome-page.jsp model.addAttribute("userInput",userInput); return "process-order"; } }
true
95514d1a8477a3f78ced033ec82cf00ad21f2a1f
Java
dionis09/project
/src/main/java/com/example/project/model/Address.java
UTF-8
642
2.25
2
[]
no_license
package com.example.project.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; @Getter @Setter @SuperBuilder @AllArgsConstructor @NoArgsConstructor public class Address extends ObjectMongo{ private String street = ""; private String houseNumber = ""; private String zipCode = ""; private String city = ""; private String country = ""; @Override public String toString() { return street.replace(" ", "+") + ',' + houseNumber + ',' + zipCode + '+' + city + '+' + country; } }
true