text
stringlengths
10
2.72M
package com.lotus.controller; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.ConcurrentHashMap; import com.lotus.model.TweetDetails; import com.lotus.util.Lockobj; import com.lotus.util.Pair; public class Operations implements Controller { @Override public void parseTweet(TweetDetails tweet) { String username = tweet.getUsername(); String location = tweet.getLocation(); String hashtag = tweet.getHashtag(); String text = tweet.getText(); /* * System.out.println("username: " + username); System.out.println("location: " * + location); System.out.println("hashtag: " + hashtag); * System.out.println("text: " + text); * System.out.println("--------------------------------------------"); */ updateUserMap(username, hashtag); updateDistinctHasttag(hashtag); updateLocationTweetCount(location); saveTweet(tweet); } private synchronized void saveTweet(TweetDetails tweet) { LinkedList<TweetDetails> ll = null; if (userToTweet.containsKey(tweet.getUsername())) { ll = userToTweet.get(tweet.getUsername()); ll.add(tweet); } else { ll = new LinkedList<TweetDetails>(); ll.add(tweet); userToTweet.put(tweet.getUsername(), ll); } switch (ll.size()) { case 5: updateMileStoneUsers(new Pair<String, Integer>(tweet.getUsername(), 5)); break; case 6: updateMileStoneUsers(new Pair<String, Integer>(tweet.getUsername(), 6)); break; case 7: updateMileStoneUsers(new Pair<String, Integer>(tweet.getUsername(), 7)); break; default: break; } } private void updateUserMap(String username, String hashtag) { if (userToHashtagsMap.containsKey(username)) { ConcurrentHashMap<String, Integer> value = userToHashtagsMap.get(username); value.put(hashtag, value.getOrDefault(hashtag, 0) + 1); } else { ConcurrentHashMap<String, Integer> value = new ConcurrentHashMap<String, Integer>(); value.put(hashtag, 1); userToHashtagsMap.put(username, value); } } private void updateDistinctHasttag(String hashtag) { synchronized (top100hashtags) { hashtagCountMap.put(hashtag, hashtagCountMap.getOrDefault(hashtag, 0) + 1); int hashtagCount = hashtagCountMap.get(hashtag); if(top100hashtags.isEmpty()) { top100hashtags.add(new Pair<String,Integer>(hashtag, hashtagCount)); }else if(top100hashtags.peekLast().getSecond() >= hashtagCount) { if(top100hashtags.size() < 100) { top100hashtags.addLast(new Pair<String,Integer>(hashtag, hashtagCount)); } }else updateTrendingHashtags(hashtag, hashtagCount); } } private void updateTrendingHashtags(String hashtag, int count) { Iterator<Pair<String, Integer>> it = top100hashtags.iterator(); boolean notfound = true; Pair<String, Integer> p = null; while (it.hasNext()) { p = it.next(); if (p.getFirst().equalsIgnoreCase(hashtag)) { notfound = false; break; } } if (!notfound) { top100hashtags.remove(p); p.setSecond(count); if(!top100hashtags.isEmpty()) if(top100hashtags.isEmpty()) top100hashtags.add(p); else if ( p.getSecond() > top100hashtags.peekFirst().getSecond()) { top100hashtags.addFirst(p); } else { int index = 0; it = top100hashtags.iterator(); while (it.hasNext()) { Pair<String, Integer> temp = it.next(); if (temp.getSecond() <= p.getSecond()) { top100hashtags.add(index, p); return; } index++; } } } } private void updateLocationTweetCount(String location) { synchronized (locationTweetCountMap) { locationTweetCountMap.put(location, locationTweetCountMap.getOrDefault(location, 0) + 1); } } private void updateMileStoneUsers(Pair<String, Integer> p) { synchronized (milestoneUser) { milestoneUser.add(p); } } }
package com.as.boot.frame; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TextArea; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.ImageIcon; import javax.swing.JFrame; public class MiniTray { private static final long serialVersionUID = 1L; private static int i = 0; static int runTime = 0; static TextArea ta = new TextArea(); static boolean regStatus = false; private static TrayIcon trayIcon = null; static JFrame mf = new JFrame(); static SystemTray tray = SystemTray.getSystemTray(); public static void myFrame() { // 窗体 mf.setLocation(300, 100); mf.setSize(500, 300); mf.setTitle("XXXX系统"); mf.setLayout(new BorderLayout()); mf.setVisible(true);//使窗口可见 mf.addWindowListener(new WindowAdapter() { // 窗口关闭事件 public void windowClosing(WindowEvent e) { System.exit(0); }; public void windowIconified(WindowEvent e) { // 窗口最小化事件 mf.setVisible(false); MiniTray.miniTray(); } }); } private static void miniTray() { // 窗口最小化到任务栏托盘 ImageIcon trayImg = new ImageIcon("c://tyjkdb//leida.gif");// 托盘图标 PopupMenu pop = new PopupMenu();// 增加托盘右击菜单 MenuItem show = new MenuItem("show"); MenuItem exit = new MenuItem("exit"); show.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 按下还原键 tray.remove(trayIcon); mf.setVisible(true); mf.setExtendedState(JFrame.NORMAL); mf.toFront(); } }); exit.addActionListener(new ActionListener() { // 按下退出键 public void actionPerformed(ActionEvent e) { tray.remove(trayIcon); System.exit(0); } }); pop.add(show); pop.add(exit); trayIcon = new TrayIcon(trayImg.getImage(), "xxxx系统", pop); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { // 鼠标器双击事件 if (e.getClickCount() == 2) { tray.remove(trayIcon); // 移去托盘图标 mf.setVisible(true); mf.setExtendedState(JFrame.NORMAL); // 还原窗口 mf.toFront(); } } }); try { tray.add(trayIcon); } catch (AWTException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public static void main(String[] args) { MiniTray MiniTray = new MiniTray(); MiniTray.myFrame(); } }
package com.example.jpa.inter; import com.example.pojo.User; import org.springframework.data.jpa.repository.JpaRepository; public interface JpaUserRepository extends JpaRepository<User, Long> { }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.web.reactive.server.samples; import java.net.URI; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.containsString; /** * Samples of tests using {@link WebTestClient} with serialized JSON content. * * @author Rossen Stoyanchev * @author Sam Brannen * @since 5.0 */ class JsonContentTests { private final WebTestClient client = WebTestClient.bindToController(new PersonController()).build(); @Test void jsonContentWithDefaultLenientMode() { this.client.get().uri("/persons") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody().json(""" [ {"firstName":"Jane"}, {"firstName":"Jason"}, {"firstName":"John"} ] """); } @Test void jsonContentWithStrictMode() { this.client.get().uri("/persons") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody().json(""" [ {"firstName":"Jane", "lastName":"Williams"}, {"firstName":"Jason","lastName":"Johnson"}, {"firstName":"John", "lastName":"Smith"} ] """, true); } @Test void jsonContentWithStrictModeAndMissingAttributes() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.client.get().uri("/persons") .accept(MediaType.APPLICATION_JSON) .exchange() .expectBody().json(""" [ {"firstName":"Jane"}, {"firstName":"Jason"}, {"firstName":"John"} ] """, true) ); } @Test void jsonPathIsEqualTo() { this.client.get().uri("/persons") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody() .jsonPath("$[0].firstName").isEqualTo("Jane") .jsonPath("$[1].firstName").isEqualTo("Jason") .jsonPath("$[2].firstName").isEqualTo("John"); } @Test void jsonPathMatches() { this.client.get().uri("/persons/John/Smith") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody() .jsonPath("$.firstName").value(containsString("oh")); } @Test void postJsonContent() { this.client.post().uri("/persons") .contentType(MediaType.APPLICATION_JSON) .bodyValue(""" {"firstName":"John", "lastName":"Smith"} """) .exchange() .expectStatus().isCreated() .expectBody().isEmpty(); } @RestController @RequestMapping("/persons") static class PersonController { @GetMapping Flux<Person> getPersons() { return Flux.just(new Person("Jane", "Williams"), new Person("Jason", "Johnson"), new Person("John", "Smith")); } @GetMapping("/{firstName}/{lastName}") Person getPerson(@PathVariable String firstName, @PathVariable String lastName) { return new Person(firstName, lastName); } @PostMapping ResponseEntity<String> savePerson(@RequestBody Person person) { return ResponseEntity.created(URI.create(String.format("/persons/%s/%s", person.getFirstName(), person.getLastName()))).build(); } } static class Person { private String firstName; private String lastName; public Person() { } public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } } }
package dao; import java.util.List; import model.SupportingMaterial; public interface SupportingMaterialsInterface { public void insertSM(SupportingMaterial SM); public void updateSM(SupportingMaterial SM); public SupportingMaterial getSMByURL(String URL); public List<SupportingMaterial> getAllActiveSM(); public List<SupportingMaterial> getAllSM(); public void deleteSM(SupportingMaterial SM); }
package org.digdata.swustoj.util; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Test; public class FastJsonUtilTest { @Test public void transJson(){ Map<String, Object> map=new HashMap<String, Object>(); map.put("data", Arrays.asList(new Integer[]{1,2})); map.put("total", 1); String json=JsonUtil.object2Json(map, true); System.out.println(JsonUtil.json2Map(json)); } }
package com.github.olly.workshop.imagegrayscale; import com.github.olly.workshop.springevents.SpringBootEventsConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; @SpringBootApplication @Import(SpringBootEventsConfiguration.class) public class ImageGrayscaleApplication { public static void main(String[] args) { SpringApplication.run(ImageGrayscaleApplication.class, args); } }
package com.alexey.vk.model; public class News { private long id; private int iconNews; private String titleNews; private String timeNews; private String textNews; private int like; private int repost; private int comment; private int _iduser; public News(long id, int iconNews, String titleNews, String timeNews, String textNews, int like, int repost, int comment) { this.id = id; this.iconNews = iconNews; this.titleNews = titleNews; this.timeNews = timeNews; this.textNews = textNews; this.like = like; this.repost = repost; this.comment = comment; } public int getLike() { return like; } public void setLike(int like) { this.like = like; } public int getRepost() { return repost; } public void setRepost(int repost) { this.repost = repost; } public int getComment() { return comment; } public void setComment(int comment) { this.comment = comment; } public int get_iduser() { return _iduser; } public void set_iduser(int _iduser) { this._iduser = _iduser; } public String getTitleNews() { return titleNews; } public void setTitleNews(String titleNews) { this.titleNews = titleNews; } public String getTimeNews() { return timeNews; } public void setTimeNews(String timeNews) { this.timeNews = timeNews; } public String getTextNews() { return textNews; } public void setTextNews(String textNews) { this.textNews = textNews; } public int getIconNews() { return iconNews; } public void setIconNews(int iconNews) { this.iconNews = iconNews; } public long getId() { return id; } public void setId(int id) { this.id = id; } }
package pg01.c03; public class MyThread implements Runnable { private char caracter; private int dormido; private int impresiones; public MyThread(char caracter, int dormido, int impresiones) { this.caracter = caracter; this.dormido = dormido; this.impresiones = impresiones; } @Override public void run() { for (int i = 0; i < impresiones; i++) { for (int j = 0; j< 100000; j++) { System.out.print(caracter); } try { Thread.sleep(dormido); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.github.olly.workshop.imageorchestrator.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class TransformationRequest { private final String imageId; private final List<Transformation> transformations; private final Boolean persist; private final String name; @JsonCreator public TransformationRequest(@JsonProperty("imageId") String imageId, @JsonProperty("transformations") List<Transformation> transformations, @JsonProperty("persist") Boolean persist, @JsonProperty("name") String name) { this.imageId = imageId; this.transformations = transformations != null ? transformations : Collections.emptyList(); this.persist = persist; this.name = name; } public String getImageId() { return imageId; } public List<Transformation> getTransformations() { return transformations; } public Boolean getPersist() { return persist; } public String getName() { return name; } public List getTransformationTypes() { if (transformations != null) { return transformations.stream().map(Transformation::getType).collect(Collectors.toList()); } return Collections.EMPTY_LIST; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("imageId", imageId) .add("transformations", transformations) .toString(); } }
package org.micromanager.multicamera; import mmcorej.CMMCore; import org.micromanager.api.MMPlugin; import org.micromanager.api.ScriptInterface; import org.micromanager.utils.ReportingUtils; public class MultiCamera implements MMPlugin { public static String menuName = "Multi-Andor Control"; public static String tooltipDescription = "This plugin lets your control multiple " + "cameras simultanuously. It is specifically written for Andor cameras. " + "Use the Utilities->Multi Camera adapter to combine multiple Andor cameras " + "into a single logical camera."; private CMMCore core_; private ScriptInterface gui_; private MultiCameraFrame myFrame_; @Override public void setApp(ScriptInterface app) { gui_ = app; core_ = app.getMMCore(); if (myFrame_ == null) { try { myFrame_ = new MultiCameraFrame(gui_); gui_.addMMListener(myFrame_); gui_.addMMBackgroundListener(myFrame_); } catch (Exception e) { ReportingUtils.showError(e); return; } } myFrame_.setVisible(true); } @Override public void dispose() { if (myFrame_ != null) myFrame_.safePrefs(); } @Override public void show() { String ig = "Andor Control"; } @Override public String getInfo () { return "Multi Camera Plugin"; } @Override public String getDescription() { return tooltipDescription; } @Override public String getVersion() { return "0.12"; } @Override public String getCopyright() { return "University of California, 2010, 2011"; } }
package com.mcl.mancala.game; import com.mcl.mancala.beans.Mancala; import com.mcl.mancala.beans.Player; import lombok.RequiredArgsConstructor; /* * Class to store the movement mechanics when transferring pebbles between the pits. * * @author Maxim N * */ @RequiredArgsConstructor public class MovementMechanics { private final Mancala mancala; private final boolean whenCaptureAddToLargePit; private boolean lastStoneInLargePit = false; public boolean playerMove(int playerNr, int startingSmallPit) { Player movingPlayer = mancala.getPlayer(playerNr); Player stillPlayer = mancala.getInversePlayer(playerNr); if (!movingPlayer.isMove()) { return false; } int pebblesCount = takingCareOfChosenSmallPit(movingPlayer, startingSmallPit - 1); if (pebblesCount == 0) { return false; } boolean movingPlayerPits = true; while (pebblesCount > 0) { Player handleSmallPitsPlayer = movingPlayerPits ? movingPlayer : stillPlayer; pebblesCount = addPebblesInPits(pebblesCount, startingSmallPit, handleSmallPitsPlayer); startingSmallPit = resetStartingSmallPitToFirst(startingSmallPit); movingPlayerPits = !movingPlayerPits; } decideWhatPlayerMovesNext(movingPlayer, stillPlayer); return true; } private int resetStartingSmallPitToFirst(int startingSmallPit) { if (startingSmallPit != 0) { startingSmallPit = 0; } return startingSmallPit; } private int takingCareOfChosenSmallPit(Player movingPlayer, int i) { int pebblesCount = movingPlayer.getSmallPitValue(i); movingPlayer.emptySmallPit(i); return pebblesCount; } private void decideWhatPlayerMovesNext(Player movingPLayer, Player stillPlayer) { if (lastStoneInLargePit) { movingPLayer.setMove(true); stillPlayer.setMove(false); } else { movingPLayer.setMove(false); stillPlayer.setMove(true); } } private int addPebblesInPits(int pebblesCount, int startPosition, Player playerWithPitsToFill) { int numberOfSmallPits = playerWithPitsToFill.getSmallPits().length; for (int pitPosition = startPosition; pitPosition <= numberOfSmallPits; pitPosition++) { pebblesCount = fillBigPit(pebblesCount, playerWithPitsToFill, numberOfSmallPits, pitPosition); pebblesCount = fillSmallPits(pebblesCount, playerWithPitsToFill, numberOfSmallPits, pitPosition); if (pebblesCount == 0) { return pebblesCount; } } return pebblesCount; } private int fillSmallPits(int pebblesCount, Player playerWithPitsToFill, int numberOfSmallPits, int pitPosition) { if (pitPosition != numberOfSmallPits) { int universalPitPosition = playerWithPitsToFill.isMove() ? pitPosition : getInvertedSmallPit(playerWithPitsToFill, pitPosition); playerWithPitsToFill.incrementSmallPit(universalPitPosition); pebblesCount--; captureOpponentPebbles(pebblesCount, playerWithPitsToFill, pitPosition); } return pebblesCount; } private void captureOpponentPebbles(int pebblesCount, Player playerWithPitsToFill, int pitPosition) { if (playerWithPitsToFill.isMove() && pebblesCount == 0 && playerWithPitsToFill.getSmallPitValue(pitPosition) == 1) { Player opponent = mancala.getInversePlayer(playerWithPitsToFill.getId()); int invertedPitPosition = getInvertedSmallPit(playerWithPitsToFill, pitPosition); int opponentPebbles = takingCareOfChosenSmallPit(opponent, invertedPitPosition); playerWithPitsToFill.setPebblesToSmallPit(pitPosition, opponentPebbles + playerWithPitsToFill.getSmallPitValue(pitPosition)); if (whenCaptureAddToLargePit) { playerWithPitsToFill.addToLargePit(playerWithPitsToFill.getSmallPitValue(pitPosition)); playerWithPitsToFill.emptySmallPit(pitPosition); } } } private int getInvertedSmallPit(Player player, int pitPosition) { return player.getSmallPits().length - 1 - pitPosition; } private int fillBigPit(int pebblesCount, Player playerWithPitsToFill, int numberOfSmallPits, int pitPosition) { if (pitPosition == numberOfSmallPits && playerWithPitsToFill.isMove()) { playerWithPitsToFill.incrementLargePit(); if (pebblesCount == 1) { lastStoneInLargePit = true; } pebblesCount--; } return pebblesCount; } }
package com.youma.his.dao; import com.youma.his.vo.Drug; /** * @author Administrator */ public interface DrugDao { public int drugAdd(Drug drug); }
package com.example.adapter; public class NumberView { private int imageId; private String textId1; private String textId2; public NumberView(int imageId,String textId1,String textId2) { this.imageId=imageId; this.textId1=textId1; this.textId2=textId2; } public int getImageId() { return imageId; } public String getTextId1() { return textId1; } public String getTextId2() { return textId2; } }
package asylumdev.adgresources.block; public class ModBlocks { }
//package com.yan.coupons.tests; // //import java.util.Calendar; //import java.util.GregorianCalendar; // //import com.yan.coupons.beans.Coupon; //import com.yan.coupons.beans.User; //import com.yan.coupons.enums.Category; //import com.yan.coupons.enums.UserType; //import com.yan.coupons.logic.CouponsController; // //public class testCoupon { // // public static void main(String[] args) { // CouponsController coupon= new CouponsController(); // Coupon com1= new Coupon("home video", 3000.00f, null, (Calendar)new GregorianCalendar(2019, 11, 1), (Calendar)new GregorianCalendar(2020, 01, 01), Category.ELECTRICITY, 300, "alam/222334.co.il", 4); // Coupon com2= new Coupon("digital weight", 59.90f, null, (Calendar)new GregorianCalendar(2020, 11, 1), (Calendar)new GregorianCalendar(2021, 0, 1), Category.FOOD, 250, "shoping.co.ol", 6); // Coupon com3= new Coupon("Executive chair", 259.90f, "office",(Calendar)new GregorianCalendar(2020, 11, 1) , (Calendar)new GregorianCalendar(2021,10, 1), Category.HOME, 20, null, 2); // Coupon com4= new Coupon("the dust", 50, null, (Calendar)new GregorianCalendar(2021, 4, 1), (Calendar)new GregorianCalendar(2020, 11, 10), Category.HOME, 1000, "ikea/316.org.il", 7); //// Coupons com5= new Coupons(name, price, discription, startDate, endDate, category, amount, image, company_id) // User user= new User("the boss", "1&only", null, UserType.Admin ); // User user2= new User(" windows", "jelly", 6l, UserType.Company ); // // // try { //// coupon.createCouponController(com4, user2); //// coupon.deleteCouponController(3, user2); //// coupon.updateCoupon(9, com4, user2); //// coupon.getCouponBetwinPricesController(user, 40, 600); //// coupon.getCouponsByCategoryController(user, Category.ELECTRICITY); //// coupon.getCouponsByCompanyIdController(user, 2); //// coupon.getCouponByIdController(user, 8); //// boolean ex= coupon.isCouponNameExist("baag"); //// System.out.println("bag is exist:"+ ex); //// coupon.getAllCouponsController(user); // } catch (Exception e) { // e.printStackTrace(); // } // // } // //}
/** * */ package net.sf.taverna.t2.component.ui.menu.profile; import static javax.swing.JOptionPane.showMessageDialog; import static net.sf.taverna.t2.component.ui.serviceprovider.ComponentServiceIcon.getIcon; import static org.apache.log4j.Logger.getLogger; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import org.apache.log4j.Logger; /** * @author alanrw * */ public class ComponentProfileDeleteAction extends AbstractAction { private static final long serialVersionUID = -5697971204434020559L; @SuppressWarnings("unused") private static final Logger log = getLogger(ComponentProfileDeleteAction.class); private static final String DELETE_PROFILE = "Delete profile..."; public ComponentProfileDeleteAction() { super(DELETE_PROFILE, getIcon()); this.setEnabled(false); } @Override public void actionPerformed(ActionEvent arg0) { // FIXME Not yet implemented showMessageDialog(null, "Not yet implemented"); } }
package server.sport.model; import org.hibernate.annotations.GenericGenerator; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "matches") public class Match { private int matchesId; private Integer score; private User playerOfTheMatch; private Activity activity; @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "native") @GenericGenerator(name="native", strategy = "native") @Column(name = "matches_id", nullable = false) public int getMatchesId() { return matchesId; } public void setMatchesId(int matchesId) { this.matchesId = matchesId; } @Basic @Column(name = "score", nullable = true) public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Match match = (Match) o; if (matchesId != match.matchesId) return false; if (!Objects.equals(score, match.score)) return false; return true; } @Override public int hashCode() { int result = matchesId; result = 31 * result + (score != null ? score.hashCode() : 0); return result; } @ManyToOne @JoinColumn(name = "player_of_the_match", referencedColumnName = "user_id") public User getPlayerOfTheMatch() { return playerOfTheMatch; } public void setPlayerOfTheMatch(User playerOfTheMatch) { this.playerOfTheMatch = playerOfTheMatch; } @JsonBackReference @OneToOne @JoinColumn(name = "activity_id", referencedColumnName = "activity_id", nullable = false) public Activity getActivity() { return activity; } public void setActivity(Activity activity) { this.activity = activity; } public Match() { } public Match(Integer score, User playerOfTheMatch, Activity activity) { this.score = score; this.playerOfTheMatch = playerOfTheMatch; this.activity = activity; } public Match(Activity activity){ this.activity = activity; } public Match(int matchesId, Integer score, User playerOfTheMatch, Activity activity) { this.matchesId = matchesId; this.score = score; this.playerOfTheMatch = playerOfTheMatch; this.activity = activity; } /*@Override public String toString() { return "Match{" + "matchesId=" + matchesId + ", score=" + score + ", playerOfTheMatch=" + playerOfTheMatch + ", activity=" + activity + '}'; }*/ }
// https://leetcode.com/problems/cousins-in-binary-tree/solution/ class Solution { public boolean isCousins(TreeNode root, int x, int y) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { boolean siblings = false; boolean cousins = false; int nodesAtDepth = queue.size(); for (int i = 0; i < nodesAtDepth; i++) { TreeNode node = queue.remove(); if (node == null) siblings = false; else { if (node.val == x || node.val == y) { if (!cousins) { siblings = cousins = true; } else { return !siblings; } } if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); queue.add(null); } } if (cousins) return false; } return false; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.mapreduce; import java.io.IOException; import org.apache.hadoop.mapreduce.lib.output.RecordWriter; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.WritableComparable; /** * A context object that allows input and output from the task. It is only * supplied to the {@link Mapper} or {@link Reducer}. * * @param <KEYIN> the input key type for the task * @param <VALUEIN> the input value type for the task * @param <KEYOUT> the output key type for the task * @param <VALUEOUT> the output value type for the task */ public abstract class TaskInputOutputContext<KEYIN extends WritableComparable, VALUEIN extends WritableComparable, KEYOUT extends WritableComparable, VALUEOUT extends WritableComparable> extends TaskAttemptContext { private StatusReporter reporter; private RecordWriter output; public TaskInputOutputContext(Configuration conf, TaskAttemptID taskid, final RecordWriter output, final StatusReporter reporter) { super(conf, taskid); this.reporter = reporter; this.output = output; } /** * Advance to the next key, value pair, returning null if at end. * * @return the key object that was read into, or null if no more */ public abstract boolean nextKeyValue() throws IOException, InterruptedException; /** * Get the current key. * * @return the current key object or null if there isn't one * @throws IOException * @throws InterruptedException */ public abstract KEYIN getCurrentKey() throws IOException, InterruptedException; /** * Get the current value. * * @return the value object that was read into * @throws IOException * @throws InterruptedException */ public abstract VALUEIN getCurrentValue() throws IOException, InterruptedException; /** * Generate an output key/value pair. */ public void write(KEYOUT key, VALUEOUT value) throws IOException, InterruptedException { output.write(key, value); } public Counter getCounter(Enum<?> counterName) { return reporter.getCounter(counterName); } public Counter getCounter(String groupName, String counterName) { return reporter.getCounter(groupName, counterName); } public void progress() { reporter.progress(); } public void setStatus(String status) { reporter.setStatus(status); } }
package com.crawler.htmlunit.crawler; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlPage; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Crawler { private final static Logger LOG = LoggerFactory.getLogger(Crawler.class); private final WebClient webClient = new WebClient(); public HtmlPage getPageByString(final String url) { HtmlPage pageToReturn = null; try { pageToReturn = webClient.getPage(url); } catch (IOException | FailingHttpStatusCodeException e) { LOG.error("unable to get the desired webpage", e); } return pageToReturn; } }
package de.cuuky.varo.list.item.lists; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import de.cuuky.varo.list.item.ItemList; import de.cuuky.varo.version.types.Materials; public class StartItems extends ItemList { @SuppressWarnings("deprecation") public StartItems() { super("StartItems"); if (!items.isEmpty()) return; items.add(Materials.AIR.parseItem()); } public void giveToAll() { for (Player player : Bukkit.getOnlinePlayers()) for (ItemStack item : items) player.getInventory().addItem(item); } }
package com.gaoshin.business; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gaoshin.beans.Review; import com.gaoshin.beans.ReviewSummary; import com.gaoshin.beans.ReviewTarget; import com.gaoshin.dao.UserDao; import com.gaoshin.entity.ReviewEntity; import com.gaoshin.entity.ReviewSummaryEntity; import com.gaoshin.entity.UserEntity; import common.web.BusinessException; import common.web.ServiceError; @Service("reviewService") @Transactional public class ReviewServiceImpl extends BaseServiceImpl implements ReviewService { @Autowired private UserDao userDao; @Override public Review create(Review review) { UserEntity userEntity = userDao.getUser(review.getAuthor()); if (userEntity == null) throw new BusinessException(ServiceError.NotFound); ReviewSummaryEntity reviewSummaryEntity = userDao.getFirstEntityBy(ReviewSummaryEntity.class, "targetId", review.getTargetId(), "targetType", review.getTargetType()); if (reviewSummaryEntity == null) { reviewSummaryEntity = new ReviewSummaryEntity(); reviewSummaryEntity.setTargetId(review.getTargetId()); reviewSummaryEntity.setTargetType(review.getTargetType()); reviewSummaryEntity.setLastUpdateTime(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); userDao.saveEntity(reviewSummaryEntity); } ReviewEntity entity = new ReviewEntity(review); entity.setAuthor(userEntity); entity.setCreateTime(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); entity.setReviewSummaryEntity(reviewSummaryEntity); userDao.saveEntity(entity); reviewSummaryEntity.setThumbsdown(reviewSummaryEntity.getThumbsdown() + review.getThumbsdown()); reviewSummaryEntity.setThumbsup(reviewSummaryEntity.getThumbsup() + review.getThumbsup()); reviewSummaryEntity.getReviewEntities().add(entity); reviewSummaryEntity.setLastUpdateTime(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); userDao.saveEntity(reviewSummaryEntity); return entity.getBean(Review.class); } @Override public ReviewSummary list(ReviewTarget type, Long id) { ReviewSummaryEntity reviewSummaryEntity = userDao.getFirstEntityBy(ReviewSummaryEntity.class, "targetId", id, "targetType", type); if (reviewSummaryEntity == null) { ReviewSummary reviewSummary = new ReviewSummary(); return reviewSummary; } List<ReviewEntity> entities = userDao.findEntityBy(ReviewEntity.class, "targetId", id, "targetType", type); ReviewSummary list = reviewSummaryEntity.getBean(ReviewSummary.class); for (ReviewEntity entity : entities) { list.getReviews().add(entity.getBean(Review.class)); } return list; } }
package com.example.android.sign_up_page; import android.content.Intent; import android.content.res.Configuration; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button b; EditText name1,email1,pass1; String name; String email; String pass; RadioButton male; RadioButton female; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b = (Button) findViewById(R.id.button); name1 = (EditText) findViewById(R.id.name); male = (RadioButton) findViewById(R.id.maleid); female = (RadioButton) findViewById(R.id.femaleid); email1 = (EditText) findViewById(R.id.email); pass1 = (EditText) findViewById(R.id.pass); } public void raj(View v) { name=name1.getText().toString(); email=email1.getText().toString(); pass=pass1.getText().toString(); String gend; if(male.isChecked()) { gend ="male"; } else gend ="female"; Toast.makeText(MainActivity.this,"Welcome",Toast.LENGTH_LONG).show(); Intent ras=new Intent(MainActivity.this, Main2Activity.class); startActivity(ras); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) Toast.makeText(MainActivity.this,"changing orientation to Landscape is not recommended",Toast.LENGTH_LONG).show(); } }
/** * Copyright 2009 - 2011 Wouter Beheydt. * This file is part of the flemish foster care registration application. * http://registratie.pleegzorgvlaanderen.be */ package org.aksw.autosparql.client.widget.autocomplete; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayMixed; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.URL; import com.google.gwt.json.client.JSONObject; import com.google.gwt.jsonp.client.JsonpRequestBuilder; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.SuggestOracle; /** * * @author Wouter Beheydt * @version 3.5.0 */ public class SearchSuggestOracle extends SuggestOracle { private String displayFieldName; private String searchItemUrl; private JSONObject requestObject; private RequestBuilder searchRequestBuilder; private SearchCallback searchCallback; private Timer timer; private String query; private int limit; SuggestOracle.Callback callback; SuggestOracle.Request request; private JsonpRequestBuilder builder; public SearchSuggestOracle(String displayFieldName, String searchItemUrl) { this.displayFieldName = displayFieldName; this.searchItemUrl = searchItemUrl; initRequestObject(); init(); initTimer(); } /** * Initialize the request object to update ref to object */ private void initRequestObject() { requestObject = new JSONObject(); JSONObject meta = new JSONObject(); JSONObject payload = new JSONObject(); requestObject.put("meta", meta); requestObject.put("payload", payload); searchCallback = new SearchCallback(displayFieldName); searchRequestBuilder = new RequestBuilder(RequestBuilder.POST, URL.encode(searchItemUrl)); searchRequestBuilder.setHeader("Content-type", "text/x-json"); searchRequestBuilder.setCallback(searchCallback); } private void init(){ builder = new JsonpRequestBuilder(); builder.setCallbackParam("json.wrf"); } /** * Initialize the timer * The timer's run method has the code to fetch the suggestions */ private void initTimer() { timer = new Timer() { @Override public void run() { // requestObject.get("payload").isObject().put("search", new JSONString(query)); // requestObject.get("payload").isObject().put("limit", new JSONString("" + limit)); // searchRequestBuilder.setRequestData(requestObject.toString()); // String url = "http://139.18.2.173:8080/apache-solr-3.1.0/dbpedia_resources/terms?terms=true&terms.fl=label&terms.lower=" + query + "&terms.prefix=" + query + "&terms.lower.incl=false&indent=true&wt=json"; String url = "http://139.18.2.173:8080/apache-solr-3.1.0/dbpedia_classes/suggest?q=" + query + "&wt=json&omitHeader=true"; try { // searchRequestBuilder.send(); builder.requestObject(url, new AsyncCallback<SolrSuggestionResponse>() { // Type-safe! public void onFailure(Throwable throwable) { System.out.println("ERROR: " + throwable); } public void onSuccess(SolrSuggestionResponse response) { JsArrayMixed a = response.getLabels(); List<SimpleSuggestion> suggestions = new ArrayList<SimpleSuggestion>(a.length()); for(int i = 0; i < a.length(); i++){ suggestions.add(new SimpleSuggestion(a.getString(i))); } SuggestOracle.Response oracleResponse = new SuggestOracle.Response(suggestions); callback.onSuggestionsReady(request, oracleResponse); } }); } catch (Exception e) { e.printStackTrace(); } } }; } /** * Method to retrieve suggestions * * (Re-) schedules the timer to wait 0.8 sec * As long as user types (at least a char per 0.8 sec) * method waits, then timer runs and gets suggestions * * This method accepts the limit set by the SuggestBox, default 10 * * @param request * @param callback */ @Override public void requestSuggestions(SuggestOracle.Request request, SuggestOracle.Callback callback) { this.callback = callback; this.request = request; searchCallback.setOracleCallback(callback); searchCallback.setOracleRequest(request); query = request.getQuery(); limit = request.getLimit(); timer.schedule(100); // millisecs } } class SolrDoc extends JavaScriptObject { protected SolrDoc() {} public final native String getURI() /*-{ return this.terms; }-*/; } class SolrTermsResponse extends JavaScriptObject { protected SolrTermsResponse() {} public final native JsArrayMixed getLabels() /*-{ return this.terms.label; }-*/; public final native JsArray<SolrDoc> getDocs() /*-{ return this.terms.label; }-*/; } class SolrSuggestionResponse extends JavaScriptObject { protected SolrSuggestionResponse() {} public final native JsArrayMixed getLabels() /*-{ return this.spellcheck.suggestions[1].suggestion; }-*/; public final native JsArray<SolrDoc> getDocs() /*-{ return this.terms.label; }-*/; }
package com.DeltaFish.pojo; import org.hibernate.validator.constraints.Email; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.awt.*; public class TUser { private String userId; private String password; private String userName; private int credits; private String email; private String mobile; private String lastVisit; private String lastIp; private Image image; private String lable; private String introduction; private String buyerComment; private String sellerComment; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getCredits() { return credits; } public void setCredits(int credits) { this.credits = credits; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String note) { this.mobile = mobile; } public String getLastVisit() { return lastVisit; } public String getLastIp() { return lastIp; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } public String getLable() { return lable; } public void setLable(String lable) { this.lable = lable; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getBuyerComment() { return buyerComment; } public void setBuyerComment(String buyerComment) { this.buyerComment = buyerComment; } public String getSellerComment() { return sellerComment; } public void setSellerComment(String sellerComment) { this.sellerComment = sellerComment; } }
package lesson2; public class Main { public static String name = "Имя проекта"; // public static void main(String[] args) { // String name = "Петя"; // switch (name) { // case "Петя": // System.out.println("Привет Петя, как дела?"); // break; // case "Егор": // System.out.println("Привет Егор, как жизнь?"); // break; // default: // System.out.println("Привет незнакомец"); // } // System.out.println("какая-то логика"); // for (int i = 0; i<=10; i++){ // System.out.println(i); // } // // for (int counter = 10; counter >=0 ; counter--) { // if (counter == 4) { // break; // } // System.out.println(counter); // } // // } // private static int getRandomInt() { // return 8; // } // public static void main(String[] args) { //// for (int i = 1; i <= 10; i++) { //// System.out.println("Начался верхний цикл со счетчиком " + i); //// for (int j = 1; j <= 10; j++) { //// System.out.println("i*j = " + i * j); //// } //// } // //// int i = 0; //// while (true) { //// i++; //// System.out.println(i + " Условие всё еще выполняется"); //// if (i==5) { //// break; //// } //// } //// int i = 0; //// boolean catFed = false; //// do { //// i++; //// System.out.println("Покормил кота " + i + " раз"); //// if (i == 1) { //// System.out.println("Кот наелся"); //// catFed = true; //// } //// } while (!catFed); // int j = getInt(); // String s = (j == 0 ? "j = 0" : "j != 0"); // System.out.println(); // System.out.println(); // System.out.println(); // System.out.println(); // System.out.println(); //// if (j == 0) { //// s = "j = 0"; //// } else { //// s = "j != 0"; //// } // System.out.println(s); // } // // private static int getInt() { // System.out.println("Зашли в гет инт"); // return 1; // } //} public static void main(String[] args) { for (int i = 1; i<=10; i++) { System.out.println(i); if (i==5) { continue; } System.out.println("Не будет при i==5. i = " + i); } } }
package com.arhivator.arhwithsheduler.services; import com.arhivator.arhwithsheduler.dtos.SeparatedName; import org.apache.commons.io.FileUtils; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; class FileService { static SeparatedName separateName(String fullname) { String firstPart = fullname.split("_|\\.")[0]; String secondPart = fullname.split("_|\\.")[1]; String thirdPart = fullname.split("_|\\.")[2]; return new SeparatedName(firstPart, secondPart, thirdPart); } private static boolean isValidFile(String fileName) { // String reg = "^[A-Za-z]{1}[0-9A-Za-z]{1}[_]{1}[0-9]{4}[.]{1}[A-Z]{1}[0-9]{2}$"; String reg = "^[A-Za-z][0-9A-Za-z][_][0-9]{4}[.][A-Z][0-9]{2}$"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(fileName); return matcher.find(); } private static boolean isValidDBF(String fileName) { // String regularDBF = "^[A-Za-z]{2}[_]{1}[0-9]{4}[.]{1}[A-Z]{3}$"; String regularDBF = "^[A-Za-z]{2}[_][0-9]{4}[.][A-Z]{3}$"; Pattern pattern = Pattern.compile(regularDBF); Matcher matcher = pattern.matcher(fileName); return matcher.find(); } private static String fileNameByPath(String pathName) { String[] splitResult = pathName.split(File.separator); return splitResult[splitResult.length - 1]; } private static List<File> getFilesFromNested(File[] listFiles, List<File> list) { if (listFiles != null && listFiles.length != 0) { for (File file : listFiles) { if (file.isDirectory()) { getFilesFromNested(file.listFiles(), list); } if (file.isFile()) { list.add(file); } } } return list; } static void createListOfFiles(String creatingFileName, String checkingDirectory, String creatingFileError) { File directory = new File(checkingDirectory); File[] listOfFiles = directory.listFiles(); List<File> test = new ArrayList<>(); getFilesFromNested(listOfFiles, test); List<String> listOfErrors = new ArrayList<>(); int countAllFiles = 0; int countValidFiles = 0; try (FileWriter writer = new FileWriter(creatingFileName, false)) { if (test.size() != 0) { for (File file : test) { if (isValidFile(file.getName()) | isValidDBF(file.getName())) { countValidFiles++; writer.write(String.valueOf(file.getAbsoluteFile())); writer.append('\n'); writer.flush(); } else { listOfErrors.add(String.valueOf(file.getAbsoluteFile())); } } } else { System.out.println("0 files in chosen directory"); } } catch (IOException ex) { System.out.println(ex.getMessage()); } if (countAllFiles - countValidFiles != 0) { try (FileWriter writerError = new FileWriter(creatingFileError, false)) { for (String file : listOfErrors) { System.out.println("ERROR : " + file); writerError.write(file); writerError.append('\n'); writerError.flush(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } static void createListOfFolders(String creatingFileName, String checkingDirectory) { File directory = new File(checkingDirectory); File[] listOfFiles = directory.listFiles(); try (FileWriter writer = new FileWriter(creatingFileName, false)) { if (listOfFiles != null) { for (File file : listOfFiles) { if (file.isDirectory()) { writer.write(String.valueOf(file.getAbsoluteFile())); writer.append('\n'); writer.flush(); } } } } catch (IOException ex) { System.out.println(ex.getMessage()); } } static List<String> fileReaderFullName(String readingFile) { Reader reader = null; BufferedReader buffReader = null; List<String> fileNames = new ArrayList<>(); try { reader = new FileReader(readingFile); buffReader = new BufferedReader(reader); while (buffReader.ready()) { fileNames.add(buffReader.readLine()); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } if (buffReader != null) { buffReader.close(); } } catch (IOException e) { e.printStackTrace(); } } return fileNames; } static void createFolders(String nameOfNewFolder, String directoryOfNewFolder) { File file = new File(directoryOfNewFolder + nameOfNewFolder); boolean bool = file.mkdir(); if (bool) { System.out.println("Directory created successfully"); } else { System.out.println("Sorry couldn’t create specified directory"); } } static String getSecondPartOfName(String fileName) { return fileName != null ? FileService.separateName(fileName).getSecondPart() : "fileName doesn't exist!"; } static void fillSetOfFolderNames(List<String> listOfFileNames, Set<String> folderNames) { for (String listOfFileName : listOfFileNames) { if (!listOfFileName.isEmpty()) { folderNames.add(getSecondPartOfName(listOfFileName)); } } } static List<String> fillShortFileNamesByListFullNames(List<String> fullnames) { List<String> shortFileNames = new ArrayList<>(); for (String name : fullnames) { shortFileNames.add(FileService.fileNameByPath(name)); } return shortFileNames; } static void createFoldersBySet(Set<String> folderNames, String directoryForNewFoldersByListOfFiles) { if (!folderNames.isEmpty()) { for (String foldersNameS : folderNames) { FileService.createFolders(foldersNameS, directoryForNewFoldersByListOfFiles); } } } static void copyFileToDirectory(List<String> listFileNames, Set<String> setFolderNames, String directoryForNewFoldersByListOfFiles) { for (String fileName : listFileNames) { for (String folderName : setFolderNames) { if (getSecondPartOfName(fileNameByPath(fileName)).equals(folderName)) { File copingFile = new File(fileName); File dir = new File(directoryForNewFoldersByListOfFiles + File.separator + folderName); try { FileUtils.copyFileToDirectory(copingFile, dir); } catch (IOException e) { //TODO logging here e.printStackTrace(); } } } } } static void copyErrFileToERR(List<String> listErr, String directoryERR) { for (String error : listErr) { File copingFile = new File(error); File dir = new File(directoryERR); try { FileUtils.copyFileToDirectory(copingFile, dir); } catch (IOException e) { //TODO logging here e.printStackTrace(); } } } // public List deleteAllFilesFromDirectory(String directory) { //// File[] listOfFiles = foundAllFilesInDirectory(directory); // List<DeleteResult> deleteResults = new ArrayList<>(); // // for (File file : listOfFiles) { // DeleteResult deleteResult = new DeleteResult(file.getName(), file.delete()); // deleteResults.add(deleteResult); // } // return deleteResults; // } }
package com.example.studyMybatis.mapper; /** * @PackageName: com.example.studyMybatis.mapper * @ClassName: PrivilegeMapper * @Description: 权限映射类 * @author: qiuweijie * @date: 2019/11/23 10:15 */ public interface PrivilegeMapper { }
package buyAndSell; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class createWishlist */ @WebServlet("/createWishlist") public class createWishlist extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int currItemId = Integer.parseInt(request.getParameter("itemID")); String next = "/individualitem.jsp?itemID="+currItemId; if (StoreDatabase.getCurrUser() == null) next = "/login.jsp"; else { if (StoreDatabase.sendWishListMessage(currItemId)) request.setAttribute("added", "Item added to your Wishlist!"); else request.setAttribute("added", "Item already exists in your Wishlist"); } RequestDispatcher dispatch = request.getServletContext().getRequestDispatcher(next); dispatch.forward(request, response); } }
package ch10; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.util.Scanner; public class LineNumberer { /** * @param args * @throws IOException * @throws MalformedURLException */ public static void main(String[] args) throws MalformedURLException, IOException { //Prompt for the input and output file. Scanner console = new Scanner(System.in); System.out.println("Input file:"); String inputFileName = console.next(); System.out.println("Output file:"); String outputFileName = console.next(); //Construct the Scanner and PrintWriter objects for reading and writing. File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); //Scanner in = new Scanner(new URL("http://petertolstrup.com").openStream()); PrintWriter out = new PrintWriter(outputFileName); int lineNumber = 1; //Read the input and write the output: while(in.hasNextLine()) { String line = in.nextLine(); out.println("/* " + lineNumber + " */" + line); lineNumber++; } //Close streams in.close(); out.close(); } }
package com.example.myapplication.data.db.entity; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import androidx.room.TypeConverters; import com.example.myapplication.data.db.converter.DateConverter; import java.util.Date; @Entity(tableName = "patients") @TypeConverters(DateConverter.class) public class Patients { @PrimaryKey(autoGenerate = true) public long id; public String name; public String address; public Date birthday; public String phone; public String email; public String height; public String weight; public String bloodGroup; @Ignore public Patients() { this.name = ""; this.address = ""; this.birthday = null; this.phone = ""; this.email = ""; this.height=""; this.weight=""; this.bloodGroup=""; } public Patients(long id, String name, String address, Date birthday, String phone, String email, String height, String weight, String bloodGroup) { this.id = id; this.name = name; this.address = address; this.birthday = birthday; this.phone = phone; this.email = email; this.height = height; this.weight = weight; this.bloodGroup = bloodGroup; } }
package ca.uot.scs2682.marvelcatalog.util; /** * Created by ricardohidekiyamamoto on 2017-03-27. */ public class DateFormater { public static String formatDate(String dateString){ if (dateString != null){ String year = dateString.substring(0,4); String month = dateString.substring(5,7); String day = dateString.substring(8,10); return dateString.substring(5,7) + "/" + dateString.substring(8,10) + "/" + dateString.substring(0,4); } else { return null; } } }
package com.example.demo.controller; import com.example.demo.service.PageClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Map; import java.util.TreeMap; @Controller public class MainController { @Autowired PageClient pageClient; @GetMapping("/") public String main(Model model) { model.addAttribute("page", pageClient.getLatestPage().getRates()); model.addAttribute("title", "Курсы Валют - тестовое задание"); return "main"; } @PostMapping("/filter") public String filter (@RequestParam String filter, Model model){ Map<String,Double> filteredRates = new TreeMap<>(); if (filter != null && !filter.isEmpty()) { for (Map.Entry<String,Double> value : pageClient.getLatestPage().getRates().entrySet()){ if (value.getKey().contains(filter)){ filteredRates.put(value.getKey(), value.getValue()); } } }else { filteredRates = pageClient.getLatestPage().getRates(); } model.addAttribute("page",filteredRates); return "main"; } }
package com.JLANE.wxPay; import java.util.HashMap; import java.util.Map; import com.JLANE.wxPay.wxapi.*; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; /** * @author TishoY */ public class WXContext extends FREContext { /** * INIT sdk */ public static final String WX_FUNCTION_PAY = "wx_function_pay"; public static final String WX_FUNCTION_INIT = "wx_function_init"; @Override public void dispose() { // TODO Auto-generated method stub } @Override public Map<String, FREFunction> getFunctions() { // TODO Auto-generated method stub Map<String, FREFunction> map = new HashMap<String, FREFunction>(); //映射安卓类 map.put(WX_FUNCTION_PAY, new WXPay()); map.put(WX_FUNCTION_INIT, new WXPayEntryActivity()); return map; } }
package main; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Set; public class AdvancedTasks implements Task { /** * HashMaps – Anagrams Create a method that reads words from a file, one per * line, and stores them in an Array. -> Done Create a method that takes a * String as a parameter, and returns a sorted version of the string back. * (bac->abc) -> Done * * Using these methods and a HashMap, perform the following; • Find the word * that has the most anagrams located in the list • If two words have the * same amount of anagrams, output the word that is longer. • If two words * have the same length and the same amount of anagrams, output both. * * Email your lecturer to get access to the wordlist once your code is * ready. Until then create your own text file to test it on. Hint – The key * will be the sorted word, the value will be an arraylist of the anagrams * found. * * @throws IOException */ private ArrayList<String> taskStatisticLog = new ArrayList<String>(); private ArrayList<Integer> batchNumbers; private HashMap<Integer, HashMap<Integer, Boolean>> primeBuckets; private int numberRange; private int maxBucketSize; private int neededBuckets; private int currentBucket; private int totalPrimes; private int nhTotalPrimes; public void runTasks() { System.out.println("\n\n----- START OF ADVANCED TASKS -----"); task21(); // Anagram Word List task22(); // 1 to 3 mil Prime Numbers System.out.println("\n\n----- END OF ADVANCED TASKS -----"); } private void task21() { System.out.println("[AdvancedTasks]: Task 21 (Word List anagram Finder):"); try { System.out.print("[AdvancedTasks]: Loading word list..."); ArrayList<String> wordList = readFile("WordList.txt"); System.out.println(" done"); HashMap<String, String> anagramList = new HashMap<String, String>(); HashMap<String, Integer> anagramCount = new HashMap<String, Integer>(); // System.out.println("[AdvancedTasks]: WordList: " + wordList); System.out.println("[AdvancedTasks]: Running task..."); for (String w : wordList) { // System.out.print("[AdvancedTasks]: Sort: " + w + " => "); // System.out.println(sortStringAlphabetically(w)); anagramList.put(w, sortStringAlphabetically(w)); } System.out.println(anagramList); for (String a : anagramList.values()) { if (anagramCount.containsKey(a)) { anagramCount.put(a, anagramCount.get(a) + 1); } else { anagramCount.put(a, 1); } } // System.out.println(anagramCount); System.out.print("[AdvancedTasks]: The word(s) with most anagrams has " + Collections.max(anagramCount.values()) + " matches, the value is: "); String result = ""; for (Object o : anagramCount.keySet()) { if (anagramCount.get(o).equals(Collections.max(anagramCount.values()))) { System.out.println("[" + o + "]"); result = (String) o; } } // System.out.print("[AdvancedTasks]: The words matching this // anagram are: "); // for(String w : wordList) { // if(result.equals(sortStringAlphabetically(w))) { // System.out.print("[" + w + "]"); // } // } // System.out.println(); } catch (Exception e) { System.out.println(e.getMessage()); } } private void task22() { int num = 6000000; //calculatePrimes(PrimeMode.MODE_COUNT, num); calculatePrimes(PrimeMode.MODE_BATCHED, num); //calculatePrimes(PrimeMode.MODE_BATCHED_HASHMAP, num); System.out.println(); for (String i : taskStatisticLog) { System.out.println(i); } } private void task23() { } // For 21 private ArrayList<String> readFile(String file) throws IOException { ArrayList<String> wordList = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { wordList.add(line); } } catch (IOException e) { throw e; } return wordList; } // For 21 private String sortStringAlphabetically(String word) { ArrayList<Character> charList = new ArrayList<Character>(); char[] charArray = word.toLowerCase().toCharArray(); for (char c : charArray) { charList.add(c); } Collections.sort(charList); String finalString = ""; for (Character c : charList) { finalString += c; } return finalString; } // For 22 private void populateBucket(int from, int to) { long startTime = System.nanoTime(); for(int i = from; i <= to; i++) { if(isPrime(i)) { currentBucket = i / maxBucketSize; //System.out.println("[AdvancedTasks]: Current bucket: " + currentBucket); if(!primeBuckets.containsKey(currentBucket)) { //System.out.println("[AdvancedTasks]: Making new bucket... (index: " + currentBucket + ")"); primeBuckets.put(currentBucket, new HashMap<Integer, Boolean>()); } primeBuckets.get(currentBucket).put(i, true); } } long endTime = System.nanoTime(); long duration = (endTime - startTime) / 1000000; //divide by 1000000 to get milliseconds. System.out.println("[AdvancedTasks]: [BATCH TASK] | Total prime numbers from " + from + " to " + to + " is: " + primeBuckets.get(currentBucket).size() + " | Bucket (" + currentBucket + ") Time: " + duration + " ms"); } // For 22 private void batchWork(int from, int to) { nhTotalPrimes = 0; long startTime = System.nanoTime(); for (int i = from; i <= to; i++) { if (isPrime(i)) { nhTotalPrimes++; } } long endTime = System.nanoTime(); long duration = (endTime - startTime) / 1000000; // divide by 1000000 to // get milliseconds. System.out.println("[AdvancedTasks]: [BATCH TASK] | Total prime numbers from " + from + " to " + to + " is " + nhTotalPrimes + " | Batch Time: " + duration + " ms"); batchNumbers.add(nhTotalPrimes); } // For 22 private void calculatePrimes(PrimeMode pm, int toNumber) { String finalOutputResult = ""; primeBuckets = new HashMap<Integer, HashMap<Integer, Boolean>>(); batchNumbers = new ArrayList<Integer>(); numberRange = toNumber; maxBucketSize = 3000000; neededBuckets = (int) Math.floor(numberRange / maxBucketSize); currentBucket = 1; totalPrimes = 0; nhTotalPrimes = 0; int numberRange = toNumber; // 3000000; //2000000000; switch (pm) { case MODE_BATCHED: // without HM, batched System.out.println("[AdvancedTasks]: [BATCHED COUNT MODE] | Calculating primes between 1 and " + numberRange + " | Needed Batch Jobs: " + neededBuckets); long startTime = System.nanoTime(); int currentNumber = 1; while (currentNumber < numberRange) { if (numberRange > maxBucketSize) { batchWork(currentNumber, currentNumber + maxBucketSize - 1); currentNumber += maxBucketSize; } else { batchWork(currentNumber, currentNumber + numberRange - 1); currentNumber += numberRange; } } for (HashMap<Integer, Boolean> h : primeBuckets.values()) { totalPrimes += h.size(); } long endTime = System.nanoTime(); long duration = (endTime - startTime) / 1000000; int finalCount = 0; for (int i : batchNumbers) { finalCount += i; } finalOutputResult = "[BATCHED COUNT MODE] | Time Taken: " + duration + " ms"; System.out.println("[AdvancedTasks]: [OPERATION COMPLETE] | Total prime numbers from 1 to " + numberRange + " is: " + finalCount + " | Total Time Taken: " + duration + " ms\n\n"); break; case MODE_BATCHED_HASHMAP: // with HM, batched System.out.println("[AdvancedTasks]: [BATCHED HASHMAP MODE] | Calculating primes between 1 and " + numberRange + " | Needed Buckets: " + neededBuckets); startTime = System.nanoTime(); currentNumber = 1; while (currentNumber < numberRange) { if (numberRange > maxBucketSize) { populateBucket(currentNumber, currentNumber + maxBucketSize - 1); currentNumber += maxBucketSize; } else { populateBucket(currentNumber, currentNumber + numberRange - 1); currentNumber += numberRange; } } for (HashMap<Integer, Boolean> h : primeBuckets.values()) { totalPrimes += h.size(); } endTime = System.nanoTime(); duration = (endTime - startTime) / 1000000; finalOutputResult = "[BATCHED HASHMAP MODE] | Time Taken: " + duration + " ms"; System.out.println("[AdvancedTasks]: [OPERATION COMPLETE] | Total prime numbers from 1 to " + numberRange + " is: " + totalPrimes + " | Total Time Taken: " + duration + " ms"); break; case MODE_COUNT: // without HM, no batch System.out.println("[AdvancedTasks]: [COUNT ONLY MODE] | Calculating primes between 1 and " + numberRange); startTime = System.nanoTime(); for (int i = 1; i <= numberRange; i++) { if (isPrime(i)) { nhTotalPrimes++; } } endTime = System.nanoTime(); duration = (endTime - startTime) / 1000000; finalOutputResult = "[COUNT ONLY MODE] | Time Taken: " + duration + " ms"; System.out.println("[AdvancedTasks]: [OPERATION COMPLETE] | Total prime numbers from 1 to " + numberRange + " is: " + nhTotalPrimes + " | Total Time Taken: " + duration + " ms\n\n"); break; } taskStatisticLog.add(finalOutputResult); } // For 22 public static boolean isPrime(int num) { // Initial check, non primes at the start if (num > 2 && num % 2 == 0) { return false; } // Now for all numbers int top = (int) Math.sqrt(num) + 1; for (int i = 3; i < top; i += 2) { if (num % i == 0) { return false; } } return true; } }
/** * Provides miscellaneous interceptor implementations. * More specific interceptors can be found in corresponding * functionality packages, like "transaction" and "orm". */ @NonNullApi @NonNullFields package org.springframework.aop.interceptor; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.pky.smartselling.repository; import com.pky.smartselling.domain.sheet.Sheet; import org.springframework.data.jpa.repository.JpaRepository; public interface SheetRepository extends JpaRepository<Sheet, Long> { }
package com.vti.entity; public class Student_Ex1_Ques2 { private int sobaodanh; private String hoten; private String diachi; private String mucuutien; private Khoi khoi; public static int COUNT = 0; public int getSobaodanh() { return sobaodanh; } public String getHoten() { return hoten; } public String getDiachi() { return diachi; } public String getMucuutien() { return mucuutien; } public Student_Ex1_Ques2(String hoten, String diachi, String mucuutien,Khoi khoi) { COUNT++; this.sobaodanh = COUNT; this.hoten = hoten; this.diachi = diachi; this.mucuutien = mucuutien; this.khoi =khoi; } @Override public String toString() { return "Thí Sinh: Số Báo danh: " + sobaodanh + ", Họ và Tên: " + hoten + ", Địa chỉ: " + diachi + ", Mức ưu tiên: " + mucuutien + ", Khối: " + khoi.getSubject() + "]"; } }
package com.esum.web.ims.nckims.vo; /** * table: NCKIMS_INFO * * Copyright(c) eSum Technologies., Inc. All rights reserved. */ public class NckimsInfo { // primary key private String interfaceId; // fields private String inboundUseFlag; private String inboundId; private String inboundPassword; private String inboundWsdl; private String inboundVendorId; private String inboundRegnum; private String inboundCompanyId; private String inboundGlnkey; private Integer inboundDoctype; private Integer inboundSectype; private String inboundNodeId; private String operation; private String interval; private String inboundUseBackup; private String inboundBackupPath; private String isTest; private String inboundTestSearchDate; private String parsingRule; private String regDate; // "yyyyMMddHHmmss" private String modDate; // "yyyyMMddHHmmss" public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getInboundUseFlag() { return inboundUseFlag; } public void setInboundUseFlag(String inboundUseFlag) { this.inboundUseFlag = inboundUseFlag; } public String getInboundId() { return inboundId; } public void setInboundId(String inboundId) { this.inboundId = inboundId; } public String getInboundPassword() { return inboundPassword; } public void setInboundPassword(String inboundPassword) { this.inboundPassword = inboundPassword; } public String getInboundWsdl() { return inboundWsdl; } public void setInboundWsdl(String inboundWsdl) { this.inboundWsdl = inboundWsdl; } public String getInboundVendorId() { return inboundVendorId; } public void setInboundVendorId(String inboundVendorId) { this.inboundVendorId = inboundVendorId; } public String getInboundRegnum() { return inboundRegnum; } public void setInboundRegnum(String inboundRegnum) { this.inboundRegnum = inboundRegnum; } public String getInboundCompanyId() { return inboundCompanyId; } public void setInboundCompanyId(String inboundCompanyId) { this.inboundCompanyId = inboundCompanyId; } public String getInboundGlnkey() { return inboundGlnkey; } public void setInboundGlnkey(String inboundGlnkey) { this.inboundGlnkey = inboundGlnkey; } public Integer getInboundDoctype() { return inboundDoctype; } public void setInboundDoctype(Integer inboundDoctype) { this.inboundDoctype = inboundDoctype; } public Integer getInboundSectype() { return inboundSectype; } public void setInboundSectype(Integer inboundSectype) { this.inboundSectype = inboundSectype; } public String getInboundNodeId() { return inboundNodeId; } public void setInboundNodeId(String inboundNodeId) { this.inboundNodeId = inboundNodeId; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } public String getInterval() { return interval; } public void setInterval(String interval) { this.interval = interval; } public String getInboundUseBackup() { return inboundUseBackup; } public void setInboundUseBackup(String inboundUseBackup) { this.inboundUseBackup = inboundUseBackup; } public String getInboundBackupPath() { return inboundBackupPath; } public void setInboundBackupPath(String inboundBackupPath) { this.inboundBackupPath = inboundBackupPath; } public String getIsTest() { return isTest; } public void setIsTest(String isTest) { this.isTest = isTest; } public String getInboundTestSearchDate() { return inboundTestSearchDate; } public void setInboundTestSearchDate(String inboundTestSearchDate) { this.inboundTestSearchDate = inboundTestSearchDate; } public String getParsingRule() { return parsingRule; } public void setParsingRule(String parsingRule) { this.parsingRule = parsingRule; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } public String getModDate() { return modDate; } public void setModDate(String modDate) { this.modDate = modDate; } }
package wawi.fachlogik.sachbearbeitersteuerung.bestellungsverwaltung.impl; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import wawi.datenhaltung.bestellungverwaltungs.impl.IBestellungAdminImpl; import wawi.datenhaltung.bestellungverwaltungs.impl.IBestellungSachImpl; import wawi.datenhaltung.bestellungverwaltungs.impl.IKundeServiceImpl; import wawi.datenhaltung.wawidbmodel.entities.Bestellung; import wawi.datenhaltung.wawidbmodel.entities.Bestellungsposition; import wawi.datenhaltung.wawidbmodel.entities.Produkt; import wawi.datenhaltung.wawidbmodel.impl.IDatabaseImpl; import wawi.fachlogik.sachbearbeitersteuerung.bestellungsverwaltung.service.IBestellungsVerwaltung; import wawi.fachlogik.sachbearbeitersteuerung.grenzklassen.BestellungGrenz; import wawi.fachlogik.sachbearbeitersteuerung.grenzklassen.KundeGrenz; import wawi.fachlogik.sachbearbeitersteuerung.grenzklassen.ProduktGrenz; /** * * @author Christian */ public class IBestellungsVerwaltungImpl implements IBestellungsVerwaltung { private final EntityManager em; private final IBestellungAdminImpl iBestellungAdminImpl; private final IBestellungSachImpl iBestellungSachImpl; private final IKundeServiceImpl iKundeServiceImpl; /** * Einziger Konstruktor der Klasse IBestellungsVerwaltungImpl. Instanziiert * alle verwendeten Klassen der Datenhaltung und setzt den EntityManager bei * ihnen. */ public IBestellungsVerwaltungImpl() { em = new IDatabaseImpl().getEntityManager(); iBestellungSachImpl = new IBestellungSachImpl(); iBestellungSachImpl.setEntityManager(em); iBestellungAdminImpl = new IBestellungAdminImpl(); iBestellungAdminImpl.setEntityManager(em); iKundeServiceImpl = new IKundeServiceImpl(); iKundeServiceImpl.setEntityManager(em); } /** * Erstellt eine Liste die alle Bestellungen im System beinhaltet. Die * Bestellungen werden als BestellungGrenz-Objekte zurueck gegeben. Es kann * niemals null zurueck gegeben werden, wohl aber eine leere Liste. * * @return Eine Liste aller Bestellungen */ @Override public ArrayList<BestellungGrenz> alleBestellungenAnzeigen() { List<Bestellung> listAlleBestellungen = iBestellungAdminImpl.getAlleBestellungen(); ArrayList<BestellungGrenz> listAlleBestellungenGrenz = new ArrayList<>(); for (Bestellung bestellung : listAlleBestellungen) { KundeGrenz kundeGrenz = new KundeGrenz( bestellung.getKunde().getKid(), bestellung.getKunde().getName(), bestellung.getKunde().getVorname(), bestellung.getKunde().getAdresse(), bestellung.getKunde().getCreated()); BestellungGrenz bestellungGrenz = new BestellungGrenz( bestellung.getBid(), kundeGrenz, bestellung.getLieferadresse(), bestellung.getRechnungsadresse(), bestellung.getCreated(), bestellung.getStatus(), bestellung.getGesamtnetto(), bestellung.getGesamtbrutto()); listAlleBestellungenGrenz.add(bestellungGrenz); } return listAlleBestellungenGrenz; } /** * Erstellt eine Liste die alle Bestellungen mit dem Status "n" fuer neu im * System beinhaltet. Die Bestellungen werden als BestellungGrenz-Objekte * zurueck gegeben. Es kann niemals null zurueck gegeben werden, wohl aber * eine leere Liste. * * @return Eine Liste aller neuen Bestellungen */ @Override public ArrayList<BestellungGrenz> neueBestellungenAnzeigen() { List<Bestellung> listAlleNeuenBestellungen = iBestellungSachImpl.getAlleNeuenBestellungen(); ArrayList<BestellungGrenz> listAlleNeuenBestellungenGrenz = new ArrayList<>(); for (Bestellung bestellung : listAlleNeuenBestellungen) { KundeGrenz kundeGrenz = new KundeGrenz( bestellung.getKunde().getKid(), bestellung.getKunde().getName(), bestellung.getKunde().getVorname(), bestellung.getKunde().getAdresse(), bestellung.getKunde().getCreated()); BestellungGrenz bestellungGrenz = new BestellungGrenz( bestellung.getBid(), kundeGrenz, bestellung.getLieferadresse(), bestellung.getRechnungsadresse(), bestellung.getCreated(), bestellung.getStatus(), bestellung.getGesamtnetto(), bestellung.getGesamtbrutto()); listAlleNeuenBestellungenGrenz.add(bestellungGrenz); } return listAlleNeuenBestellungenGrenz; } /** * Sucht eine Bestellung anhand einer eindeutigen BestellungsID und gibt * diese als BestellungGrenz-Objekt zurueck. Wird keine Bestellung zur ID * gefunden wird null zurueck gegeben. * * @param bestellungsID Die ID der gesuchten Bestellung * @return Die Bestellung zur BestellungsID oder null */ @Override public BestellungGrenz bestellungAnzeigen(int bestellungsID) { Bestellung bestellung = iBestellungSachImpl.getBestellungById(bestellungsID); if (bestellung == null) { return null; } KundeGrenz kundeGrenz = new KundeGrenz(bestellung.getKunde().getKid(), bestellung.getKunde().getName(), bestellung.getKunde().getVorname(), bestellung.getKunde().getAdresse(), bestellung.getKunde().getCreated()); BestellungGrenz bestellungGrenz = new BestellungGrenz(bestellung.getBid(), kundeGrenz, bestellung.getLieferadresse(), bestellung.getRechnungsadresse(), bestellung.getCreated(), bestellung.getStatus(), bestellung.getGesamtnetto(), bestellung.getGesamtbrutto()); return bestellungGrenz; } /** * Entfernt ein Produkt mit produktID aus einer Bestellung mit * bestellungsID. Ist kein Produkt oder keine Bestellung mit ihrer * respektiven ID vorhanden wird nichts gemacht und false wird zurueck * gegeben. Ist das Entfernen erfolgreich wird true zurueck gegeben, * ansonsten findet ein rollback statt und es wird false zurueck gegeben. * * @param bestellungsID Die ID der Bestellung aus der das Produkt entfernt * wird * @param produktID Die ID des Produktes, das aus der Bestellung entfernt * werden soll * @return true wenn das Produkt erfolgreich entfernt wurde, sonst false */ @Override public boolean produktEntfernen(int bestellungsID, int produktID) { Bestellung bestellung = iBestellungSachImpl.getBestellungById(bestellungsID); if (bestellung == null) { return false; } Produkt produkt = iBestellungSachImpl.getProduktById(produktID); if (produkt == null) { return false; } List<Bestellungsposition> bestellungspositionList = bestellung.getBestellungspositionList(); for (Bestellungsposition bestellungsposition : bestellungspositionList) { if (bestellungsposition.getBestellung().getBid() == bestellungsID && bestellungsposition.getProdukt().getProdid() == produktID) { //if(bestellungsposition.getBestellung().getBid() == bestellung.getBid()) { em.getTransaction().begin(); if (iBestellungSachImpl.deleteBestellposition(bestellungsposition.getBpid())) { em.getTransaction().commit(); List<Bestellungsposition> listWithoutProdukt = bestellung.getBestellungspositionList(); listWithoutProdukt.remove(bestellungsposition); bestellung.setBestellungspositionList(listWithoutProdukt); } else { em.getTransaction().rollback(); return false; } return true; } } return false; } /** * Fuegt ein Produkt mit produktID zu einer Bestellung mit bestellungsID * hinzu. Ist entweder kein Produkt oder keine Bestellung mit passender ID * vorhanden so wird nichts gemacht und false wird zurueck gegeben. Falls * das Hinzufuegen stattfinden kann wird Produkt anzahl mal bestellt. Ist * die Operation erfolgreich wird true zurueck gegeben, ansonsten findet ein * rollback statt und es wird false zurueck gegeben. * * @param bestellungsID Die ID der Bestellung aus der das Produkt entfernt * wird * @param produktID Die ID des Produktes, das aus der Bestellung entfernt * werden soll * @param anzahl Wie oft das Produkt bestellt werden soll * @return true wenn das Produkt erfolgreich zur Bestellung hinzugefuegt * wurde, sonst false */ @Override public boolean produktHinzufuegen(int bestellungsID, int produktID, int anzahl) { Bestellung bestellung = iBestellungSachImpl.getBestellungById(bestellungsID); if (bestellung == null) { return false; } Produkt produkt = iBestellungSachImpl.getProduktById(produktID); if (produkt == null) { return false; } Bestellungsposition bestellungsposition = new Bestellungsposition(null, anzahl); bestellungsposition.setProdukt(produkt); bestellungsposition.setBestellung(bestellung); List<Bestellungsposition> bestellungspositionList = bestellung.getBestellungspositionList(); for (Bestellungsposition bp : bestellungspositionList) { if (bp.getProdukt().getProdid() == produktID) { return false; } } em.getTransaction().begin(); if (iBestellungSachImpl.insertBestellposition(bestellungsposition)) { em.getTransaction().commit(); bestellungspositionList.add(bestellungsposition); } else { em.getTransaction().rollback(); return false; } return true; } /** * Aendert das Attribut anzahl in einer Bestellungsposition zu einer * Bestellung mit bestellungsID das ein Produkt mit produktID enthaelt zu * anzahl. Liefert false falls keine Bestellung mit bestellungsID existiert * oder falls kein Produkt mit produktID existiert oder falls keine * Bestellungsposition mit Produkt und Bestellung existiert oder falls * anzahl negativ ist. Ansonsten wird Anzahl in Bestellungsposition mit * anzahl ersetzt und true zurueck gegeben. * * @param bestellungsID ID zur Bestimmung der betreffenden Bestellung * @param produktID ID zur Bestimmung des betreffenden Produktes * @param anzahl Wie oft das Produkt in Bestellungsposition bestellt werden soll * @return True, wenn die Produktanzahl geändert wurde, sonst false */ @Override public boolean produktAnzahlAendern(int bestellungsID, int produktID, int anzahl) { Bestellung bestellung = iBestellungSachImpl.getBestellungById(bestellungsID); if (anzahl < 0) { return false; } if (bestellung == null) { return false; } for (Bestellungsposition bestellungsposition : bestellung.getBestellungspositionList()) { if (bestellungsposition.getProdukt().getProdid() == produktID) { //bestellungsposition.getProdukt().setStueckzahl(anzahl); bestellungsposition.setAnzahl(anzahl); em.getTransaction().begin(); if (iBestellungSachImpl.updateBestellposition(bestellungsposition)) { em.getTransaction().commit(); return true; } else { em.getTransaction().rollback(); return false; } } } return false; } /** * Falls eine Bestellung abgerechnet ist, d.h. falls ihr Status "r" ist, * wird sie als bezahlt markiert, ihr Status wird zu "b" geaendert. Ist * keine Bestellung mit bestellungsID vorhanden wird nichts gemacht und * false wird zurueck gegeben, ansonsten wird der Status geaendert und true * zuruck gegeben. * * @param bestellungsID ID zur Bestimmung der Bestellung deren Status * geandert werden soll * @return True, wenn die Bestellung als bezahlt markiert wurde, * sonst False */ @Override public boolean bestellungBezahltMarkieren(int bestellungsID) { em.getTransaction().begin(); if (iBestellungSachImpl.setBestellungBezahlt(bestellungsID)) { em.getTransaction().commit(); return true; } else { em.getTransaction().rollback(); return false; } } /** * Liefert eine Liste mit allen Produkten als ProduktGrenz-Objekte zu einer * BestellungsID. Ist keine Bestellung mit bestellungsID vorhanden wird eine * leere Liste zurueck gegeben. * * @param bestellungsID ID zur Bestimmung der Bestellung * @return Eine Liste mit allen Produkten einer Bestellung */ @Override public ArrayList<ProduktGrenz> alleProdukteAnzeigen(int bestellungsID) { Bestellung bestellung = iBestellungAdminImpl.getBestellungById(bestellungsID); ArrayList<ProduktGrenz> alleProdukte = new ArrayList<>(); if(bestellung == null) { return alleProdukte; } for(Bestellungsposition bestellungsposition : bestellung.getBestellungspositionList()) { Produkt produkt = bestellungsposition.getProdukt(); ProduktGrenz produktGrenz = new ProduktGrenz(produkt.getProdid(), produkt.getStueckzahl(), produkt.getMwstsatz(), produkt.getKategorie().getKatid(), produkt.getName(), produkt.getBeschreibung(), produkt.getAngelegt(), produkt.getNettopreis(), produkt.getAktiv()); alleProdukte.add(produktGrenz); } return alleProdukte; } /** * Liefert eine Liste mit allen aktiven Produkten als ProduktGrenz-Objekte. * * @return Eine Liste mit allen Produkten */ @Override public ArrayList<ProduktGrenz> alleProdukteAnzeigen() { List<Produkt> alleProdukte = iKundeServiceImpl.getAktiveProdukte(); ArrayList<ProduktGrenz> alleProdukteGrenz = new ArrayList<>(); for (Produkt produkt : alleProdukte) { ProduktGrenz produktGrenz = new ProduktGrenz(produkt.getProdid(), produkt.getStueckzahl(), produkt.getMwstsatz(), produkt.getKategorie().getKatid(), produkt.getName(), produkt.getBeschreibung(), produkt.getAngelegt(), produkt.getNettopreis(), produkt.getAktiv()); alleProdukteGrenz.add(produktGrenz); } return alleProdukteGrenz; } /** * Ermittelt wie oft ein Produkt mit der ID pid in einer Bestellung mit der * ID bid bestellt wurde. Gibt -1 zurück, wenn die Bestellung oder das * Produkt nicht gefunden werden konnten. * * @param bid ID der Bestellung aus der das Produkt kommt * @param pid ID des Produktes, aus der Bestellung * @return Anzahl des Produktes in der Bestellung */ @Override public int getAnzahlProdukte(int bid, int pid) { Bestellung bestellung = iBestellungAdminImpl.getBestellungById(bid); if (bestellung == null) { return -1; } List<Bestellungsposition> bestellungspositionList = bestellung.getBestellungspositionList(); for (Bestellungsposition bestellungsposition : bestellungspositionList) { if (bestellungsposition.getProdukt().getProdid() == pid) { return bestellungsposition.getAnzahl(); } } return -1; } /** * Zeigt alle abgerechneten Bestellungen an * * @return liste mit allen abgerechneten Bestellungen */ @Override public List<BestellungGrenz> abgerechneteBestellungenAnzeigen() { List<BestellungGrenz> retList = new ArrayList<>(); List<Bestellung> temp = iBestellungSachImpl.getAlleAbgerechnetenBestellungen(); for (Bestellung b : temp) { retList.add(new BestellungGrenz(b.getBid(), b.getKunde(), b.getLieferadresse(), b.getRechnungsadresse(), b.getCreated(), b.getStatus(), b.getGesamtnetto(), b.getGesamtbrutto())); } return retList; } /** * Storniert eine Bestellung * * @param bestellungsid * @return erfolg der Stornierung */ @Override public boolean bestellungStornieren(int bestellungsid) { em.getTransaction().begin(); boolean retVal = iBestellungSachImpl.setBestellungStorniert(bestellungsid); em.getTransaction().commit(); return retVal; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.socket.server.support; import java.net.InetSocketAddress; import java.net.URI; import java.security.Principal; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.context.Lifecycle; import org.springframework.http.HttpCookie; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.reactive.socket.HandshakeInfo; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; import org.springframework.web.reactive.socket.server.WebSocketService; import org.springframework.web.reactive.socket.server.upgrade.JettyRequestUpgradeStrategy; import org.springframework.web.reactive.socket.server.upgrade.ReactorNetty2RequestUpgradeStrategy; import org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy; import org.springframework.web.reactive.socket.server.upgrade.StandardWebSocketUpgradeStrategy; import org.springframework.web.reactive.socket.server.upgrade.TomcatRequestUpgradeStrategy; import org.springframework.web.reactive.socket.server.upgrade.UndertowRequestUpgradeStrategy; import org.springframework.web.server.MethodNotAllowedException; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; /** * {@code WebSocketService} implementation that handles a WebSocket HTTP * handshake request by delegating to a {@link RequestUpgradeStrategy} which * is either auto-detected (no-arg constructor) from the classpath but can * also be explicitly configured. * * @author Rossen Stoyanchev * @author Juergen Hoeller * @since 5.0 */ public class HandshakeWebSocketService implements WebSocketService, Lifecycle { private static final String SEC_WEBSOCKET_KEY = "Sec-WebSocket-Key"; private static final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol"; private static final Mono<Map<String, Object>> EMPTY_ATTRIBUTES = Mono.just(Collections.emptyMap()); private static final boolean tomcatWsPresent; private static final boolean jettyWsPresent; private static final boolean undertowWsPresent; private static final boolean reactorNettyPresent; private static final boolean reactorNetty2Present; static { ClassLoader classLoader = HandshakeWebSocketService.class.getClassLoader(); tomcatWsPresent = ClassUtils.isPresent( "org.apache.tomcat.websocket.server.WsHttpUpgradeHandler", classLoader); jettyWsPresent = ClassUtils.isPresent( "org.eclipse.jetty.websocket.server.JettyWebSocketServerContainer", classLoader); undertowWsPresent = ClassUtils.isPresent( "io.undertow.websockets.WebSocketProtocolHandshakeHandler", classLoader); reactorNettyPresent = ClassUtils.isPresent( "reactor.netty.http.server.HttpServerResponse", classLoader); reactorNetty2Present = ClassUtils.isPresent( "reactor.netty5.http.server.HttpServerResponse", classLoader); } private static final Log logger = LogFactory.getLog(HandshakeWebSocketService.class); private final RequestUpgradeStrategy upgradeStrategy; @Nullable private Predicate<String> sessionAttributePredicate; private volatile boolean running; /** * Default constructor automatic, classpath detection based discovery of the * {@link RequestUpgradeStrategy} to use. */ public HandshakeWebSocketService() { this(initUpgradeStrategy()); } /** * Alternative constructor with the {@link RequestUpgradeStrategy} to use. * @param upgradeStrategy the strategy to use */ public HandshakeWebSocketService(RequestUpgradeStrategy upgradeStrategy) { Assert.notNull(upgradeStrategy, "RequestUpgradeStrategy is required"); this.upgradeStrategy = upgradeStrategy; } /** * Return the {@link RequestUpgradeStrategy} for WebSocket requests. */ public RequestUpgradeStrategy getUpgradeStrategy() { return this.upgradeStrategy; } /** * Configure a predicate to use to extract * {@link org.springframework.web.server.WebSession WebSession} attributes * and use them to initialize the WebSocket session with. * <p>By default this is not set in which case no attributes are passed. * @param predicate the predicate * @since 5.1 */ public void setSessionAttributePredicate(@Nullable Predicate<String> predicate) { this.sessionAttributePredicate = predicate; } /** * Return the configured predicate for initialization WebSocket session * attributes from {@code WebSession} attributes. * @since 5.1 */ @Nullable public Predicate<String> getSessionAttributePredicate() { return this.sessionAttributePredicate; } @Override public void start() { if (!isRunning()) { this.running = true; doStart(); } } protected void doStart() { if (getUpgradeStrategy() instanceof Lifecycle lifecycle) { lifecycle.start(); } } @Override public void stop() { if (isRunning()) { this.running = false; doStop(); } } protected void doStop() { if (getUpgradeStrategy() instanceof Lifecycle lifecycle) { lifecycle.stop(); } } @Override public boolean isRunning() { return this.running; } @Override public Mono<Void> handleRequest(ServerWebExchange exchange, WebSocketHandler handler) { ServerHttpRequest request = exchange.getRequest(); HttpMethod method = request.getMethod(); HttpHeaders headers = request.getHeaders(); if (HttpMethod.GET != method) { return Mono.error(new MethodNotAllowedException( request.getMethod(), Collections.singleton(HttpMethod.GET))); } if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) { return handleBadRequest(exchange, "Invalid 'Upgrade' header: " + headers); } List<String> connectionValue = headers.getConnection(); if (!connectionValue.contains("Upgrade") && !connectionValue.contains("upgrade")) { return handleBadRequest(exchange, "Invalid 'Connection' header: " + headers); } String key = headers.getFirst(SEC_WEBSOCKET_KEY); if (key == null) { return handleBadRequest(exchange, "Missing \"Sec-WebSocket-Key\" header"); } String protocol = selectProtocol(headers, handler); return initAttributes(exchange).flatMap(attributes -> this.upgradeStrategy.upgrade(exchange, handler, protocol, () -> createHandshakeInfo(exchange, request, protocol, attributes)) ); } private Mono<Void> handleBadRequest(ServerWebExchange exchange, String reason) { if (logger.isDebugEnabled()) { logger.debug(exchange.getLogPrefix() + reason); } return Mono.error(new ServerWebInputException(reason)); } @Nullable private String selectProtocol(HttpHeaders headers, WebSocketHandler handler) { String protocolHeader = headers.getFirst(SEC_WEBSOCKET_PROTOCOL); if (protocolHeader != null) { List<String> supportedProtocols = handler.getSubProtocols(); for (String protocol : StringUtils.commaDelimitedListToStringArray(protocolHeader)) { if (supportedProtocols.contains(protocol)) { return protocol; } } } return null; } private Mono<Map<String, Object>> initAttributes(ServerWebExchange exchange) { if (this.sessionAttributePredicate == null) { return EMPTY_ATTRIBUTES; } return exchange.getSession().map(session -> session.getAttributes().entrySet().stream() .filter(entry -> this.sessionAttributePredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } private HandshakeInfo createHandshakeInfo(ServerWebExchange exchange, ServerHttpRequest request, @Nullable String protocol, Map<String, Object> attributes) { URI uri = request.getURI(); // Copy request headers, as they might be pooled and recycled by // the server implementation once the handshake HTTP exchange is done. HttpHeaders headers = new HttpHeaders(); headers.addAll(request.getHeaders()); MultiValueMap<String, HttpCookie> cookies = request.getCookies(); Mono<Principal> principal = exchange.getPrincipal(); String logPrefix = exchange.getLogPrefix(); InetSocketAddress remoteAddress = request.getRemoteAddress(); return new HandshakeInfo(uri, headers, cookies, principal, protocol, remoteAddress, attributes, logPrefix); } static RequestUpgradeStrategy initUpgradeStrategy() { if (tomcatWsPresent) { return new TomcatRequestUpgradeStrategy(); } else if (jettyWsPresent) { return new JettyRequestUpgradeStrategy(); } else if (undertowWsPresent) { return new UndertowRequestUpgradeStrategy(); } else if (reactorNettyPresent) { // As late as possible (Reactor Netty commonly used for WebClient) return ReactorNettyStrategyDelegate.forReactorNetty1(); } else if (reactorNetty2Present) { // As late as possible (Reactor Netty commonly used for WebClient) return ReactorNettyStrategyDelegate.forReactorNetty2(); } else { // Let's assume Jakarta WebSocket API 2.1+ return new StandardWebSocketUpgradeStrategy(); } } /** * Inner class to avoid a reachable dependency on Reactor Netty API. */ private static class ReactorNettyStrategyDelegate { public static RequestUpgradeStrategy forReactorNetty1() { return new ReactorNettyRequestUpgradeStrategy(); } public static RequestUpgradeStrategy forReactorNetty2() { return new ReactorNetty2RequestUpgradeStrategy(); } } }
package Parte05.P5PG43; public class Midia { protected int codigo; protected double preco; protected String nome; public Midia(int codigo, double preco, String nome) { this.codigo = codigo; this.preco = preco; this.nome = nome; } public Midia() { } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public double getPreco() { return preco; } public void setPreco(double preco) { this.preco = preco; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getTipo(){ String midia = null; return midia; } public String getDetalhes(){ return "\n Cógigo: "+this.codigo+ "\n Preço: "+ this.preco+ "\n Nome: "+this.nome; } public void printDados(){ System.out.println(this.getDetalhes()); } }
package hw1.q10; public class MapAnalyzer { public int[][] getDesirabilityMap(char[][] terrainMap) { char item; int[][] influence = new int[terrainMap.length][terrainMap[0].length]; for (int i = 0; i < terrainMap.length; i++) { for (int j = 0; j < terrainMap[i].length; j++) { item = terrainMap[i][j]; if(item == 'T'){ influence[i][j] += 8; influence = surroundTree(influence,i,j); } if(item == 'W'){ influence[i][j] += 2; influence = surroundWater(influence,i,j); } if(item == 'C'){ influence[i][j] += 16; influence = surroundCherry(influence,i,j); } if(item == 'P'){ influence[i][j] += -8; influence = surroundPeople(influence,i,j); } } } return influence; } public GridPoint getBestPosition(char[][] terrainMap){ int[][] influence = getDesirabilityMap(terrainMap); influence = removeLandMarks(terrainMap, influence); GridPoint thePoint = new GridPoint(); int best = 0; int select = 0; for (int i = 0; i < influence.length; i++) { for (int j = 0; j < influence[i].length; j++) { select = influence[i][j]; if(select > best){ best = select; thePoint.x = i; thePoint.y = j; } } } return thePoint; } private int[][] removeLandMarks(char[][] terrainMap, int[][] influence){ char item; for (int i = 0; i < terrainMap.length; i++) { for (int j = 0; j < terrainMap[i].length; j++) { item = terrainMap[i][j]; if(item == 'T'){ influence[i][j] = 0; } if(item == 'W'){ influence[i][j] = 0; influence = surroundWater(influence,i,j); } if(item == 'C'){ influence[i][j] = 0; influence = surroundCherry(influence,i,j); } if(item == 'P'){ influence[i][j] = 0; influence = surroundPeople(influence,i,j); } } } return influence; } private int[][] surroundTree(int[][] theMap,int column,int row){ int rows = theMap[0].length; int columns = theMap.length; int center = 8; System.out.println("rows " + rows); System.out.println("columns " + columns); // theMap[columns-1][rows-1] = 9; int newIndex = 0; int radius = 2; for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { if(!(i == 0 && j == 0)){ if(i + column >= 0 && j + row >= 0){ if(i + column < columns && j + row < rows ){ if((i == radius || i == -radius || j == radius || j == -radius) ){ theMap[i + column][j + row] += center/4; } else{ theMap[i + column][j + row] += center/2; } } } } } } return theMap; } private int[][] surroundWater(int[][] theMap,int column,int row){ int rows = theMap[0].length; int columns = theMap.length; int center = 2; System.out.println("rows " + rows); System.out.println("columns " + columns); int newIndex = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if(!(i == 0 && j == 0)){ if(i + column >= 0 && j + row >= 0){ if(i + column < columns && j + row <= rows ){ // System.out.println("----"); // System.out.println("column: " + (i + column)); // System.out.println("row: " + (j + row)); int current = theMap[i + column][j + row]; // System.out.println("current val = " + current); // System.out.println("adding val" + (center/2)); theMap[i + column][j + row] += center/2; // System.out.println("---"); } } } } } return theMap; } private int[][] surroundCherry(int[][] theMap,int column,int row){ int rows = theMap[0].length; int columns = theMap.length; int center = 16; System.out.println("rows " + rows); System.out.println("columns " + columns); int radius = 3; for (int i = -3; i <= 3; i++) { for (int j = -3; j <= 3; j++) { if(!(i == 0 && j == 0)){ if(i + column >= 0 && j + row >= 0){ if(i + column < columns && j + row < rows ){ if((i == radius || i == -radius || j == radius || j == -radius) ){ theMap[i + column][j + row] += center/8; } else if((i == radius-1 || i == -(radius-1) || j == radius-1 || j == -(radius-1))) { theMap[i + column][j + row] += center/4; } else{ theMap[i + column][j + row] += center/2; } } } } } } return theMap; } private int[][] surroundPeople(int[][] theMap,int column,int row){ int rows = theMap[0].length; int columns = theMap.length; int center = -2; System.out.println("rows " + rows); System.out.println("columns " + columns); // theMap[columns-1][rows-1] = 9; int newIndex = 0; int radius = 2; for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { if(!(i == 0 && j == 0)){ if(i + column >= 0 && j + row >= 0){ if(i + column < columns && j + row < rows ){ if((i == radius || i == -radius || j == radius || j == -radius) ){ theMap[i + column][j + row] += center/4; } else{ theMap[i + column][j + row] += center/2; } } } } } } return theMap; } }
package be.openclinic.datacenter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.Debug; public class HTTPSender extends Sender { public void send() { try{ if(MedwanQuery.getInstance().getConfigInt("datacenterServerId",-1)>0 && MedwanQuery.getInstance().getConfigString("datacenterHTTPKey","").length()>0) { String lastHTTPSenderActivity = MedwanQuery.getInstance().getConfigString("lastDatacenterHTTPSenderActivity","0"); Debug.println("Checking HTTP Datacenter deadline ...: "+lastHTTPSenderActivity+" < "+getDeadline()); if(lastHTTPSenderActivity.equalsIgnoreCase("0") || new SimpleDateFormat("yyyyMMddHHmmss").parse(lastHTTPSenderActivity).before(getDeadline())){ loadMessages(); if(messages.size()>0){ String url = MedwanQuery.getInstance().getConfigString("datacenterHTTPURL","http://www.globalhealthbarometer.net/globalhealthbarometer/datacenter/postMessage.jsp"); String key = MedwanQuery.getInstance().getConfigString("datacenterHTTPKey",""); String datacenterServerId=MedwanQuery.getInstance().getConfigString("datacenterServerId",""); String msgid=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); //Compose message payload Date sentDateTime=new Date(); String messageContent="<?xml version='1.0' encoding='UTF-8'?><message type='datacenter.content' id='"+msgid+"'>"; for (int n=0;n<messages.size();n++){ ExportMessage exportMessage = (ExportMessage) messages.elementAt(n); exportMessage.setServerId(Integer.parseInt(datacenterServerId)); exportMessage.setSentDateTime(sentDateTime); messageContent=messageContent+exportMessage.asXML(); } messageContent=messageContent+"</message>"; boolean bMessageSent = false; //Send payload HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.addParameter("key",key); method.addParameter("type","post"); method.addParameter("message",messageContent); try { client.executeMethod(method); bMessageSent = method.getResponseBodyAsString().contains("<OK>"); } catch (Exception e) { e.printStackTrace(); } if(bMessageSent) { for (int n=0;n<messages.size();n++){ ExportMessage exportMessage = (ExportMessage) messages.elementAt(n); exportMessage.updateSentDateTime(sentDateTime); //This automatically implies a SENTACK ExportMessage.updateAckDateTime(exportMessage.getObjectId(), new java.util.Date()); } Debug.println("-- Message successfully sent"); Debug.println("------------------------------------------------------------------------------------------"); } else { Debug.println("-- Message could not be sent"); Debug.println("-- Received: "+method.getResponseBodyAsString().trim()); Debug.println("------------------------------------------------------------------------------------------"); } } MedwanQuery.getInstance().setConfigString("lastDatacenterHTTPSenderActivity",new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); } } } catch (Exception e) { e.printStackTrace(); } } public static boolean sendImportAckMessage(String messageContent, String to, String msgid) { return true; } public static boolean sendImportAckMessage(ImportMessage importMessage) { return true; } public static boolean sendSysadminMessage(String s, DatacenterMessage msg) { if(MedwanQuery.getInstance().getConfigString("datacenterHTTPKey","").length()>0) { String url = MedwanQuery.getInstance().getConfigString("datacenterHTTPURL","http://www.globalhealthbarometer.net/globalhealthbarometer/datacenter/postMessage.jsp"); String key = MedwanQuery.getInstance().getConfigString("datacenterHTTPKey",""); //Create message content HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.addParameter("key",key); method.addParameter("type","sysadmin"); method.addParameter("message",s); try { client.executeMethod(method); return method.getResponseBodyAsString().contains("<OK>"); } catch (Exception e) { e.printStackTrace(); } } return false; } }
import java.util.Scanner; /** * 이진 검색 시, 배열에서 중복 요소가 있는 경우, * 가운데가 아닌 맨 앞의 요소를 찾는 binSearchX 메소드를 작성해 보세요. */ public class DoIt_Ex5 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); System.out.print("요솟 수 : "); int num = stdIn.nextInt(); int[] x = new int[num]; System.out.println("오름차순으로 입력해 주세요."); System.out.print("x[0] : "); x[0] = stdIn.nextInt(); for (int i = 1; i < num; i++) { do{ System.out.print("x[" + i + "] : "); x[i] = stdIn.nextInt(); } while (x[i] < x[i-1]); } System.out.print("key : "); int ky = stdIn.nextInt(); int idx = binSearchX(x, num, ky); if (idx == -1) { System.out.println("요소가 배열에 존재하지 않습니다."); } else { System.out.println("가장 앞쪽에 위치하는 " + ky + "는 x[" + idx + "]에 위치합니다."); } } static int binSearchX(int[] a, int n, int key) { int pl = 0; int pr = n - 1; int center; do { center = (pl + pr) / 2; if (a[center] == key) { for (int i = pl; i <= pr; i++) { if (a[i] == key) return i; } } else if (a[center] < key) { pl = center + 1; } else { pr = center - 1; } } while (pr >= pl); return -1; } }
import java.lang.reflect.Array; import java.util.Arrays; public class PlusOne { public static void main(String[] args) { int [] output = plusOne(new int[]{9}); Arrays.stream(output).forEach(System.out::println); } public static int[] plusOne(int[] digits) { int [] output = digits; for (int i=digits.length-1;i>=0;i--){ if(i==0 && digits[i] ==9){ output = new int[digits.length+1]; output[0] = 1; break; }else if(digits[i] == 9) { digits[i] = 0; }else{ digits[i]++; break; } } return output; } }
package com.eomcs.basic.oop.ex02; import com.eomcs.util.Calculater; public class EXam0100 { public static void main(String[] args) {// Calculater c1 = new Calculater();//new연산자 힙영역생성 변수만 있는곳 //Calculater 설계도에 따른 c1생성 메인영역에 c1.plus(4); c1.plus(6); c1.divide(2); c1.multiple(4); printResult(c1.result); } static void printResult(int value) { //스태틱 stack 영역 변수만 있는곳 System.out.println("************************************"); System.out.printf("==> 결과 = %d", value); System.out.println("************************************"); } }
package tool; import java.io.UnsupportedEncodingException; import org.apache.log4j.Logger; import sun.misc.*; /** * Base64编码解码工具类 */ public class Base64 { static Logger logger = Logger.getLogger(Base64.class); /** * 对传入的字符串进行Base64编码 * @param str 待编码的字符串,<strong>传入的字符串需按照utf-8编码</strong> * @return 编码好的Base64字符串 */ public static String encode(String str) { byte[] b = null; String s = null; if (str == null) return null; try { b = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (b != null) { s = new BASE64Encoder().encode(b); } return s; } /** * 对base64字符串解码 * @param s base64编码的字符串 * @return 解码后的字符串,按utf-8编码<strong>注意:如果解析的字符中含有不可见字符,可能会解析出错。上述情况应使用decodeBytes方法</strong> * @see #decodeBytes(String) */ public static String decode(String s) { s = s.replace(' ', '+'); byte[] b = null; String result = null; if (s != null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(s); result = new String(b, "utf-8"); } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 对base64字符串解码 * @param s base64编码的字符串 * @return 解码后的字节数组 */ public static byte[] decodeBytes(String s) { byte[] b = null; if (s != null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(s); } catch (Exception e) { e.printStackTrace(); } } return b; } }
package com.revolut.moneytransfer.controller; import com.revolut.moneytransfer.exceptions.InvalidUuidException; import com.revolut.moneytransfer.model.Account; import com.revolut.moneytransfer.util.RequestValidator; import org.eclipse.jetty.http.HttpStatus; import spark.Request; import spark.Response; import spark.Route; import java.util.UUID; import static com.revolut.moneytransfer.Application.accountService; public class AccountController { public static Route createAccount = (Request request, Response response) -> { Account account = RequestValidator.getNewAccount(request.body()); accountService.save(account); response.status(HttpStatus.CREATED_201); return account; }; public static Route getAccount = (Request request, Response response) -> { try { return accountService.get(UUID.fromString(request.params("uuid").trim())); } catch (IllegalArgumentException e) { throw new InvalidUuidException(); } }; }
package com.lamsey.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lamsey.bean.Book; import com.lamsey.bean.Page; import com.lamsey.service.BookService; import com.lamsey.service.impl.BookServiceImpl; import com.lamsey.utils.WebUtils; /** * Servlet implementation class BookClientServlet */ @WebServlet("/client/BookServlet") public class BookClientServlet extends BaseServlet { private static final long serialVersionUID = 1L; /** * 图书业务接口 */ private BookService bookService; public BookClientServlet() { bookService = new BookServiceImpl(); } protected void pageByPrice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取分页的当前页码 int pageNo = WebUtils.parseInt(request.getParameter("pageNO"), 1); int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE); String minStr = request.getParameter("min"); String maxStr = request.getParameter("max"); double min = WebUtils.parseDouble(request.getParameter("min"), 0); double max = WebUtils.parseDouble(request.getParameter("max"),Double.MAX_VALUE); // 查询分页信息 Page<Book> bookPage = bookService.pageByPrice(pageNo, pageSize, min, max); String url = "client/BookServlet?action=pageByPrice"; if (minStr != null){ url =url+"&min="+minStr; } if (maxStr != null){ url = url +"&max=" + maxStr; } // 设置分页的url地址 bookPage.setUrl(url); // 把分页数据保存到域对象中 request.setAttribute("page", bookPage); // 转发到jsp页面 request.getRequestDispatcher("/pages/client/index.jsp").forward(request, response); } }
package com.ifeng.recom.mixrecall.template.behavior; import static com.ifeng.recom.mixrecall.threadpool.ThreadUtils.getAsyncExecutorResult; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import com.google.common.collect.Lists; import com.ifeng.recom.mixrecall.common.constant.RecallChannelBeanName; import com.ifeng.recom.mixrecall.common.model.Document; import com.ifeng.recom.mixrecall.common.model.item.MixResult; import com.ifeng.recom.mixrecall.common.service.handler.remove.IItemRemoveHandler; import com.ifeng.recom.mixrecall.common.service.handler.remove.RemoverHandlerService; import com.ifeng.recom.mixrecall.model.RecallChannelResult; import com.ifeng.recom.mixrecall.model.RecallConfig; import com.ifeng.recom.mixrecall.threadpool.RecallExecutor; import com.ifeng.recom.tools.common.logtools.model.TimerEntity; import com.ifeng.recom.tools.common.logtools.utils.timer.TimerEntityUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ifeng.recom.mixrecall.common.constant.GyConstant; import com.ifeng.recom.mixrecall.common.constant.RecallConstant; import com.ifeng.recom.mixrecall.common.model.RecallResult; import com.ifeng.recom.mixrecall.common.model.RecallThreadResult; import com.ifeng.recom.mixrecall.common.model.UserModel; import com.ifeng.recom.mixrecall.common.model.request.LogicParams; import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo; import com.ifeng.recom.mixrecall.template.BaseTemplate; import javax.annotation.Resource; /** * 召回的增量和全量公用一个逻辑,只是调用量的size不同 * 处理用户订阅频道数据 * Created by jibin on 2018/1/19. */ @Service public class UserSubBehavior extends BaseTemplate<MixResult> { private static final Logger logger = LoggerFactory.getLogger(UserSubBehavior.class); @Autowired private RemoverHandlerService removerHandlerService; @Autowired private RecallExecutor recallThreadPool; @Resource(name = "recallUserSubThreadPool") private ThreadPoolExecutor poolExecutor; @Override public MixResult doRecom(MixRequestInfo mixRequestInfo) { TimerEntity timer = TimerEntityUtil.getInstance(); String uid = mixRequestInfo.getUid(); List<RecallConfig> recallConfigs = Lists.newArrayList(); List<IItemRemoveHandler<Document>> removeHandlers = removerHandlerService.buildCommonHandlers(mixRequestInfo); recallConfigs.add(RecallConfig.build().setBeanName(RecallChannelBeanName.COTAG_DOC).setRemoverList(removeHandlers)); recallConfigs.add(RecallConfig.build().setBeanName(RecallChannelBeanName.USER_SUB).setRemoverList(removeHandlers)); recallConfigs.add(RecallConfig.build().setBeanName(RecallChannelBeanName.PositiveFeedDocpic).setRemoverList(removeHandlers)); recallConfigs.add(RecallConfig.build().setBeanName(RecallChannelBeanName.PositiveFeedVideo).setRemoverList(removeHandlers)); recallConfigs.add(RecallConfig.build().setBeanName(RecallChannelBeanName.USER_CF_ALS).setRemoverList(removeHandlers)); recallConfigs.add(RecallConfig.build().setBeanName(RecallChannelBeanName.COTAG_V_N).setRemoverList(removeHandlers)); recallConfigs.add(RecallConfig.build().setBeanName(RecallChannelBeanName.COTAG_V).setRemoverList(removeHandlers)); timer.addStartTime("getAsyncExecutorResult"); List<RecallChannelResult> channelResults = recallThreadPool.recall(mixRequestInfo, recallConfigs, 500, poolExecutor); logger.info("recall channel statistics result:{}, uid:{}", recallThreadPool.storeLoggerInfo(channelResults), uid); Map<RecallConstant.CHANNEL, List<RecallResult>> channelDocsMap = recallThreadPool.change(channelResults); timer.addEndTime("getAsyncExecutorResult"); List<RecallResult> userCFList = channelDocsMap.getOrDefault(RecallConstant.CHANNEL.USER_CF_ALS, Collections.emptyList()); List<RecallResult> cotagList = channelDocsMap.getOrDefault(RecallConstant.CHANNEL.COTAG_DOC, Collections.emptyList()); List<RecallResult> posVideos = channelDocsMap.getOrDefault(RecallConstant.CHANNEL.PositiveFeedVideo, Collections.emptyList()); List<RecallResult> posDocpics = channelDocsMap.getOrDefault(RecallConstant.CHANNEL.PositiveFeedDocpic, Collections.emptyList()); List<RecallResult> cotagVideoN = channelDocsMap.getOrDefault(RecallConstant.CHANNEL.COTAG_V_N, new ArrayList<>()); List<RecallResult> cotagVideoNew = channelDocsMap.getOrDefault(RecallConstant.CHANNEL.COTAG_V, new ArrayList<>()); List<RecallResult> userSub = channelDocsMap.getOrDefault(RecallConstant.CHANNEL.USER_SUB, Collections.emptyList()); List<RecallResult> resultDocs = outputChannelNumControl(mixRequestInfo, cotagList, userCFList, posDocpics, posVideos, userSub,cotagVideoNew,cotagVideoN); //debug 日志 if (mixRequestInfo.isDebugUser()) { for (RecallResult recallResult : resultDocs) { logger.info("uid:{} docId:{} title:{} channel:{} debug:{}", uid, recallResult.getDocument().getDocId(), recallResult.getDocument().getTitle(), recallResult.getWhyReason().getValue(), recallResult.getRecallTag()); } } return buildMixResult(mixRequestInfo, resultDocs, GyConstant.isOldResult); } private static List<RecallResult> outputChannelNumControl(MixRequestInfo mixRequestInfo, List<RecallResult> cotag, List<RecallResult> userCF, List<RecallResult> posVideo, List<RecallResult> posDocpic, List<RecallResult> userSub , List<RecallResult> cotagVideoNew, List<RecallResult> cotagVideoN) { LogicParams logicParams = mixRequestInfo.getLogicParams(); int needNum = logicParams.getResult_size(); List<RecallResult> results = new ArrayList<>(); //修改为比例控制 int posDocpicNum = (int) (0.1 * needNum); int posVideoNum = (int) (0.1 * needNum); results.addAll(userSub); results.addAll(userCF.subList(0, Math.min(100, userCF.size()))); results.addAll(posDocpic.subList(0, Math.min(posDocpicNum, posDocpic.size()))); results.addAll(posVideo.subList(0, Math.min(posVideoNum, posVideo.size()))); results.addAll(cotag.subList(0, Math.min(needNum, cotag.size()))); results.addAll(cotagVideoNew.subList(0, Math.min(needNum, cotagVideoNew.size()))); results.addAll(cotagVideoN.subList(0, Math.min(needNum, cotagVideoN.size()))); return results; } }
package com.library.source; import java.util.ArrayList; public class MethodObj implements Comparable<MethodObj> { public String returnType; public String methodName; public ArrayList<String> inputParam; public String scope; public String fullMethodName; public String packageName; public Double frequency; public MethodObj(String returnType, String methodName, String scope) { inputParam = new ArrayList<String>(); this.returnType = returnType; this.methodName = methodName; this.scope = scope; } public MethodObj() { inputParam = new ArrayList<String>(); this.returnType = ""; this.methodName = ""; this.scope = ""; this.fullMethodName = ""; } public void addInputParam(String inputType) { inputParam.add(inputType.trim()); } public String getInputParamAsString() { String inputParams = ""; for (String param : inputParam) { if (inputParams == "") { inputParams = param; } else { inputParams = inputParams + "," + param; } } return inputParams; } public int countOfInputParam() { return inputParam.size(); } // TODO: need to be able to process method like sum({1,2,3}) // This function recive line of code and return method signture public static MethodObj GenerateSignature(String lineCode) { lineCode = lineCode.trim(); MethodObj methodObj = new MethodObj(); // find index of input param int startParamIndex = lineCode.indexOf("("); int endParamIndex = lineCode.lastIndexOf(")"); if (startParamIndex == -1 || endParamIndex == -1) { // System.err.println("line donot have method: "+ lineCode); return null; } String inputTypes = lineCode.substring(startParamIndex + 1, endParamIndex).trim(); inputTypes = inputTypes.replaceAll("<([^<]*)>", "<T>"); // replace Answer1<T,A> to Answer1<T> avoid bad split // save all input param in list if (inputTypes.indexOf(",") > 0) { String[] paramsSP = inputTypes.split(","); for (String inputType : paramsSP) { methodObj.addInputParam(inputType.trim()); } } else { // has only one param if (inputTypes.length() > 0) { methodObj.addInputParam(inputTypes.trim()); } } // find function name String nameWithDefine = lineCode.substring(0, startParamIndex).trim(); if (nameWithDefine.indexOf(" ") > 0) { // find function name int startNameIndex = nameWithDefine.lastIndexOf(" "); methodObj.methodName = lineCode.substring(startNameIndex + 1, nameWithDefine.length()).trim(); // find return type String returnTypeWithDefine = lineCode.substring(0, startNameIndex).trim(); if (returnTypeWithDefine.indexOf(" ") > 0) { int startReturnTypeIndex = returnTypeWithDefine.lastIndexOf(" "); methodObj.returnType = returnTypeWithDefine .substring(startReturnTypeIndex + 1, returnTypeWithDefine.length()).trim(); // find scope methodObj.scope = lineCode.substring(0, startReturnTypeIndex).trim(); } else { methodObj.returnType = returnTypeWithDefine; } } else { methodObj.methodName = nameWithDefine; } // check if their is static instance methodObj.packageName = getPackageName(methodObj.methodName); methodObj.methodName = removeDot(methodObj.methodName); methodObj.fullMethodName = lineCode; if (methodObj.returnType.equals("public") || methodObj.returnType.equals("protected") || methodObj.returnType.equals("private")) { methodObj.scope = methodObj.returnType; methodObj.returnType = "void"; } return methodObj; } // Get name without packages public static String removeDot(String name) { // remove donts it it found if (name.contains(".")) { int lastDotIndex = name.lastIndexOf("."); name = name.substring(lastDotIndex + 1, name.length()).trim(); } return name; } // Get name without packages public static String getPackageName(String name) { // remove donts it it found if (name.contains(".")) { int lastDotIndex = name.lastIndexOf("."); name = name.substring(0, lastDotIndex).trim(); } else { name = ""; } return name; } // Get name without packages public String getMethodNameWithoutPackage() { String name = this.methodName; // remove donts it it found if (name.contains(".")) { int lastDotIndex = name.lastIndexOf("."); name = name.substring(lastDotIndex + 1, name.length()).trim(); } return name; } public static void main(String[] args) { MethodObj methodObj = GenerateSignature("public static LogicalOperator valueOf(long.n name)"); MethodObj methodObj1 = GenerateSignature("public static LogicalOperator valueOf(log.java.string name)"); System.out.println(methodObj.inputParamDataType(methodObj1)); } public boolean inputParamCompare(MethodObj otherMethodObj) { boolean isEqual = false; // in case they have same number of param if (this.countOfInputParam() == otherMethodObj.countOfInputParam()) { isEqual = true; } /* * in case we compare with '...' that could have any number of param public * static void verify(java.lang.Object...); */ if (isEqual == false && countOfInputParam() == 1) { if (this.inputParam.get(0).endsWith("...")) { isEqual = true; } } if (isEqual == false && otherMethodObj.countOfInputParam() == 1) { if (otherMethodObj.inputParam.get(0).endsWith("...")) { isEqual = true; } } return isEqual; } public boolean inputParamDataType(MethodObj otherMethodObj) { if (this.countOfInputParam() == otherMethodObj.countOfInputParam() && this.countOfInputParam() == 0) { return true; } if (this.countOfInputParam() != otherMethodObj.countOfInputParam()) { return false; } int countOfParams = 0; // System.out.println(this.fullMethodName +"<===>"+ // otherMethodObj.fullMethodName); // System.out.println(this.inputParam); ArrayList<String> listOfMyParams = new ArrayList<String>(); listOfMyParams.addAll(this.inputParam); ArrayList<String> listOfOtherParams = new ArrayList<String>(); listOfOtherParams.addAll(otherMethodObj.inputParam); // System.out.println(otherMethodObj.inputParam); for (int i = 0; i < listOfMyParams.size(); i++) { String meDataType = listOfMyParams.get(i).trim(); String[] inputPramaSp = meDataType.split(" "); meDataType = inputPramaSp[0]; // System.out.println("==>"+ inputPramaSp.length); if (meDataType.contains(".")) { String[] inputPramaOtherSp = meDataType.split("\\."); meDataType = inputPramaOtherSp[inputPramaOtherSp.length - 1]; } // System.out.println("=="+ meDataType); // System.out.println(meDataType); if (inputPramaSp.length < 1) { continue; } // System.out.println(inputPramaSp[0]); for (int j = 0; j < listOfOtherParams.size(); j++) { String[] inputPramaOtherSp = listOfOtherParams.get(j).trim().split("\\s+"); String otherDataType = inputPramaOtherSp[0]; if (otherDataType.contains(".")) { inputPramaOtherSp = otherDataType.split("\\."); otherDataType = inputPramaOtherSp[inputPramaOtherSp.length - 1]; } // System.out.println("=="+ meDataType); // System.out.println("=="+ otherDataType); // System.out.println(otherDataType); // if(inputPramaOtherSp.length<1){ continue;} // System.out.println(inputPramaOtherSp[inputPramaOtherSp.length-1] +"="+ // inputPramaSp[0]); if (otherDataType.toLowerCase().startsWith(meDataType.toLowerCase())) { listOfOtherParams.remove(j); countOfParams++; break; } } } // System.out.println(countOfParams); // System.out.println((countOfParams == otherMethodObj.inputParam.size()) // &&(countOfParams == this.inputParam.size())); return (countOfParams == otherMethodObj.inputParam.size()) && (countOfParams == this.inputParam.size()); } public double inputParamComparePercent(MethodObj otherMethodObj) { double isEqual = 0; // in case they have same number of param if (this.countOfInputParam() == otherMethodObj.countOfInputParam()) { isEqual = 1.0; } /* * in case we compare with '...' that could have any number of param public * static void verify(java.lang.Object...); */ if (isEqual == 0 && countOfInputParam() == 1) { if (this.inputParam.get(0).endsWith("...")) { isEqual = 1.0; } } if (isEqual == 0 && otherMethodObj.countOfInputParam() == 1) { if (otherMethodObj.inputParam.get(0).endsWith("...")) { isEqual = 1.0; } } return Math.abs((this.countOfInputParam() - otherMethodObj.countOfInputParam())); } // Show different in Ratio public double inputParamCompareRatio(MethodObj otherMethodObj) { double diffRation = inputParamComparePercent(otherMethodObj); if (diffRation > 1) { diffRation = 1.0 - (diffRation / ((this.countOfInputParam() + otherMethodObj.countOfInputParam()) * 1.0)); } return diffRation; } public boolean inputParamDataTypeCompare(MethodObj otherMethodObj) { boolean isEqual = true; // in case they have same number of param if (this.countOfInputParam() == otherMethodObj.countOfInputParam()) { for (int i = 0; i < this.countOfInputParam(); i++) { if (this.inputParam.get(i) != otherMethodObj.inputParam.get(i)) { isEqual = false; break; } } } else { isEqual = false; } return isEqual; } /* * see if two methods has good match To have excellent match they should be * similar in number of params and not abstruct */ boolean hasGoodMatch(String functionSignature) { boolean hasGoodMatch = true; // We prefer method name over abstruct name,if we cannot find method we will use // abstruct if (functionSignature.contains("abstract ") == false) { hasGoodMatch = false; } if (hasGoodMatch == true && this.countOfInputParam() == 1) { if (this.inputParam.get(0).endsWith("...")) { hasGoodMatch = false; } } return hasGoodMatch; } public void print() { System.out.println(this.fullMethodName); System.out.println("Method Name: " + this.methodName); System.out.println("Return Type: " + this.returnType); if (this.scope.length() > 0) { // TODO: return this System.out.println("Scope: "+this.scope); } if (this.packageName.length() > 0) { System.out.println("Package Name: " + this.packageName); } int index = 1; for (String param : this.inputParam) { System.out.println("Input Params(" + (index++) + ")==> " + param); } if (this.inputParam.size() > 0) { System.out.println("All input Params: " + getInputParamAsString()); } System.out.println("-------------------------"); } public int compareTo(MethodObj o) { // TODO Auto-generated method stub return (int) (o.frequency - this.frequency); } }
package com.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 FormController { @RequestMapping("/showForm") public String showForm() { return "show-form"; } @RequestMapping("/processForm") public String processForm() { return "process-form"; } @RequestMapping("/customProcessForm") public String customformProcess(HttpServletRequest request, Model model) { String name = request.getParameter("studentName"); String nameModified = "Yo! " + name.toUpperCase(); model.addAttribute("message", nameModified); return "processed-form"; } }
package com.flyingh.engine; public interface ILockService { public void unlock(String packageName); }
package video.api.android.sdk.domain; import video.api.android.sdk.domain.analytic.AnalyticLive; import video.api.android.sdk.domain.pagination.AnalyticsFilter; import video.api.android.sdk.domain.pagination.Pager; import video.api.android.sdk.domain.pagination.PagerBuilder; public interface AnalyticsLiveClient { void getLiveAnalytics(String liveStreamId, String period, ResponseListener<AnalyticLive> analyticsLiveResponseListener, ResponseErrorListener responseErrorListener); Pager<AnalyticLive> search(String period, PagerBuilder pagerBuilder, AnalyticsFilter analyticsFilter); Pager<AnalyticLive> search(String period, AnalyticsFilter analyticsFilter); Pager<AnalyticLive> list(String period, PagerBuilder pagerBuilder); Pager<AnalyticLive> list(String period); }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.Method; public class Main { public static void main(String args[]) { expectEqualsByte((byte)1, booleanToByte(true)); expectEqualsShort((short)1, booleanToShort(true)); expectEqualsChar((char)1, booleanToChar(true)); expectEqualsInt(1, booleanToInt(true)); expectEqualsLong(1L, booleanToLong(true)); expectEqualsLong(1L, $noinline$runSmaliTest("booleanToLong", true)); expectEqualsInt(1, longToIntOfBoolean()); expectEqualsInt(1, $noinline$runSmaliTest("longToIntOfBoolean")); System.out.println("passed"); } /// CHECK-START: byte Main.booleanToByte(boolean) instruction_simplifier$after_bce (after) /// CHECK: <<Arg:z\d+>> ParameterValue /// CHECK-DAG: Return [<<Arg>>] static byte booleanToByte(boolean b) { return (byte)(b ? 1 : 0); } /// CHECK-START: short Main.booleanToShort(boolean) instruction_simplifier$after_bce (after) /// CHECK: <<Arg:z\d+>> ParameterValue /// CHECK-DAG: Return [<<Arg>>] static short booleanToShort(boolean b) { return (short)(b ? 1 : 0); } /// CHECK-START: char Main.booleanToChar(boolean) instruction_simplifier$after_bce (after) /// CHECK: <<Arg:z\d+>> ParameterValue /// CHECK-DAG: Return [<<Arg>>] static char booleanToChar(boolean b) { return (char)(b ? 1 : 0); } /// CHECK-START: int Main.booleanToInt(boolean) instruction_simplifier$after_bce (after) /// CHECK: <<Arg:z\d+>> ParameterValue /// CHECK-DAG: Return [<<Arg>>] static int booleanToInt(boolean b) { return b ? 1 : 0; } /// CHECK-START: long Main.booleanToLong(boolean) builder (after) /// CHECK: <<Arg:z\d+>> ParameterValue /// CHECK-DAG: <<IZero:i\d+>> IntConstant 0 /// CHECK-DAG: <<Zero:j\d+>> LongConstant 0 /// CHECK-DAG: <<One:j\d+>> LongConstant 1 /// CHECK-DAG: <<Cond:z\d+>> Equal [<<Arg>>,<<IZero>>] /// CHECK-DAG: If [<<Cond>>] /// CHECK-DAG: <<Phi:j\d+>> Phi [<<One>>,<<Zero>>] /// CHECK-DAG: Return [<<Phi>>] /// CHECK-START: long Main.booleanToLong(boolean) select_generator (after) /// CHECK-NOT: IntConstant /// CHECK-NOT: Equal /// CHECK-NOT: If /// CHECK-NOT: Phi /// CHECK-START: long Main.booleanToLong(boolean) select_generator (after) /// CHECK: <<Arg:z\d+>> ParameterValue /// CHECK-DAG: <<Zero:j\d+>> LongConstant 0 /// CHECK-DAG: <<One:j\d+>> LongConstant 1 /// CHECK-DAG: <<Sel:j\d+>> Select [<<Zero>>,<<One>>,<<Arg>>] /// CHECK-DAG: Return [<<Sel>>] // As of now, the code is not optimized any further than the above. // TODO: Re-enable checks below after simplifier is updated to handle this pattern: b/63064517 // CHECK-START: long Main.booleanToLong(boolean) instruction_simplifier$after_bce (after) // CHECK: <<Arg:z\d+>> ParameterValue // CHECK-DAG: <<ZToJ:j\d+>> TypeConversion [<<Arg>>] // CHECK-DAG: Return [<<ZToJ>>] static long booleanToLong(boolean b) { return b ? 1 : 0; } /// CHECK-START: int Main.longToIntOfBoolean() builder (after) /// CHECK-DAG: <<Sget:z\d+>> StaticFieldGet /// CHECK-DAG: <<ZToJ:j\d+>> InvokeStaticOrDirect [<<Sget>>{{(,[ij]\d+)?}}] /// CHECK-DAG: <<JToI:i\d+>> TypeConversion [<<ZToJ>>] /// CHECK-DAG: Return [<<JToI>>] /// CHECK-START: int Main.longToIntOfBoolean() inliner (after) /// CHECK-DAG: <<Zero:j\d+>> LongConstant 0 /// CHECK-DAG: <<One:j\d+>> LongConstant 1 /// CHECK-DAG: <<Sget:z\d+>> StaticFieldGet /// CHECK-DAG: If [<<Sget>>] /// CHECK-DAG: <<Phi:j\d+>> Phi [<<One>>,<<Zero>>] /// CHECK-DAG: <<JToI:i\d+>> TypeConversion [<<Phi>>] /// CHECK-DAG: Return [<<JToI>>] /// CHECK-START: long Main.booleanToLong(boolean) select_generator (after) /// CHECK-NOT: IntConstant /// CHECK-NOT: Equal /// CHECK-NOT: If /// CHECK-NOT: Phi /// CHECK-START: int Main.longToIntOfBoolean() select_generator (after) /// CHECK-DAG: <<Zero:j\d+>> LongConstant 0 /// CHECK-DAG: <<One:j\d+>> LongConstant 1 /// CHECK-DAG: <<Sget:z\d+>> StaticFieldGet /// CHECK-DAG: <<Sel:j\d+>> Select [<<Zero>>,<<One>>,<<Sget>>] /// CHECK-DAG: <<JToI:i\d+>> TypeConversion [<<Sel>>] /// CHECK-DAG: Return [<<JToI>>] // As of now, the code is not optimized any further than the above. // TODO: Re-enable checks below after simplifier is updated to handle this pattern: b/63064517 // CHECK-START: int Main.longToIntOfBoolean() instruction_simplifier$after_bce (after) // CHECK-DAG: <<Sget:z\d+>> StaticFieldGet // CHECK-DAG: Return [<<Sget>>] static int longToIntOfBoolean() { long l = booleanToLong(booleanField); return (int) l; } private static void expectEqualsByte(byte expected, byte result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } private static void expectEqualsShort(short expected, short result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } private static void expectEqualsChar(char expected, char result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } private static void expectEqualsInt(int expected, int result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } private static void expectEqualsLong(long expected, long result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } public static long $noinline$runSmaliTest(String name, boolean input) { try { Class<?> c = Class.forName("SmaliTests"); Method m = c.getMethod(name, boolean.class); return (Long) m.invoke(null, input); } catch (Exception ex) { throw new Error(ex); } } public static int $noinline$runSmaliTest(String name) { try { Class<?> c = Class.forName("SmaliTests"); Method m = c.getMethod(name); return (Integer) m.invoke(null); } catch (Exception ex) { throw new Error(ex); } } public static boolean booleanField = true; }
package com.example.web.client; import com.example.soap.ProductClient; import com.example.soap.product.ProductModel; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.Collections; import java.util.List; @Slf4j @Controller @RequiredArgsConstructor public class SoapController { private final ProductClient productClient; @GetMapping({"/soap"}) public String index() { return "soap"; } }
package fr.pantheonsorbonne.miage; import java.io.IOException; public class FailedException extends RuntimeException { public FailedException(String string, IOException e) { super(string,e); } public FailedException(String string, Exception e) { super(string,e); } /** * */ private static final long serialVersionUID = 1L; }
package tech.liujin.drawable.progress.load; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint.Style; import android.graphics.Rect; import android.support.annotation.NonNull; import tech.liujin.drawable.progress.ProgressDrawable; /** * @author Liujin 2018-11-15:22:10 */ public class BallPulseDrawable extends ProgressDrawable { private static final int COUNT = 3; private float mRadius; private float mMinScale = 0.1f; private float mMinRadius; private float mDRadius; private float[] mRadiusArray = new float[ 3 ]; public BallPulseDrawable ( ) { super(); mPaint.setStyle( Style.FILL ); mPaint.setColor( Color.RED ); } @Override protected void onBoundsChange ( Rect bounds ) { int size = Math.min( bounds.width(), bounds.height() ); mRadius = size * 1f / 6; mMinRadius = mRadius * mMinScale; mDRadius = mRadius - mMinRadius; super.onBoundsChange( bounds ); } @Override public void onProcessChange ( float progress ) { mProgress = progress; mRadiusArray[ 0 ] = calculateRadius( calculateProgress( progress ) ); mRadiusArray[ 1 ] = calculateRadius( calculateProgress( progress - 0.2f ) ); mRadiusArray[ 2 ] = calculateRadius( calculateProgress( progress - 0.4f ) ); invalidateSelf(); } @Override public void draw ( @NonNull Canvas canvas ) { int dX = ( getWidth() ) >> 1; int dY = ( getHeight() ) >> 1; canvas.translate( dX, dY ); canvas.drawCircle( -mRadius * 2, 0, mRadiusArray[ 0 ], mPaint ); canvas.drawCircle( 0, 0, mRadiusArray[ 1 ], mPaint ); canvas.drawCircle( mRadius * 2, 0, mRadiusArray[ 2 ], mPaint ); } private float calculateProgress ( float progress ) { if( progress < 0f ) { progress = -progress; } if( progress <= 0.5f ) { progress *= 2; } else { progress = ( 1f - progress ) * 2; } return progress; } private float calculateRadius ( float progress ) { return mMinRadius + mDRadius * ( progress ); } public void setMinScale ( float minScale ) { mMinScale = minScale; } public float getMinScale ( ) { return mMinScale; } }
package algorithms.fundamentals.divideconquer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; @Configuration public class DivideConquerContext { @Bean public MatrixMultiply standardMM() { return new StandardMatrixMultiply(); } @Bean public MatrixMultiply recursiveMM() { return new RecursiveMatrixMultiply(); } @Bean public MatrixMultiplyDivideConquer strassenMethod() { return new StrassenMethod(); } @Bean public MatrixMultiplyDivideConquer winogradMethod() { return new WinogradMethod(); } @Bean @Scope(scopeName = "prototype") public MatrixMultiply standardStrassenMM() { StandardStrassenMM mm = new StandardStrassenMM(); mm.setCutoffSize(1); mm.setMatrixMultiplyDivideConquer(strassenMethod()); mm.setName("standardStrassenMM"); return mm; } @Bean @Scope(scopeName = "prototype") public MatrixMultiply standardWinogradMM() { StandardStrassenMM mm = new StandardStrassenMM(); mm.setCutoffSize(1); mm.setMatrixMultiplyDivideConquer(winogradMethod()); mm.setName("standardWinogradMM"); return mm; } @Bean @Scope(scopeName = "prototype") public MatrixMultiply dynamicPaddingStrassenMM() { DynamicPaddingStrassenMM mm = new DynamicPaddingStrassenMM(); mm.setCutoffSize(1); mm.setMatrixMultiplyDivideConquer(strassenMethod()); mm.setName("dynamicPaddingStrassenMM"); return mm; } @Bean @Scope(scopeName = "prototype") public MatrixMultiply dynamicPeelingStrassenMM() { DynamicPeelingStrassenMM mm = new DynamicPeelingStrassenMM(); mm.setCutoffSize(1); mm.setMatrixMultiplyDivideConquer(strassenMethod()); mm.setName("dynamicPeelingStrassenMM"); return mm; } @Bean @Scope(scopeName = "prototype") public MatrixMultiply dynamicPaddingWinogradMM() { DynamicPaddingStrassenMM mm = new DynamicPaddingStrassenMM(); mm.setCutoffSize(1); mm.setMatrixMultiplyDivideConquer(winogradMethod()); mm.setName("dynamicPaddingWinogradMM"); return mm; } @Bean @Scope(scopeName = "prototype") public MatrixMultiply dynamicPeelingWinogradMM() { DynamicPeelingStrassenMM mm = new DynamicPeelingStrassenMM(); mm.setCutoffSize(1); mm.setMatrixMultiplyDivideConquer(winogradMethod()); mm.setName("dynamicPeelingWinogradMM"); return mm; } }
/** * */ package net.sf.taverna.t2.component.ui.panel; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.sf.taverna.t2.component.api.Family; import net.sf.taverna.t2.component.api.Registry; import net.sf.taverna.t2.component.api.Version; import net.sf.taverna.t2.component.registry.ComponentVersionIdentification; import org.apache.commons.lang.StringUtils; /** * @author alanrw * */ public class RegisteryAndFamilyChooserComponentEntryPanel extends JPanel { /** * */ private static final long serialVersionUID = -6675545311458594678L; private static final String T2FLOW = ".t2flow"; private JTextField componentNameField = new JTextField(20); private RegistryAndFamilyChooserPanel registryAndFamilyChooserPanel = new RegistryAndFamilyChooserPanel(); public RegisteryAndFamilyChooserComponentEntryPanel() { this.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; gbc.weightx = 1; this.add(registryAndFamilyChooserPanel, gbc); gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridx = 0; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; this.add(new JLabel("Component name:"), gbc); gbc.gridx = 1; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(componentNameField, gbc); } public String getComponentName() { return componentNameField.getText(); } public void setComponentName(String name) { componentNameField.setText(name); } public Version.ID getComponentVersionIdentification() { String componentName = getComponentName(); Family familyChoice = registryAndFamilyChooserPanel.getChosenFamily(); Registry registry = registryAndFamilyChooserPanel.getChosenRegistry(); if ((familyChoice == null) || (registry == null) || (componentName == null) || componentName.isEmpty()) { return null; } componentName = StringUtils.remove(componentName, T2FLOW); Version.ID ident = new ComponentVersionIdentification( registry.getRegistryBase(), familyChoice.getName(), componentName, -1); return ident; } }
package com.energytrade.app.model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the cancelled_by_pl database table. * */ @Entity @Table(name="cancelled_by_pl") @NamedQuery(name="CancelledByPl.findAll", query="SELECT c FROM CancelledByPl c") public class CancelledByPl implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="cancelled_by_id") private int cancelledById; @Column(name="cancelled_by_desc") private String cancelledByDesc; @Column(name="cancelled_by_name") private String cancelledByName; @Column(name="created_by") private String createdBy; @Temporal(TemporalType.TIMESTAMP) @Column(name="created_ts") private Date createdTs; private byte softdeleteflag; @Temporal(TemporalType.TIMESTAMP) @Column(name="sync_ts") private Date syncTs; @Column(name="updated_by") private String updatedBy; @Temporal(TemporalType.TIMESTAMP) @Column(name="updated_ts") private Date updatedTs; //bi-directional many-to-one association to AllContract @OneToMany(mappedBy="cancelledByPl") private List<AllContract> allContracts; public CancelledByPl() { } public int getCancelledById() { return this.cancelledById; } public void setCancelledById(int cancelledById) { this.cancelledById = cancelledById; } public String getCancelledByDesc() { return this.cancelledByDesc; } public void setCancelledByDesc(String cancelledByDesc) { this.cancelledByDesc = cancelledByDesc; } public String getCancelledByName() { return this.cancelledByName; } public void setCancelledByName(String cancelledByName) { this.cancelledByName = cancelledByName; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedTs() { return this.createdTs; } public void setCreatedTs(Date createdTs) { this.createdTs = createdTs; } public byte getSoftdeleteflag() { return this.softdeleteflag; } public void setSoftdeleteflag(byte softdeleteflag) { this.softdeleteflag = softdeleteflag; } public Date getSyncTs() { return this.syncTs; } public void setSyncTs(Date syncTs) { this.syncTs = syncTs; } public String getUpdatedBy() { return this.updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedTs() { return this.updatedTs; } public void setUpdatedTs(Date updatedTs) { this.updatedTs = updatedTs; } public List<AllContract> getAllContracts() { return this.allContracts; } public void setAllContracts(List<AllContract> allContracts) { this.allContracts = allContracts; } public AllContract addAllContract(AllContract allContract) { getAllContracts().add(allContract); allContract.setCancelledByPl(this); return allContract; } public AllContract removeAllContract(AllContract allContract) { getAllContracts().remove(allContract); allContract.setCancelledByPl(null); return allContract; } }
package com.tianwotian.tools; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by user on 2016/9/7. */ public class LoadImageFromServer { public static InputStream getImageViewInputStream(String URL_PATH) throws IOException { InputStream inputStream = null; URL url = new URL(URL_PATH); //服务器地址 //打开连接 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(3000);//设置网络连接超时的时间为3秒 httpURLConnection.setRequestMethod("GET"); //设置请求方法为GET httpURLConnection.setDoInput(true); //打开输入流 int responseCode = httpURLConnection.getResponseCode(); // 获取服务器响应值 if (responseCode == HttpURLConnection.HTTP_OK) //正常连接 inputStream = httpURLConnection.getInputStream(); //获取输入流 return inputStream; } }
package jire.packet; public abstract class PacketEvent { private final Packet packet; protected PacketEvent(Packet packet) { this.packet = packet; } public final Packet getPacket() { return packet; } }
package com.tessoft.nearhere.activities; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import com.tessoft.common.Constants; import com.tessoft.common.Util; import com.tessoft.domain.APIResponse; import com.tessoft.domain.Post; import com.tessoft.domain.User; import com.tessoft.domain.UserLocation; import com.tessoft.nearhere.PhotoViewer; import com.tessoft.nearhere.R; import com.tessoft.nearhere.adapters.TaxiArrayAdapter; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.type.TypeReference; import java.io.IOException; import java.util.HashMap; import java.util.List; public class UserProfileActivity extends BaseActivity { ListView listMain = null; View header = null; View footer = null; TaxiArrayAdapter adapter = null; DisplayImageOptions options = null; @Override protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_profile); header = getLayoutInflater().inflate(R.layout.user_profile_list_header, null); footer = getLayoutInflater().inflate(R.layout.user_profile_list_footer, null); listMain = (ListView) findViewById(R.id.listMain); listMain.addHeaderView(header, null, false ); adapter = new TaxiArrayAdapter( this , this, 0); listMain.setAdapter(adapter); listMain.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub if ( arg1.getTag() != null && arg1.getTag() instanceof Post ) { Post post = (Post) arg1.getTag(); Intent intent = new Intent( getApplicationContext(), TaxiPostDetailActivity.class); intent.putExtra("postID", post.getPostID()); startActivity(intent); overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left); } } }); footer.findViewById(R.id.txtNone).setVisibility(ViewGroup.GONE); inquiryUserInfo(); ImageView imgProfile = (ImageView) header.findViewById(R.id.imgProfile); imgProfile.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if ( v.getTag() != null ) { Intent intent = new Intent( getApplicationContext(), PhotoViewer.class); intent.putExtra("imageURL", v.getTag().toString()); startActivity(intent); overridePendingTransition(R.anim.fade_in, R.anim.stay); } } }); options = new DisplayImageOptions.Builder() .resetViewBeforeLoading(true) .cacheInMemory(true) .showImageOnLoading(R.drawable.no_image) .showImageForEmptyUri(R.drawable.no_image) .showImageOnFail(R.drawable.no_image) .displayer(new RoundedBitmapDisplayer(20)) .delayBeforeLoading(100) .build(); setTitle("사용자정보"); Button btnRefresh = (Button) findViewById(R.id.btnRefresh); btnRefresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { inquiryUserInfo(); } catch ( Exception ex ) { // TODO Auto-generated catch block catchException(this, ex); } } }); if ( getIntent().getExtras().getString("userID").equals( application.getLoginUser().getUserID() )) header.findViewById(R.id.btnSendMessage).setVisibility(ViewGroup.GONE); else header.findViewById(R.id.btnSendMessage).setVisibility(ViewGroup.VISIBLE); } catch( Exception ex ) { Log.e("error", ex.getMessage()); } } protected void setTitle( String title ) { TextView txtTitle = (TextView) findViewById(R.id.txtTitle); txtTitle.setText( title ); } private void inquiryUserInfo() throws IOException, JsonGenerationException, JsonMappingException { findViewById(R.id.marker_progress).setVisibility(ViewGroup.VISIBLE); listMain.setVisibility(ViewGroup.GONE); HashMap hash = application.getDefaultRequest(); hash.put("userID", application.getLoginUser().getUserID() ); hash.put("userIDToInquiry", getIntent().getExtras().getString("userID")); sendHttp("/taxi/getUserInfoV2.do", mapper.writeValueAsString( hash ), 1); } @SuppressWarnings({ "rawtypes", "unchecked"}) public void goUserMessageActivity( View v ) { if ( "Guest".equals( application.getLoginUser().getType())) { showOKDialog("확인", "SNS 계정연동 후에 등록하실 수 있습니다.\r\n\r\n메인 화면에서 SNS연동을 할 수 있습니다.", "kakaoLoginCheck" ); return; } HashMap hash = new HashMap(); hash.put("fromUserID", getIntent().getExtras().getString("userID") ); hash.put("userID", application.getLoginUser().getUserID() ); Intent intent = new Intent( this, UserMessageActivity.class); intent.putExtra("messageInfo", hash ); startActivity(intent); overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left); } @Override public void finish() { // TODO Auto-generated method stub super.finish(); if ( getIntent().getExtras() != null && getIntent().getExtras().containsKey("anim1") ) { overridePendingTransition( getIntent().getExtras().getInt("anim1"), getIntent().getExtras().getInt("anim2")); } else this.overridePendingTransition(R.anim.stay, R.anim.slide_out_to_bottom); } @Override public void doPostTransaction(int requestCode, Object result) { // TODO Auto-generated method stub try { findViewById(R.id.marker_progress).setVisibility(ViewGroup.GONE); if ( Constants.FAIL.equals(result) ) { showOKDialog("통신중 오류가 발생했습니다.\r\n다시 시도해 주십시오.", null); return; } listMain.setVisibility(ViewGroup.VISIBLE); super.doPostTransaction(requestCode, result); APIResponse response = mapper.readValue(result.toString(), new TypeReference<APIResponse>(){}); if ( "0000".equals( response.getResCode() ) ) { if ( requestCode == 1 ) { HashMap hash = (HashMap) response.getData(); String userString = mapper.writeValueAsString( hash.get("user") ); String locationListString = mapper.writeValueAsString( hash.get("locationList") ); String userPostString = mapper.writeValueAsString( hash.get("userPost") ); String postsUserRepliedString = mapper.writeValueAsString( hash.get("postsUserReplied") ); User user = mapper.readValue(userString, new TypeReference<User>(){}); List<UserLocation> locationList = mapper.readValue(locationListString, new TypeReference<List<UserLocation>>(){}); List<Post> postList = mapper.readValue(userPostString, new TypeReference<List<Post>>(){}); List<Post> userPostsReplied = mapper.readValue(postsUserRepliedString, new TypeReference<List<Post>>(){}); postList.addAll( userPostsReplied ); ImageView imgProfile = (ImageView) header.findViewById(R.id.imgProfile); imgProfile.setImageResource(R.drawable.no_image); if ( user != null && user.getProfileImageURL() != null && user.getProfileImageURL().isEmpty() == false ) { ImageLoader.getInstance().displayImage( Constants.getThumbnailImageURL() + user.getProfileImageURL() , imgProfile, options); imgProfile.setTag(user.getProfileImageURL()); } TextView txtUserName = (TextView) header.findViewById(R.id.txtUserName); if ( !Util.isEmptyString( user.getUserName() ) ) txtUserName.setText( user.getUserName() ); TextView txtCreditValue = (TextView) header.findViewById(R.id.txtCreditValue); txtCreditValue.setText( user.getProfilePoint() + "%" ); ProgressBar progressCreditValue = (ProgressBar) header.findViewById(R.id.progressCreditValue); progressCreditValue.setProgress( Integer.parseInt( user.getProfilePoint() )); if ( user.getBirthday() != null && !"".equals( user.getBirthday() ) ) { String birthday = Util.getFormattedDateString(user.getBirthday(),"yyyy-MM-dd", "yyyy.MM.dd"); TextView txtBirthday = (TextView) header.findViewById(R.id.txtBirthday ); txtBirthday.setText( birthday ); } for ( int i = 0; i < locationList.size(); i++ ) { UserLocation loc = locationList.get(i); if ( "집".equals( loc.getLocationName() ) ) { TextView txtHomeLocation = (TextView) header.findViewById(R.id.txtHomeLocation); txtHomeLocation.setText( loc.getAddress() ); } else if ( "직장".equals( loc.getLocationName() )) { TextView txtOfficeLocation = (TextView) header.findViewById(R.id.txtOfficeLocation); txtOfficeLocation.setText( loc.getAddress() ); } } ImageView imgSex = (ImageView) header.findViewById(R.id.imgSex); TextView txtSex = (TextView) header.findViewById(R.id.txtSex); imgSex.setVisibility(ViewGroup.VISIBLE); if ( "M".equals( user.getSex() )) { imgSex.setImageResource(R.drawable.ic_male); txtSex.setText("남자"); } else if ( "F".equals( user.getSex() )) { imgSex.setImageResource(R.drawable.ic_female); txtSex.setText("여자"); } else imgSex.setVisibility(ViewGroup.GONE); if ( user.getJobTitle() != null && !"".equals( user.getJobTitle() )) { TextView txtJobTitle = (TextView) header.findViewById(R.id.txtJobTitle); txtJobTitle.setText( user.getJobTitle() ); } if ( !Util.isEmptyString( user.getKakaoID() ) ) findViewById(R.id.imgKakaoIcon).setVisibility(ViewGroup.VISIBLE); else findViewById(R.id.imgKakaoIcon).setVisibility(ViewGroup.GONE); if ( !Util.isEmptyString( user.getFacebookID() ) ) findViewById(R.id.imgFacebookIcon).setVisibility(ViewGroup.VISIBLE); else findViewById(R.id.imgFacebookIcon).setVisibility(ViewGroup.GONE); adapter.clear(); adapter.addAll(postList); adapter.notifyDataSetChanged(); if ( postList.size() == 0 ) footer.findViewById(R.id.txtNone).setVisibility(ViewGroup.VISIBLE); LinearLayout layoutFacebook = (LinearLayout) header.findViewById(R.id.layoutFacebook); if ( Util.isEmptyString( user.getFacebookID() ) ) layoutFacebook.setVisibility(ViewGroup.GONE); else { layoutFacebook.setVisibility(ViewGroup.VISIBLE); TextView txtFacebookURL = (TextView) header.findViewById(R.id.txtFacebookURL); txtFacebookURL.setTag( user.getFacebookURL() ); } } } else { showOKDialog("경고", response.getResMsg(), null); return; } } catch( Exception ex ) { catchException(this, ex); } } @Override public void onBackPressed() { finish(); if ( MainActivity.active == false ) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } } public void goFacebook( View v ) { if ( v != null && v.getTag() != null ) { try { String facebookURL = v.getTag().toString(); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( facebookURL )); startActivity(browserIntent); } catch( Exception ex ) { } } } }
package com.pwq.DesignPatterns.SimpleFactory.Component; /** * @Author:WenqiangPu * @Description * @Date:Created in 9:48 2017/10/12 * @Modified By: */ public abstract class Component {//抽象类实现 public abstract void add(Component component);//增加 public abstract void remove(Component component);//删除 public abstract Component get(int i);//查询 public abstract void operation();//操作 }
package cn.xuetang.common.dao; import java.io.BufferedReader; import java.sql.ResultSet; import org.nutz.log.Log; import org.nutz.log.Logs; /** * @author Wizzer.cn * @time 2012-9-13 下午6:13:55 * */ public class DBObject { private static final Log log = Logs.get(); /* * 获取CLOB字段值 */ public static String getClobBody(ResultSet rs, String colnumName) { String result = ""; try { String str_Clob = ""; StringBuffer strBuffer_CLob = new StringBuffer(); strBuffer_CLob.append(""); oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob(colnumName); BufferedReader in = new BufferedReader(clob.getCharacterStream()); while ((str_Clob = in.readLine()) != null) { strBuffer_CLob.append(str_Clob + "\n"); } in.close(); result = strBuffer_CLob.toString(); } catch (Exception e) { log.debug(e.getMessage()); } return result; } }
package com.clever.base; import android.content.Intent; import android.os.Bundle; import com.cleverlib.base.BaseActivity; import butterknife.ButterKnife; /** * Clever Activity基类 * * @author liuhea . * @created 16-12-2 . */ public class AppBaseActivity extends BaseActivity { @Override protected int getLayoutResId() { return 0; } @Override protected void onBeforeSetContentLayout() { super.onBeforeSetContentLayout(); } @Override protected void onAfterSetContentLayout(Bundle savedInstanceState) { super.onAfterSetContentLayout(savedInstanceState); ButterKnife.bind(this); } @Override protected void initView() { } @Override protected void initListener() { } @Override protected void initData() { } protected void startActivity(Class clazz, boolean isFinishSelf) { startActivity(new Intent(this, clazz)); if (isFinishSelf) { finish(); } } protected String getResString(int stringId) { return getResources().getString(stringId); } }
package uk.co.dyadica.unitymsband; import com.microsoft.band.BandClient; import com.microsoft.band.BandException; import com.microsoft.band.UserConsent; import com.microsoft.band.notifications.VibrationType; import com.microsoft.band.sensors.HeartRateConsentListener; import com.unity3d.player.UnityPlayer; import java.lang.reflect.Array; import java.util.Arrays; /** * Created by dyadica.co.uk on 02/01/2016. * This source is subject to the dyadica.co.uk Permissive License. * Please see the http://www.dyadica.co.uk/permissive-license file for more information. * All other rights reserved. * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ public class MsBand { // Ref the manager public MsBandManager bandManager; // Ref this bands client public BandClient client; // Set this bands id public int bandId; // Band Details // The firmware version public String fwVersion; // The hardware version public String hwVersion; // Default Band Sensors public Accelerometer accelerometer; public Gyroscope gyroscope; public HeartRate heartRate; public Calories calories; public Distance distance; public Contact contact; public Pedometer pedometer; public UVIndex uvIndex; public SkinTemperature skinTemperature; // Band 2 Sensors public Altimeter altimeter; public Gsr gsr; public Barometer barometer; public AmbientLight ambientLight; public RRInterval rrInterval; // An example tile to be created on a band device // public ExampleTile exampleTile; // Flag which will be used to identify the connection // state of the device. TBI! public boolean connected = false; /** * * @param client * @param bandManager */ public MsBand(BandClient client, MsBandManager bandManager) { this.client = client; this.bandManager = bandManager; try { fwVersion = client.getFirmwareVersion().await(); hwVersion = client.getHardwareVersion().await(); } catch (Exception ex) { String error = "3" + "Failed to get Band[" + bandId + "] version Information!"; System.err.println(error); UnityPlayer.UnitySendMessage( "MsBandManager", "ThrowBandErrorEvent", error ); } } // region Tiles public void createTile() { // Sorry this has been removed for this release! // exampleTile = new ExampleTile(this); // exampleTile.createNewTile(); } // endregion Tiles // region Enable and Disable Sensors /** * Method to enable specific sensors via defined string[] * @param sensors string[] array */ public void enableNamedSensors(String[] sensors) { enableDisableNamedSensors(sensors, true); } /** * Method to disable specific sensors via defined string[] * @param sensors */ public void disableNamedSensors(String[] sensors) { enableDisableNamedSensors(sensors, false); } /** * Method to both enable and or disable named sensors defined via a string[] * and a given boolean state * @param sensors string[] * @param state true enable or false disable */ public void enableDisableNamedSensors(String[] sensors, boolean state) { for(String sensor: sensors) { switch (sensor) { case "Accelerometer": accelerometer = new Accelerometer(this); accelerometer.enableOrDisableListener(state); break; case "Gyroscope": gyroscope = new Gyroscope(this); gyroscope.enableOrDisableListener(state); break; case "Calories": calories = new Calories(this); calories.enableOrDisableListener(state); break; case "Distance": distance = new Distance(this); distance.enableOrDisableListener(state); break; case "HeartRate": checkHeartRateSensor(); break; case "Contact": contact = new Contact(this); contact.enableOrDisableListener(state); break; case "Pedometer": pedometer = new Pedometer(this); pedometer.enableOrDisableListener(true); break; case "UVIndex": uvIndex = new UVIndex(this); uvIndex.enableOrDisableListener(true); break; case "SkinTemperature": skinTemperature = new SkinTemperature(this); skinTemperature.enableOrDisableListener(true); break; } if (Integer.valueOf(hwVersion) >= 20) { switch (sensor) { case "Gsr": gsr = new Gsr(this); gsr.enableOrDisableListener(state); break; case "AmbientLight": ambientLight = new AmbientLight(this); ambientLight.enableOrDisableListener(state); break; case "Barometer": barometer = new Barometer(this); barometer.enableOrDisableListener(state); break; case "Altimeter": altimeter = new Altimeter(this); altimeter.enableOrDisableListener(state); break; /* case "RRInterval": rrInterval = new RRInterval(this); rrInterval.enableOrDisableListener(state); */ } } else { System.err.println("Some sensors are not supported with your Band version. Microsoft Band 2 is required!"); } } } /** * Method to enable all sensors that are supported by the band */ public void enableAllSensors() { enableAllBand1Sensors(); System.out.println("Band[" + bandId + "] Version: " + hwVersion); if (Integer.valueOf(hwVersion) >= 20) { enableAllBand2Sensors(); } else { System.err.println("Some sensors are not supported with your Band version. Microsoft Band 2 is required!"); // Gsr // RRInterval // AmbientLight // Barometer // Altimeter } // The HeartRate sensor is a special case as it needs extra permissions checkHeartRateSensor(); } public void disableAllSensors() { disableAllBand1Sensors(); if (Integer.valueOf(hwVersion) >= 20) { disableAllBand2Sensors(); } else { System.err.println("Some sensors are not supported with your Band version. Microsoft Band 2 is required!"); // Gsr // RRInterval // AmbientLight // Barometer // Altimeter } } /** * Method that checks user consent status for use of the HeartRate sensor */ public void checkHeartRateSensor() { if (client.getSensorManager().getCurrentHeartRateConsent() == UserConsent.GRANTED) { // Status has already been granted to enable the sensor enableHeartSensors(); } else { // Show the consent request client.getSensorManager().requestHeartRateConsent(bandManager.activity, new HeartRateConsentListener() { @Override public void userAccepted(boolean consentGiven) { if(consentGiven) { // Consent has been granted so enable the sensor enableHeartSensors(); } else { // Consent declined so show error and return String error = "2,"+ "You have not given this application consent to access heart rate data!"; System.err.println(error); UnityPlayer.UnitySendMessage( "MsBandManager", "ThrowBandErrorEvent", error ); // HeartRate is disabled for this session! } } }); } } /** * Method that enables the HeartRate sensor */ public void enableHeartSensors() { try { System.out.println("Enabling Heart Sensors!"); // Initialise the class heartRate = new HeartRate(this); heartRate.enableOrDisableListener(true); // If this we are connected to a band 2 then also enable the // RRInterval sensor. if (Integer.valueOf(hwVersion) >= 20) { rrInterval = new RRInterval(this); rrInterval.enableOrDisableListener(true); } } catch (Exception ex) { System.err.println("HeartRate: " + ex.getMessage()); } } /** * Method to disable the HeartRate sensor */ public void disableHeartSensors() { try { // Disable the HeartRate sensor heartRate.enableOrDisableListener(false); // If this we are connected to a band 2 then also disable the // RRInterval sensor. if (Integer.valueOf(hwVersion) >= 20) { rrInterval.enableOrDisableListener(false); } } catch (Exception ex) { System.err.println("HeartRate: " + ex.getMessage()); } } /** * Method that enables all the sensors of the Band 1 with the exception * of the HeartRate sensor. */ public void enableAllBand1Sensors() { System.out.println("Enabling Band 1 Sensors for Band[" + bandId + "]"); accelerometer = new Accelerometer(this); accelerometer.enableOrDisableListener(true); gyroscope = new Gyroscope(this); gyroscope.enableOrDisableListener(true); calories = new Calories(this); calories.enableOrDisableListener(true); distance = new Distance(this); distance.enableOrDisableListener(true); contact = new Contact(this); contact.enableOrDisableListener(true); pedometer = new Pedometer(this); pedometer.enableOrDisableListener(true); uvIndex = new UVIndex(this); uvIndex.enableOrDisableListener(true); skinTemperature = new SkinTemperature(this); skinTemperature.enableOrDisableListener(true); } /** * Method that disables all the sensors of the Band 1 with the exception * of the HeartRate sensor. */ public void disableAllBand1Sensors() { try { accelerometer.enableOrDisableListener(false); gyroscope.enableOrDisableListener(false); calories.enableOrDisableListener(false); distance.enableOrDisableListener(false); contact.enableOrDisableListener(false); pedometer.enableOrDisableListener(false); uvIndex.enableOrDisableListener(false); skinTemperature.enableOrDisableListener(false); } catch (Exception ex) { System.err.println("Failed to disable band 1 Sensors for Band[" + bandId + "]"); } } /** * Method that enables all the sensors of the Band 2 with the exception * of the RRInterval sensor as this is catered for via the HeartRate * sensor check. */ public void enableAllBand2Sensors() { System.out.println("Enabling Band 2 Sensors for Band[" + bandId + "]"); altimeter = new Altimeter(this); altimeter.enableOrDisableListener(true); gsr = new Gsr(this); gsr.enableOrDisableListener(true); barometer = new Barometer(this); barometer.enableOrDisableListener(true); ambientLight = new AmbientLight(this); ambientLight.enableOrDisableListener(true); // rrInterval = new RRInterval(this); // rrInterval.enableOrDisableListener(true); } public void disableAllBand2Sensors() { try { altimeter.enableOrDisableListener(false); gsr.enableOrDisableListener(false); barometer.enableOrDisableListener(false); ambientLight.enableOrDisableListener(false); } catch (Exception ex) { System.err.println("Failed to disable band 2 Sensors for Band[" + bandId + "]"); } } // endregion Enable and Disable Sensors // region Haptic Triggers /** * Method used to trigger haptic events * @param vibration string name of the event to trigger */ public void triggerHapticEvent(String vibration) { try { switch (vibration) { case "NOTIFICATION_ALARM": client.getNotificationManager().vibrate(VibrationType.NOTIFICATION_ALARM).await(); break; case "NOTIFICATION_ONE_TONE": client.getNotificationManager().vibrate(VibrationType.NOTIFICATION_ONE_TONE).await(); break; case "NOTIFICATION_TIMER": client.getNotificationManager().vibrate(VibrationType.NOTIFICATION_TIMER).await(); break; case "NOTIFICATION_TWO_TONE": client.getNotificationManager().vibrate(VibrationType.NOTIFICATION_TWO_TONE).await(); break; case "ONE_TONE_HIGH": client.getNotificationManager().vibrate(VibrationType.ONE_TONE_HIGH).await(); break; case "RAMP_DOWN": client.getNotificationManager().vibrate(VibrationType.RAMP_DOWN).await(); break; case "RAMP_UP": client.getNotificationManager().vibrate(VibrationType.RAMP_UP).await(); break; case "THREE_TONE_HIGH": client.getNotificationManager().vibrate(VibrationType.THREE_TONE_HIGH).await(); break; case "TWO_TONE_HIGH": client.getNotificationManager().vibrate(VibrationType.TWO_TONE_HIGH).await(); break; } } catch (InterruptedException ex) { System.err.println(ex.getMessage()); } catch (BandException ex) { System.err.println(ex.getMessage()); } } /** * Method used to trigger haptic events * @param value string value of the event to trigger */ public void triggerHapticValue(String value) { try { client.getNotificationManager().vibrate(VibrationType.valueOf(value)).await(); } catch (InterruptedException ex) { System.err.println(ex.getMessage()); } catch (BandException ex) { System.err.println(ex.getMessage()); } } // endregion Haptic Triggers }
/* * using java lang math static methods. * */ package Math; /** * * @author YNZ */ public class NewMain { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Square root "+Math.sqrt(12d)); } }
import java.util.ArrayList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { ArrayList<TreeNode> list = new ArrayList<>(); public TreeNode Convert(TreeNode pRootOfTree) { if (pRootOfTree==null) return null; if (pRootOfTree.left==null && pRootOfTree.right==null) return pRootOfTree; // 中序遍历,将节点依次存入ArrayList中 midFind(pRootOfTree); // 再遍历节点,依次排列 for (int i=1;i<list.size();i++){ TreeNode pre = list.get(i - 1); TreeNode now = list.get(i); pre.right = now; now.left = pre; } list.get(list.size()-1).right = null; return list.get(0); } private void midFind(TreeNode root) { if (root.left!=null) { // 左儿子存在 midFind(root.left); } list.add(root); if (root.right!=null) { midFind(root.right); } } public static void main(String[] args) { Solution solution = new Solution(); MyList myList = new MyList(); TreeNode root = myList.root; // solution.midFind(root); TreeNode convert = solution.Convert(root); while (convert.right!=null) { System.out.println(convert.val); convert = convert.right; } System.out.println("---"); while (convert.left!=null) { System.out.println(convert.val); convert = convert.left; } // // System.out.println(solution.list.toString()); // for (TreeNode node:solution.list) // { // System.out.print(node.val+","); // } } }
public class Rambabu{ public static void main(String args[]) throws Exception{java.io.PrintWriter pw=new java.io.PrintWriter( "E:/Apache Software Foundation/Tomcat 7.0/webapps/E-education1/java files/result.txt" ); int a=10; int b=20; int c=a+b; pw.println(c); pw.close(); }}
package com.limefriends.molde.menu_magazine.cardnews; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.limefriends.molde.R; import com.limefriends.molde.menu_magazine.comment.MagazineCommentActivity; import com.limefriends.molde.menu_magazine.entity.CardNewsDetailEntity; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class MagazineCardnewsDetailActivity extends AppCompatActivity { @BindView(R.id.cardnews_detail_layout) RelativeLayout cardnews_detail_layout; @BindView(R.id.cardnews_pager) ViewPager cardnews_pager; @BindView(R.id.cardnews_comment) ImageView cardnews_comment; @BindView(R.id.cardnews_scrap) ImageView cardnews_scrap; @BindView(R.id.cardnews_share) ImageView cardnews_share; @BindView(R.id.current_page_no) TextView current_page_no; @BindView(R.id.total_page_no) TextView total_page_no; MagazineCardNewsDetailPagerAdapter magazineCardNewsDetailPagerAdapter; List<CardNewsDetailEntity> cardNewsDetailList; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.magazine_activity_cardnews_detail); ButterKnife.bind(this); cardNewsDetailList = new ArrayList<CardNewsDetailEntity>(); for (int i = 0; i < 3; i++) { String description = String.valueOf(i + 1) + "번째 페이지\n" + "How Can I Add Many TextView or Other Views in ViewPager\n" + "How Can I Add Many TextView or Other Views in ViewPager\n" + "How Can I Add Many TextView or Other Views in ViewPager\n" + "How Can I Add Many TextView or Other Views in ViewPager\n" + "How Can I Add Many TextView or Other Views in ViewPager\n" + "How Can I Add Many TextView or Other Views in ViewPager\n" + "How Can I Add Many TextView or Other Views in ViewPager\n" + "How Can I Add Many TextView or Other Views in ViewPager\n"; cardNewsDetailList.add(new CardNewsDetailEntity(R.drawable.letters1 + i, description)); } total_page_no.setText(String.valueOf(cardNewsDetailList.size())); magazineCardNewsDetailPagerAdapter = new MagazineCardNewsDetailPagerAdapter(getLayoutInflater(), (ArrayList<CardNewsDetailEntity>) cardNewsDetailList); cardnews_pager.setAdapter(magazineCardNewsDetailPagerAdapter); cardnews_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { current_page_no.setText(String.valueOf(position + 1)); } @Override public void onPageScrollStateChanged(int state) { } }); cardnews_comment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "comment clicked", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(getApplicationContext(), MagazineCommentActivity.class); intent.putExtra("toolbarTitle", "댓글"); startActivity(intent); } }); cardnews_scrap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cardnews_scrap.setImageResource(R.drawable.ic_card_scrap_true); Toast.makeText(getApplicationContext(), "스크랩 추가", Toast.LENGTH_SHORT).show(); } }); cardnews_share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "공유하기", Toast.LENGTH_SHORT).show(); } }); } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } }
//повернуть матрицу на 90 гр вправо package Array; import java.util.Scanner; public class array_16 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int i = 0; int j = 0; int [][] arr = new int[m][n]; for(j = 1; j <= n; j++){ for(i = 0; i < m; i++){ int b = scanner.nextInt(); arr[i][n - j] = b; } } System.out.println(); for(i = 0; i < m; i++){ for(j = 0; j< n; j++){ System.out.print(arr[i][j] + " "); } System.out.println(); } } }
/* * 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. */ /** *Esta clase hereda comportamientos de Alarma y es la que corremos * @author Jose Tejada */ public class AlarmaEmergencia extends Alarma{ /** * Este metodo imprime un emergencia */ @Override public void m1(){ System.out.println("emergencia 1"); } /** * Este metodo tiene 2 super de su super clase que es Alarma e invoca a uno de Timbre tambien * */ @Override public void m2(){ super.m1(); super.m2(); } /** * Método toString para imprimir algo * @return un String propio con uno herdado */ @Override public String toString(){ return "emergencia "+ super.toString(); } }
package com.revature.controller; import com.revature.exceptions.NoSuchAccountException; import com.revature.exceptions.UsernameAlreadyExistsException; import com.revature.repository.EmployeeDaoImpl; import com.revature.service.EmployeeService; import com.revature.service.EmployeeServiceImpl; import io.javalin.http.Context; public class EmployeeControllerImpl implements EmployeeController { private EmployeeService employeeService = new EmployeeServiceImpl(new EmployeeDaoImpl()); private static final String EMPLOYEE_CODE = "Th1515th33mpl0y33C0D3!"; @Override public void employeeLogin(Context ctx) { String username = ctx.formParam("username"); String password = ctx.formParam("password"); try { if (employeeService.validateEmployeeLogin(username, password)) { ctx.status(200); ctx.redirect("/employee-home.html"); } else { ctx.status(507); ctx.redirect("/employee-login.html"); } } catch (NoSuchAccountException e) { ctx.status(507); ctx.redirect("/employee-login.html"); } } @Override public void employeeLogout(Context ctx) { ctx.clearCookieStore(); ctx.redirect("employee-login.html"); } @Override public void newEmployeeAccount(Context ctx) { String username = ctx.formParam("newEmployeeUsername"); String password = ctx.formParam("newEmployeePassword"); String secretCode = ctx.formParam("secretCode"); try { if (secretCode.equals(EMPLOYEE_CODE)) { employeeService.createNewEmployeeAccount(username, password); ctx.status(201); ctx.redirect("employee-login.html"); } else { ctx.status(403); ctx.redirect("new-employee.html"); } } catch (UsernameAlreadyExistsException e) { ctx.status(405); ctx.redirect("new-employee.html"); } } @Override public boolean checkUser(Context ctx) { return employeeService.validateToken(ctx.cookieStore("name")); } }
package com.snapup.service; import com.snapup.pojo.Station; import com.snapup.pojo.TrainRun; import java.util.List; public interface StationOnLineService { //购票者可以输入旅程信息,返回线路: public List<String> getTrainLine(String depart_station_code, String arrival_station_code); //购票者可以输入旅程信息,返回线路,包括中间站: public List<String> getTrainLine2(String depart_station_code, String arrival_station_code); //查询一个车次的始发站 public String getStartStation(String run_code); //查询一个车次的终点站 public String getEndStation(String run_code); //查询一个车次的所有途径站点 public List<Station> getAllStation(String run_code); //查询经停站: public List<Station> getPassStation(String run_code, String depart_station_name, String arrival_station_name); }
package com.sarkergmail.shreya.stringconcate; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText etFirstName; EditText etMiddleName; EditText etLastName; TextView tvFullName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initialization(); } private void initialization() { etFirstName = (EditText) findViewById(R.id.etFirstName); etMiddleName = (EditText) findViewById(R.id.etMiddleName); etLastName = (EditText) findViewById(R.id.etLastName); tvFullName = (TextView) findViewById(R.id.tvFullName); //initially the textview has nothing tvFullName.setVisibility(View.INVISIBLE); } public void concate(View view) { //get the values from edittext String firstName = etFirstName.getText().toString(); String middleName = etMiddleName.getText().toString(); String lastName = etLastName.getText().toString(); String fullName = firstName + " " + middleName + " " + lastName; tvFullName.setText(fullName); //set the textview visible tvFullName.setVisibility(View.VISIBLE); } }
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * * @author Z.Paulovics */ package org.jboss.arquillian.container.wls.jsr88_12c; import java.util.logging.Logger; import org.jboss.arquillian.container.spi.client.container.DeployableContainer; import org.jboss.arquillian.container.spi.client.container.DeploymentException; import org.jboss.arquillian.container.spi.client.container.LifecycleException; import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription; import org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext; import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData; import org.jboss.arquillian.container.wls.jsr88_12c.clientutils.WeblogicClient; import org.jboss.arquillian.container.wls.jsr88_12c.clientutils.WeblogicClientException; import org.jboss.arquillian.container.wls.jsr88_12c.clientutils.WeblogicClientService; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.descriptor.api.Descriptor; public class WeblogicJsr88DeployableContainer implements DeployableContainer<WebLogicJsr88Configuration> { private WebLogicJsr88Configuration configuration; private WeblogicClient weblogicClient; private static final Logger log = Logger.getLogger(WeblogicJsr88DeployableContainer.class.getName()); public WeblogicJsr88DeployableContainer() { } public Class<WebLogicJsr88Configuration> getConfigurationClass() { return WebLogicJsr88Configuration.class; } public void setup(WebLogicJsr88Configuration configuration) { if (configuration == null) { throw new IllegalArgumentException("configuration must not be null"); } setConfiguration(configuration); // Start up the weblogicClient service layer this.weblogicClient = new WeblogicClientService(configuration); } public void start() throws LifecycleException { try { weblogicClient.startUp(); } catch (WeblogicClientException e) { log.severe( e.getMessage() ); throw new LifecycleException( e.getMessage() ); } } public void stop() throws LifecycleException { weblogicClient.shutDown(); } public ProtocolDescription getDefaultProtocol() { return new ProtocolDescription("Servlet 3.0"); } public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException { if (archive == null) { throw new IllegalArgumentException("archive must not be null"); } ProtocolMetaData protocolMetaData = new ProtocolMetaData(); try { HTTPContext httpContext = weblogicClient.doDeploy(archive); protocolMetaData.addContext(httpContext); } catch (WeblogicClientException e) { throw new DeploymentException("Could not deploy " + archive.getName() + "; " + e.getMessage(), e); } // log.info( protocolMetaData.toString() ); return protocolMetaData; } public void undeploy(Archive<?> archive) throws DeploymentException { if (archive == null) { throw new IllegalArgumentException("archive must not be null"); } try { weblogicClient.doUndeploy(archive); } catch (WeblogicClientException e) { throw new DeploymentException("Could not undeploy " + archive.getName() + "; " + e.getMessage(), e); } } public void deploy(Descriptor descriptor) throws DeploymentException { throw new UnsupportedOperationException("Not implemented"); } public void undeploy(Descriptor descriptor) throws DeploymentException { throw new UnsupportedOperationException("Not implemented"); } protected WebLogicJsr88Configuration getConfiguration() { return configuration; } protected void setConfiguration(WebLogicJsr88Configuration configuration) { this.configuration = configuration; } }
package edu.inheritance.newbold.griffin; import edu.jenks.dist.inheritance.*; public class AlcoholItem extends BarcodeItem implements SinTaxable{ private double sinTaxRate; private boolean checkID = true; public AlcoholItem(boolean bulk, double weight, double price, double sinTaxRate){ super(bulk, weight, price); this.sinTaxRate = sinTaxRate; } public double getSinTaxRate(){ return sinTaxRate; } public double getTax(double baseTaxRate){ return super.getTax(baseTaxRate) + (price*sinTaxRate); } public void setSinTaxRate(double sinTaxRate){ this.sinTaxRate = sinTaxRate; } public boolean initBuyable(ItemHandler itemHandler){ return true; } }
package za.ac.ngosa.repository; import za.ac.ngosa.domain.TVShow; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * Created by User on 2015/08/10. */ @Repository public interface TVShowRepository extends CrudRepository<TVShow,Long> { @Override public TVShow findOne(Long code); }
package com.chinasoft.action; import java.util.List; import javax.annotation.Resource; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.chinasoft.annotation.Login; import com.chinasoft.domain.Clothing; import com.chinasoft.domain.User; import com.chinasoft.service.ClothingService; import com.chinasoft.utils.CreateNumUtils; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; @Controller("clothingAction") @Scope("prototype") public class ClothingAction extends ActionSupport { private String clotSize; public String getClotSize() { return clotSize; } public void setClotSize(String clotSize) { this.clotSize = clotSize; } @Resource(name = "clothingService") private ClothingService clothingService; // 用于保存clothing public Clothing clothing = new Clothing(); private Integer clotId; @Login public String save() throws Exception { try{ this.clothingService.saveClothing(clothing); return "saveSuccess"; }catch (Exception e) { this.addActionError("数据异常请重试!!"); return "saveError"; } } @Login public String delete() throws Exception { if (clotId != null) { this.clothingService.deleteClothingByClotId(clotId); } return "deleteSuccess"; } /* * public String findClothing() throws Exception{ * * List<Clothing> clothings = * this.clothingService.findClothingByClothing(clothing); * if(clothings.size()!=0){ * //ServletActionContext.getRequest().setAttribute("clothings", clothings); * ActionContext.getContext().put("clots", clothings); }else{ * this.addActionError("没有该记录!!!"); return "findError"; } return * "findSuccess"; } */ @Login public String clothingAddBut() { String clotNum = CreateNumUtils.generate(); ActionContext.getContext().put("clotNum", clotNum); return "clothingAddButSuccess"; } @Login public String clothingList() throws Exception { // 带条件查询所有list List<Clothing> lists = this.clothingService.findClothingList(clothing); ActionContext.getContext().put("lists", lists); // 不带条件查询所有list List<Clothing> hHLists = this.clothingService.findClothingList(null); ActionContext.getContext().put("hHLists", hHLists); return "list"; } @Login public String updateBut() throws Exception{ // 根据id查找一件衣服回显 Clothing clot = this.clothingService.getUserById(clotId); ActionContext.getContext().put("clot", clot); // 查找所有的色号 List<Clothing> ysLists = this.clothingService.findColorList(); ActionContext.getContext().put("ysLists", ysLists); // 查找所有的大小号 List<Clothing> sizeLists = this.clothingService.findSizeList(); ActionContext.getContext().put("sizeLists", sizeLists); return "updateBut"; } @Login public String updateClothing() throws Exception{ if(clothing != null){ if(clotSize!=null && !clotSize.equals("")){ Integer clotSize1 = Integer.valueOf(clotSize); clothing.setClotSize(clotSize1); } if(!clothing.getClotColor().equals("0") && clothing.getClotSize() != null){ this.clothingService.update(clothing,clotId); return "update"; }else{ this.addActionError("色号或尺码不能为空"); return "updateError"; } }else{ this.addActionError("请重试!!!"); return "updateError"; } } // ------------------getter and setter --------------------- public Integer getClotId() { return clotId; } public void setClotId(Integer clotId) { this.clotId = clotId; } }
import java.io.*; import java.util.*; class baek__1956 { static int MAX = 4000001; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] temp = br.readLine().split(" "); int v = Integer.parseInt(temp[0]); int e = Integer.parseInt(temp[1]); int[][] dist = new int[v + 1][v + 1]; for (int i = 1; i < v + 1; i++) { for (int j = 1; j < v + 1; j++) { dist[i][j] = MAX; } } for (int i = 0; i < e; i++) { temp = br.readLine().split(" "); int a = Integer.parseInt(temp[0]); int b = Integer.parseInt(temp[1]); int c = Integer.parseInt(temp[2]); dist[a][b] = Math.min(dist[a][b], c); } for (int k = 1; k < v + 1; k++) { for (int i = 1; i < v + 1; i++) { for (int j = 1; j < v + 1; j++) { if (i == j) continue; dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } int answer = -1; for (int i = 1; i < v + 1; i++) { for (int j = 1; j < v + 1; j++) { if (i == j) continue; if (dist[i][j] == MAX || dist[j][i] == MAX) continue; int d = dist[i][j] + dist[j][i]; answer = answer == -1 ? d : Math.min(answer, d); } } System.out.print(answer); } }
package com.example.fyp.Fragments; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.example.fyp.Adapters.OrdersAdapter; import com.example.fyp.ImageUtils.LoadImages; import com.example.fyp.MainActivity; import com.example.fyp.Models.CartBO; import com.example.fyp.Models.OrdersBO; import com.example.fyp.R; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import butterknife.BindView; import butterknife.ButterKnife; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class FragmentOrders extends Fragment { private Context context; private OrdersAdapter ordersAdapter; private Gson gson; @BindView(R.id.rvRecyclerView) RecyclerView rvRecyclerView; @BindView(R.id.srl) SwipeRefreshLayout srl; @BindView(R.id.tvNoDataFound) TextView tvNoDataFound; public static FragmentOrders newInstance() { FragmentOrders fragment = new FragmentOrders(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_fragment_orders, container, false); context = inflater.getContext(); ButterKnife.bind(this,view); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); gson = new Gson(); setupSwipeRefreshLayout(); setupRecycler(new ArrayList<OrdersBO>()); } /*SETUP STOCK RECYCLER*/ private void setupRecycler(ArrayList<OrdersBO> arrayList) { if(rvRecyclerView!=null && rvRecyclerView.getAdapter()==null) { rvRecyclerView.setLayoutManager(new LinearLayoutManager(context)); ordersAdapter = new OrdersAdapter(context,arrayList); rvRecyclerView.setAdapter(ordersAdapter); } else { ordersAdapter.addItems(arrayList); } } /*SETUP SWIPE REFRESH LAYOUT*/ private void setupSwipeRefreshLayout() { srl.setColorScheme(R.color.color); srl.post(new Runnable() { @Override public void run() { setupRefreshing(true); callGetOrdersApi(); } }); srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { setupRefreshing(true); callGetOrdersApi(); } }); } /*SETUP REFRESHING*/ private void setupRefreshing(boolean isRefreshing) { if(isRefreshing) { srl.setRefreshing(isRefreshing); } else { srl.setRefreshing(isRefreshing); } } /*PARSE JSON STRING*/ private void parseJson(String jsonString) { try { JSONObject jsonObject = new JSONObject(jsonString); Type type = new TypeToken<ArrayList<OrdersBO>>(){}.getType(); ArrayList<OrdersBO> arrayList = gson.fromJson(jsonObject.getJSONArray("result").toString(),type); setupRecycler(arrayList); if(arrayList.size()>0) { rvRecyclerView.setVisibility(View.VISIBLE); tvNoDataFound.setVisibility(View.GONE); } else { rvRecyclerView.setVisibility(View.GONE); tvNoDataFound.setVisibility(View.VISIBLE); } setupRefreshing(false); } catch (Exception e) { e.toString(); } } /*CALL GET ORDERS API*/ private void callGetOrdersApi() { Ion.with(context) .load(getResources().getString(R.string.base_url) +"getOrdersForMobile.php") .asString().setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { if(e!=null) { Toast.makeText(context,e.toString(),Toast.LENGTH_SHORT).show(); } else if(!TextUtils.isEmpty(result)) { parseJson(result); } } }); } }
package com.example.asynctaskdemo; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.ui.AppBarConfiguration; import com.example.asynctaskdemo.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { private AppBarConfiguration appBarConfiguration; private ActivityMainBinding binding; protected TextView label; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(R.layout.activity_main); label = findViewById(R.id.label); Button b = findViewById(R.id.startButton); b.setOnClickListener(e -> { b.setEnabled(false); DemoTask d = new DemoTask(MainActivity.this); String ret = d.execute("Hello"); Log.d(TAG, "Background service returned " + ret); b.setEnabled(true); }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package interation05; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import iteration05.Simulator; import iteration05.fr.agh.domain.Cell; import iteration05.fr.agh.domain.Dimension; import iteration05.fr.agh.domain.Grid; import iteration05.fr.agh.domain.State; import iteration05.fr.agh.services.FileLoadingService; import iteration05.fr.agh.services.LoadingService; public class LoaderTest { private LoadingService loader; private Simulator targetOneSevenSimulator; private Simulator targetOneTwoSimulator; private Simulator targetOneOneSimulator; private Simulator targetSevenOneSimulator; private Simulator targetSevenForSimulator; @Before public void setUp() { Cell c00 = new Cell(State.ALIVE); Cell[][] cells00 = { { c00 } }; Grid grid00 = new Grid(cells00); this.targetOneOneSimulator = new Simulator(new Dimension(1, 1), 3, grid00); Cell c001 = new Cell(State.ALIVE); Cell c002 = new Cell(State.DEAD); Cell[][] cells01 = { { c001, c002 } }; Grid grid01 = new Grid(cells01); this.targetOneTwoSimulator = new Simulator(new Dimension(1, 2), 3, grid01); Cell c01 = new Cell(State.ALIVE); Cell c02 = new Cell(State.DEAD); Cell c03 = new Cell(State.ALIVE); Cell c04 = new Cell(State.ALIVE); Cell c05 = new Cell(State.ALIVE); Cell c06 = new Cell(State.ALIVE); Cell c07 = new Cell(State.ALIVE); Cell[][] cells02 = { { c01, c02, c03, c04, c05, c06, c07 } }; Grid grid02 = new Grid(cells02); this.targetOneSevenSimulator = new Simulator(new Dimension(1, 7), 3, grid02); Cell c011 = new Cell(State.ALIVE); Cell c022 = new Cell(State.DEAD); Cell c033 = new Cell(State.ALIVE); Cell c044 = new Cell(State.ALIVE); Cell c055 = new Cell(State.ALIVE); Cell c066 = new Cell(State.ALIVE); Cell c077 = new Cell(State.ALIVE); Cell[][] cells03 = { { c011 }, { c022 }, { c033 }, { c044 }, { c055 }, { c066 }, { c077 } }; Grid grid03 = new Grid(cells03); this.targetSevenOneSimulator = new Simulator(new Dimension(7, 1), 3, grid03); Cell[][] cells04 = { { c011,c022,c033,c044 }, { c022,c022,c033,c044 }, { c033,c022,c033,c044 }, { c044 ,c022,c033,c044 }, { c055,c022,c033,c044 }, { c066 ,c022,c033,c044 }, { c077,c022,c033,c044 } }; Grid grid04 = new Grid(cells04); this.targetSevenForSimulator = new Simulator(new Dimension(7, 4), 3, grid04); } private LoadingService createLoader(String fileName) { String dataFileName = getClass().getResource(fileName).getPath(); loader = new FileLoadingService(dataFileName); return loader; } @Test public void should_Return_targetOneOneSimulator() { // given loader = this.createLoader("/iteration05/data01"); // when Simulator simulator = loader.load(); // then assertThat(this.targetOneOneSimulator).isEqualTo(simulator); } @Test public void should_Return_targetOneTwoSimulator() { // given loader = this.createLoader("/iteration05/data02"); // when Simulator simulator = loader.load(); // then assertThat(this.targetOneTwoSimulator).isEqualTo(simulator); } @Test public void should_Return_targetOneSevenSimulator() { // given loader = this.createLoader("/iteration05/data03"); // when Simulator simulator = loader.load(); // then assertThat(this.targetOneSevenSimulator).isEqualTo(simulator); } @Test public void should_Return_targetSevenOneSimulator() { // given loader = this.createLoader("/iteration05/data04"); // when Simulator simulator = loader.load(); // then assertThat(this.targetSevenOneSimulator).isEqualTo(simulator); } @Test public void should_Return_targetSevenForSimulator() { // given loader = this.createLoader("/iteration05/data"); // when Simulator simulator = loader.load(); // then assertThat(this.targetSevenForSimulator).isEqualTo(simulator); } }
package io.ceph.rgw.client.model; import io.ceph.rgw.client.ObjectClient; import org.apache.commons.lang3.Validate; import java.util.Objects; /** * Created by zhuangshuo on 2020/3/16. */ public abstract class UploadPartRequest<V> extends BaseObjectRequest { final V upload; private final boolean lastPart; private final String md5; private final int partNumber; private final long partSize; private final String uploadId; protected UploadPartRequest(String bucketName, String key, boolean lastPart, String md5, int partNumber, long partSize, String uploadId, V upload) { super(bucketName, key, null); this.upload = Objects.requireNonNull(upload); this.lastPart = lastPart; this.md5 = md5; Validate.isTrue(partNumber > 0, "partNumber cannot be non positive"); this.partNumber = partNumber; this.partSize = partSize; this.uploadId = uploadId; } public V getUpload() { return upload; } public String getUploadId() { return uploadId; } public boolean isLastPart() { return lastPart; } public String getMD5() { return md5; } public int getPartNumber() { return partNumber; } public long getPartSize() { return partSize; } @Override public String toString() { return "UploadPartRequest{" + "upload=" + upload + ", lastPart=" + lastPart + ", md5='" + md5 + '\'' + ", partNumber=" + partNumber + ", partSize=" + partSize + ", uploadId='" + uploadId + '\'' + "} " + super.toString(); } static abstract class Builder<T extends Builder<T, V>, V> extends BaseObjectRequest.Builder<T, UploadPartRequest<V>, MultipartUploadPartResponse> { V upload; boolean lastPart; String md5; int partNumber; long partSize; String uploadId; public Builder(ObjectClient client) { super(client); } public T withUpload(V upload) { this.upload = upload; return self(); } public T withLastPart(boolean lastPart) { this.lastPart = lastPart; return self(); } public T withMD5(String md5) { this.md5 = md5; return self(); } public T withPartNumber(int partNumber) { this.partNumber = partNumber; return self(); } public T withPartSize(long partSize) { this.partSize = partSize; return self(); } public T withUploadId(String uploadId) { this.uploadId = uploadId; return self(); } @Override public abstract UploadPartRequest<V> build(); } }
package org.sdf4j.awt; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.CubicCurve2D; import java.awt.geom.Rectangle2D; import javax.swing.ImageIcon; import org.sdf4j.core.Color; import org.sdf4j.core.Font; import org.sdf4j.core.FontMetrics; import org.sdf4j.core.ICanvas; import org.sdf4j.core.Image; import org.sdf4j.core.Point; import org.sdf4j.core.Stroke; import org.sdf4j.core.shapes.CompositeShape; import org.sdf4j.core.shapes.IShape; import org.sdf4j.core.shapes.Rectangle; /** * {@link ICanvas} implementation for AWT {@link Graphics2D}. Wraps around the * specified {@link Graphics2D} object and delegates calls. * * @author Branislav Stojkovic */ public class AWTCanvas implements ICanvas { private Graphics2D g2d; private java.awt.geom.AffineTransform transform; public AWTCanvas(Graphics2D g2d) { super(); this.g2d = g2d; } @Override public Color getColor() { return ConversionUtil.convertColor(g2d.getColor()); } @Override public void setColor(Color c) { g2d.setColor(ConversionUtil.convertColor(c)); } @Override public Stroke getStroke() { return ConversionUtil.convertStroke(g2d.getStroke()); } @Override public void setStroke(Stroke s) { g2d.setStroke(ConversionUtil.convertStroke(s)); } @Override public Font getFont() { return ConversionUtil.convertFont(g2d.getFont()); } @Override public void setFont(Font f) { g2d.setFont(ConversionUtil.convertFont(f)); } @Override public void setAntiAlias(boolean antiAlias) { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAlias ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); } @Override public void drawLine(int x1, int y1, int x2, int y2) { g2d.drawLine(x1, y1, x2, y2); } @Override public void drawRect(int x, int y, int width, int height) { g2d.drawRect(x, y, width, height); } @Override public void fillRect(int x, int y, int width, int height) { g2d.fillRect(x, y, width, height); } @Override public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { g2d.drawRoundRect(x, y, width, height, arcWidth, arcHeight); } @Override public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { g2d.fillRoundRect(x, y, width, height, arcWidth, arcHeight); } @Override public void drawOval(int x, int y, int width, int height) { g2d.drawOval(x, y, width, height); } @Override public void fillOval(int x, int y, int width, int height) { g2d.fillOval(x, y, width, height); } @Override public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { g2d.drawArc(x, y, width, height, startAngle, arcAngle); } @Override public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { g2d.fillArc(x, y, width, height, startAngle, arcAngle); } @Override public void drawString(String str, int x, int y) { g2d.drawString(str, x, y); } @Override public void drawImage(Image img, int x, int y) { ImageIcon icon = new ImageIcon(img.getData(), img.getName()); g2d.drawImage(icon.getImage(), x, y, null); } @Override public void saveTransform() { this.transform = g2d.getTransform(); } @Override public void restoreTransform() { if (transform == null) { throw new RuntimeException("There is no saved state to restore"); } g2d.setTransform(this.transform); } @Override public void rotate(double theta) { g2d.rotate(theta); } @Override public void rotate(double theta, double x, double y) { g2d.rotate(theta, x, y); } @Override public void scale(double sx, double sy) { g2d.scale(sx, sy); } @Override public void translate(double dx, double dy) { g2d.translate(dx, dy); } @Override public boolean containsPoint(IShape shape, Point point) { return ConversionUtil.convertShape(shape).contains( ConversionUtil.convertPoint(point)); } @Override public boolean intersectsRect(IShape shape, org.sdf4j.core.shapes.Rectangle rect) { java.awt.Shape awtShape = ConversionUtil.convertShape(shape); java.awt.Shape awtRect = ConversionUtil.convertShape(rect); return awtShape.intersects((Rectangle2D) awtRect); } @Override public FontMetrics getFontMetrics() { java.awt.FontMetrics awtFontMetrics = g2d.getFontMetrics(); FontMetrics fontMetrics = new FontMetrics(awtFontMetrics.getAscent(), awtFontMetrics.getDescent(), awtFontMetrics.getLeading()); return fontMetrics; } @Override public Rectangle getTextBounds(String text) { return (Rectangle) ConversionUtil.convertShape(g2d.getFontMetrics() .getStringBounds(text, g2d)); } @Override public void drawCurve(int x1, int y1, int ctrlx1, int ctrly1, int ctrlx2, int ctrly2, int x2, int y2) { CubicCurve2D curve = new CubicCurve2D.Double(x1, y1, ctrlx1, ctrly1, ctrlx2, ctrly2, x2, y2); g2d.draw(curve); } }
package com.test; import java.util.List; import com.test.multi.ac.AcRobot; import com.test.multi.ac.AcRobot.AcResult; import com.test.multi.trie.Trie; import junit.framework.TestCase; /** * 多模式,字符串匹配 * 多模式:在多个模式串和一个主串之间做匹配 * @author YLine * * 2019年4月8日 下午5:17:23 */ public class MultiSample extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testTrie() { System.out.println("-------------testTrie--------------"); Trie trie = new Trie(); trie.insert("how"); trie.insert("hi"); trie.insert("her"); trie.insert("hello"); trie.insert("so"); trie.insert("see"); assertEquals(false, trie.find("")); assertEquals(false, trie.find("h")); assertEquals(false, trie.find("ho")); assertEquals(false, trie.find("hio")); assertEquals(false, trie.find("hoq")); assertEquals(true, trie.find("how")); assertEquals(true, trie.find("hi")); assertEquals(true, trie.find("her")); assertEquals(true, trie.find("hello")); assertEquals(true, trie.find("so")); assertEquals(true, trie.find("see")); } public void testAc() { System.out.println("-------------testAc--------------"); // 构建,暂时不做删除 AcRobot robot = new AcRobot(); robot.insert("c"); robot.insert("bc"); robot.insert("bcd"); robot.insert("abcd"); // 构建failed指针,正式建立成Ac自动机 robot.buildFailurePointer(); robot.logAcNode(); // 查找对应的值 assertAcSolution(robot, "abcd", 1); assertAcSolution(robot, "fdafdsafdsafdsafdsa", 0); assertAcSolution(robot, "abcdc", 2); assertAcSolution(robot, "abcdd", 1); assertAcSolution(robot, "abcdbcd", 2); assertAcSolution(robot, CHAPTER_WAR_PEACE, 90); } public void assertAcSolution(AcRobot robot, String mainStr, int size) { List<AcResult> result = robot.find(mainStr); assertEquals(size, result.size()); System.out.println("\n------------------------str = " + mainStr + ", size = " + result.size() + "---------------"); for (int i = 0; i < result.size(); i++) { String info = String.format("i: %s, result:{%s}", String.valueOf(i), result.get(i).toString()); System.out.println(info); } } // 文章 private final String CHAPTER_WAR_PEACE = "“WELL, PRINCE, Genoa and Lucca are now no more than private estates of the Bonaparte family. No, I warn you, that if you do not tell me we are at war, if you again allow yourself to palliate all the infamies and atrocities of this Antichrist (upon my word, I believe he is), I don't know you in future, you are no longer my friend, no longer my faithful slave, as you say. There, how do you do, how do you do? I see I'm scaring you, sit down and talk to me.”\r\n" + "\r\n" + "These words were abcd uttered in July 1805 by Anna Pavlovna Scherer, a distinguished lady of the court, and confidential maid-of-honour to the Empress Marya Fyodorovna. It was her greeting to Prince Vassily, a man high in rank and office, who was the first to arrive at her soirée. Anna Pavlovna had been coughing for the last few days; she had an attack of la grippe, as she said—grippe was then a new word only used by a few people. In the notes she had sent round in the morning by a footman in red livery, she had written to all indiscriminately:\r\n" + "\r\n" + "“If you have nothing better to do, count (or prince), and if the prospect of spending an evening with a poor invalid is not too alarming to you, I shall be charmed to see you at my house between 7 and 10. Annette Scherer.”\r\n" + "\r\n" + "“Heavens! what a bc violent outburst!” the prince responded, not in the least disconcerted at such a reception. He was wearing an embroidered court uniform, stockings and slippers, and had stars on his breast, and a bright smile on his flat face.\r\n" + "\r\n" + "He spoke in that elaborately choice French, in which our forefathers not only spoke but thought, and with those slow, patronising intonations peculiar to a man of importance who has grown old in court society. He went up to Anna Pavlovna, kissed her hand, presenting her with a view of his perfumed, shining bald head, and complacently settled himself on the sofa.\r\n" + "\r\n" + "“First of all, tell bcd me how you are, dear friend. Relieve a friend's anxiety,” he said, with no change of his voice and tone, in which indifference, and even irony, was perceptible through the veil of courtesy and sympathy.\r\n" + "\r\n" + "“How can one be well when one is in moral suffering? How can one help being worried in these times, if one has any feeling?” said Anna Pavlovna. “You'll spend the whole evening with me, I hope?”\r\n" + "\r\n" + "“And the fête at the English ambassador's? To-day is Wednesday. I must put in an appearance there,” said the prince. “My daughter is coming to fetch me and take me there.”\r\n" + "\r\n" + "“I thought to-day's fête had been put off. I confess that all these festivities and fireworks are beginning to pall.”\r\n" + "\r\n" + "“If they had known that it was your wish, the fête would have been put off,” said the prince, from habit, like a wound-up clock, saying things he did not even wish to be believed.\r\n" + "\r\n" + "“Don't tease me. Well, what has been decided in regard to the Novosiltsov dispatch? You know everything.”\r\n" + "\r\n" + "“What is there to tell?” said the prince in a tired, listless tone. “What has been decided? It has been decided that Bonaparte has burnt his ships, and I think that we are about to burn ours.”\r\n" + "\r\n" + "Prince Vassily always spoke languidly, like an actor repeating his part in an old play. Anna Pavlovna Scherer, in spite of her forty years, was on the contrary brimming over with excitement and impulsiveness. To be enthusiastic had become her pose in society, and at times even when she had, indeed, no inclination to be so, she was enthusiastic so as not to disappoint the expectations of those who knew her. The affected smile which played continually about Anna Pavlovna's face, out of keeping as it was with her faded looks, expressed a spoilt child's continual consciousness of a charming failing of which she had neither the wish nor the power to correct herself, which, indeed, she saw no need to correct.\r\n" + "\r\n" + "In the midst of a conversation about politics, Anna Pavlovna became greatly excited."; @Override protected void tearDown() throws Exception { super.tearDown(); } }
package com.atguigu.java; /* λ������� << �����ƣ� ����һ����Χ�ڣ�ÿ������һλ��ôԭ����������2 >> �����ƣ� ����һ����Χ�ڣ�ÿ������һλԭ����������2 >>(����) ��������������λ��0��������Ǹ������λ��1���� >>>���޷������ƣ� �� �����������Ǹ��������λ������0�� */ public class BitTest{ public static void main(String[] args){ System.out.println(3 << 1);//6 System.out.println(3 << 2);//12 System.out.println(3 << 3);//24 System.out.println(1 << 31); System.out.println("-----------------------------------------"); System.out.println(6 >> 1); System.out.println(3 >> 1); System.out.println(-3 >> 1); System.out.println("-----------------------------------------"); System.out.println(6 >>> 1); System.out.println(-6 >>> 1); } }
package co.com.ceiba.parqueadero.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import co.com.ceiba.parqueadero.dao.VehiculoRepository; import co.com.ceiba.parqueadero.model.Vehiculo; @RestController public class VehiculoController { @Autowired VehiculoRepository vehiculoRepository; @CrossOrigin(origins="*") @RequestMapping(value = "/getAllVehicles", method = RequestMethod.GET) public List<Vehiculo> getAllVehicles() { List<Vehiculo> listVehicles = new ArrayList<>(); vehiculoRepository.findAll().forEach(listVehicles::add); return listVehicles; } }
package com.cqut.dao; import com.cqut.model.Seller; public interface SellerMapper { int deleteByPrimaryKey(String sellerid); int insert(Seller record); int insertSelective(Seller record); Seller selectByPrimaryKey(String sellerid); int updateByPrimaryKeySelective(Seller record); int updateByPrimaryKey(Seller record); }
package mb.tianxundai.com.toptoken.secondphase.aty; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.zcolin.gui.pullrecyclerview.BaseRecyclerAdapter; import com.zcolin.gui.pullrecyclerview.PullRecyclerView; import com.zcolin.gui.pullrecyclerview.progressindicator.ProgressStyle; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.base.BaseAty; import mb.tianxundai.com.toptoken.interfaces.Layout; import mb.tianxundai.com.toptoken.secondphase.bean.PipelineBean; import mb.tianxundai.com.toptoken.uitl.JumpParameter; @Layout(R.layout.activity_pipeline_record) public class GoldenInListAty extends BaseAty { @BindView(R.id.pull_recycle) PullRecyclerView pullRecycle; @BindView(R.id.title_name) TextView titleName; private PipelineRecordAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void initViews() { ButterKnife.bind(this); titleName.setText(R.string.use_enterlist); LinearLayoutManager layoutManager = new LinearLayoutManager(this); pullRecycle.setLayoutManager(layoutManager); pullRecycle.setLinearLayout(false); adapter = new PipelineRecordAdapter(this); pullRecycle.setRefreshProgressStyle(ProgressStyle.LineScaleIndicator); pullRecycle.setIsLoadMoreEnabled(false); pullRecycle.setIsRefreshEnabled(false); // pullRecycle.setOnPullLoadMoreListener(this); adapter.setPullRecyclerView(pullRecycle); pullRecycle.setAdapter(adapter); pullRecycle.refreshWithPull(); } List<PipelineBean> pipelineList = new ArrayList<>(); @OnClick({R.id.rl_back}) public void onClick(View view) { switch (view.getId()) { case R.id.rl_back: finish(); break; } } @Override public void initDatas(JumpParameter paramer) { pipelineList.clear(); for (int i = 0; i < 5; i++) { PipelineBean pipelineBean = new PipelineBean(); pipelineBean.text = getResources().getString(R.string.use_enter); pipelineBean.money = "+186"; pipelineList.add(pipelineBean); } adapter.setDatas(pipelineList); pullRecycle.setPullLoadMoreCompleted(); } @Override public void setEvents() { } class PipelineRecordAdapter extends BaseRecyclerAdapter<PipelineBean> { private PullRecyclerView pullRecyclerView; private Context context; public void setPullRecyclerView(PullRecyclerView pullRecyclerView) { this.pullRecyclerView = pullRecyclerView; } public PipelineRecordAdapter(Context context) { this.context = context; } @Override public int getItemLayoutId(int viewType) { return R.layout.pipeline_record_item; } @Override public void setUpData(CommonHolder holder, int position, int viewType, PipelineBean data) { ImageView type_img = getView(holder, R.id.type_img); TextView type_text = getView(holder, R.id.type_text); TextView tv_time = getView(holder, R.id.tv_time); TextView tv_money = getView(holder, R.id.tv_money); type_img.setBackgroundResource(R.mipmap.use_enter); String updateTime = String.valueOf(System.currentTimeMillis()); tv_time.setText(updateTime); type_text.setText(data.text); tv_money.setText(data.money); } } }
package com.pyz.tool.weixintool.util; import java.io.*; import java.util.Hashtable; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * �����ļ� * @author Administrator * */ public class LockFile extends File{ private static Hashtable<String,ReentrantReadWriteLock> locks=new Hashtable<String,ReentrantReadWriteLock>(); private ReentrantReadWriteLock lock=null; /** * */ public LockFile(String str) { super(str); lock=initLock(str); // TODO Auto-generated constructor stub } private static synchronized ReentrantReadWriteLock initLock(String path){ ReentrantReadWriteLock lock=locks.get(path); if(lock==null){ lock=new ReentrantReadWriteLock(); locks.put(path, lock); } return lock; } public ReentrantReadWriteLock getLock(){ return lock; } }
package com.github.bartimaeusnek.bettervoidworlds.common.world.chunkgenerator; import com.github.bartimaeusnek.bettervoidworlds.common.config.ConfigHandler; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.feature.WorldGenTrees; import net.minecraftforge.event.terraingen.DecorateBiomeEvent; import net.minecraftforge.event.terraingen.TerrainGen; public class GardenChunkGenerator extends UniversalChunkGenerator { public GardenChunkGenerator(World world) { super(world); } @Override public void populate(int x, int z) { if (x == 0 && z == 0) return; Biomes.PLAINS.decorate(this.world, this.random, new BlockPos(x * 16, 0, z * 16)); TerrainGen.decorate(this.world, this.random, new ChunkPos(new BlockPos(x * 16, 0, z * 16)), DecorateBiomeEvent.Decorate.EventType.TREE); new WorldGenTrees(false, 4, Blocks.LOG.getDefaultState(), Blocks.LEAVES.getDefaultState(), false).generate(this.world, this.random, new BlockPos(x * 16 + this.random.nextInt(16) + worldgenOffset, 5 + ConfigHandler.bedrockThickness, z * 16 + this.random.nextInt(16) + worldgenOffset)); } @Override public Chunk generateChunk(int cx, int cz) { ChunkPrimer chunkPrimer = new ChunkPrimer(); for (int y = 0; y < 5 + ConfigHandler.bedrockThickness; ++y) { for (int x = 0; x < 16; ++x) { for (int z = 0; z < 16; ++z) { if (y <= ConfigHandler.bedrockThickness) chunkPrimer.setBlockState(x, y, z, Blocks.BEDROCK.getDefaultState()); else if (y == 4 + ConfigHandler.bedrockThickness) chunkPrimer.setBlockState(x, y, z, Blocks.GRASS.getDefaultState()); else chunkPrimer.setBlockState(x, y, z, Blocks.DIRT.getDefaultState()); } } } Chunk chunk = new Chunk(this.world, chunkPrimer, cx, cz); for (int i = 0; i < chunk.getBiomeArray().length; ++i) { chunk.getBiomeArray()[i] = (byte) 1; } chunk.generateSkylightMap(); return chunk; } }
package com.jim.mybatis.model.po; import java.util.Date; public class Role { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column roles.id * * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ private Long id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column roles.name * * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ private String name; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column roles.enabled * * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ private Boolean enabled; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column roles.create_user_id * * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ private Long createUserId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column roles.create_at * * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ private Date createAt; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column roles.update_at * * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ private Date updateAt; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column roles.id * * @return the value of roles.id * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column roles.id * * @param id the value for roles.id * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column roles.name * * @return the value of roles.name * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column roles.name * * @param name the value for roles.name * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column roles.enabled * * @return the value of roles.enabled * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public Boolean getEnabled() { return enabled; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column roles.enabled * * @param enabled the value for roles.enabled * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public void setEnabled(Boolean enabled) { this.enabled = enabled; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column roles.create_user_id * * @return the value of roles.create_user_id * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public Long getCreateUserId() { return createUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column roles.create_user_id * * @param createUserId the value for roles.create_user_id * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public void setCreateUserId(Long createUserId) { this.createUserId = createUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column roles.create_at * * @return the value of roles.create_at * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public Date getCreateAt() { return createAt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column roles.create_at * * @param createAt the value for roles.create_at * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public void setCreateAt(Date createAt) { this.createAt = createAt; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column roles.update_at * * @return the value of roles.update_at * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public Date getUpdateAt() { return updateAt; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column roles.update_at * * @param updateAt the value for roles.update_at * @mbggenerated Thu Sep 21 01:16:58 CST 2017 */ public void setUpdateAt(Date updateAt) { this.updateAt = updateAt; } }
package mulitThread.chapter02.t2_2_8.p1; public class MyObject { }
package com.serotonin.modbus4j.exception; public class IllegalDataAddressException extends ModbusTransportException { private static final long serialVersionUID = -1; // Default constructor only. }
/* * 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. */ import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Ricardo */ public class ConnectionDB{ Connection sys, work; public ConnectionDB () { try { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Connection :: START"); this.sys = DriverManager.getConnection("jdbc:oracle:thin:sys/sys@localhost:1521/orcl","sys as sysdba","oracle"); System.out.println("Connection :: SYS"); this.work = DriverManager.getConnection("jdbc:oracle:thin:Work/Work@localhost:1521/orcl","Work","work1"); System.out.println("Connection :: WORK"); } catch (Exception e) { System.out.println(e); } } public Connection getSys() { return sys; } public Connection getWork() { return work; } }