blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
d76457cd370673be46dc9aa3a16c954567099391
Java
asifjafar/java_repo
/src/main/java/Oracle/SmallestPositiveNumber.java
UTF-8
1,525
3.703125
4
[]
no_license
package Oracle; /** * Created by prasun.pallav on 2/28/2019. */ public class SmallestPositiveNumber { static int segregate(int arr[], int size) { int j = 0, i; for (i = 0; i < size; i++) { if (arr[i] <= 0) { int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j++; } } return j; } static int findMissingPositive(int arr[], int size) { int i; for (i = 0; i < size; i++) { int x = Math.abs(arr[i]); if (x - 1 < size && arr[x - 1] > 0) arr[x - 1] = -arr[x - 1]; } // Return the first index value at which // is positive for (i = 0; i < size; i++) if (arr[i] > 0) return i + 1; // 1 is added becuase indexes // start from 0 return size + 1; } static int findMissing(int arr[], int size) { int shift = segregate(arr, size); int arr2[] = new int[size - shift]; int j = 0; for (int i = shift; i < size; i++) { arr2[j] = arr[i]; j++; } return findMissingPositive(arr2, j); } public static void main(String[] args) { int arr[] = {0, 1, 10, 2, -10, -20}; int arr_size = arr.length; int missing = findMissing(arr, arr_size); System.out.println("The smallest positive missing number is " + missing); } }
true
833684afa01bc73d536217ff82bf8991e29af5d7
Java
AmaneHayashi/TianyinMap
/app/src/main/java/com/amane/bean/SearchItem.java
UTF-8
637
2.0625
2
[]
no_license
package com.amane.bean; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * 搜索结果类,出现在搜索列表中 * @author Amane Hayashi */ @Data @NoArgsConstructor @AllArgsConstructor(suppressConstructorProperties = true) public class SearchItem implements Serializable { // ID(POI ID) private String id; // 示意图 private int imageResId; // 名称 private String name; // 详情 private String detail; // 类型 private int type; // 地理坐标(格式:[latitude,longitude]) private String point; }
true
3da87c253bd0dedfaeef52bd42be56ac437ccc4d
Java
titoaesj/JumpNinja
/andgraph/src/main/java/posmobile/br/com/andgraph/AGActivityGame.java
UTF-8
2,390
2.4375
2
[ "MIT" ]
permissive
/******************************************** Class: AGAtivivityGame Description: Android activity class Author: Silvano Maneck Malfatti Date: 05/11/2013 ********************************************/ //Engine package package posmobile.br.com.andgraph; //Used packages import android.app.Activity; import android.os.Bundle; public class AGActivityGame extends Activity { //Attributes protected AGGameManager vrManager = null; /******************************************** * Name: AGActivity * Description: constructor * Parameters: Activity, boolean * Returns: none ******************************************/ public void init(Activity context, boolean accel) { vrManager = new AGGameManager(context, accel); } /******************************************** * Name: onCreate() * Description: method called to create the application * Parameters: Bundle * Returns: none ******************************************/ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /******************************************* * Name: onPause() * Description: method called to pause application * Parameters: none * Returns: none ******************************************/ protected void onPause() { super.onPause(); AGSoundManager.vrMusic.pause(); vrManager.onPause(); } /******************************************* * Name: onResume() * Description: method called after resume application * Parameters: none * Returns: none ******************************************/ protected void onResume() { super.onResume(); vrManager.onResume(); AGSoundManager.vrMusic.play(); } /******************************************* * Name: onBackPressed() * Description: method called when Android back button is pressed * Parameters: none * Returns: none *****************************************/ public void onBackPressed() { AGInputManager.vrTouchEvents.bBackButtonClicked = true; } /******************************************* * Name: onDestroy() * Description: method called when applicatin is destroyed * Parameters: none * Returns: none *****************************************/ protected void onDestroy() { super.onDestroy(); vrManager.release(); vrManager = null; System.gc(); } }
true
fb48ab30c60ce7001f5f9543c90bcccbff82a366
Java
nimisha1796/test
/test/java/com/cts/signup/mockmvc/UserRestTestController.java
UTF-8
6,239
2.078125
2
[]
no_license
package com.cts.signup.mockmvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringRunner.class) @SpringBootTest public class UserRestTestController { @Autowired private WebApplicationContext webApplicationContext; @Rule public ExpectedException exceptionRule = ExpectedException.none(); private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void testUserDetailsSaveSuccessfully() throws Exception { String USER_REQUEST = "{\"name\":\"Nimisha\",\"email\":\"n@gmail.com\",\"password\":\"111\",\"blackListStatus\":\"false\",\"language\":{\"id\": \"1\"}}"; mockMvc.perform(post("/signup/save").content(USER_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().isOk()); } @Test public void testPreExistingEmailId() throws Exception { String USER_REQUEST = "{\"name\":\"Nimisha\",\"email\":\"n@gmail.com\",\"password\":\"111\",\"blackListStatus\":\"false\",\"language\":{\"id\": \"1\"}}"; mockMvc.perform(post("/signup/save").content(USER_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().isOk()); } @Test public void testWrongUrl() throws Exception { String USER_REQUEST = "{\"name\":\"Nimisha\",\"email\":\"n@gmail.com\",\"password\":\"111\",\"blackListStatus\":\"false\",\"language\":{\"id\": \"1\"}}"; mockMvc.perform(post("/signup/addd").content(USER_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().is4xxClientError()); } @Test public void usernameCanNotbeNull() throws Exception { String EMPLOYEE_REQUEST = "{\"email\":\"n@gmail.com\",\"password\":\"111\",\"blackListStatus\":\"false\",\"language\":{\"id\": \"1\"}}"; mockMvc.perform(post("/signup/save").content(EMPLOYEE_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().is4xxClientError()) .andExpect(jsonPath("$.errorMessage").value("Input validation failed: Name cannot be empty")); ; } @Test public void passwordCanNotbeNull() throws Exception { String EMPLOYEE_REQUEST = "{\"name\":\"Nimisha \",\"email\":\"n@gmail.com\",\"blackListStatus\":\"false\",\"language\":{\"id\": \"1\"}}"; mockMvc.perform(post("/signup/save").content(EMPLOYEE_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().is4xxClientError()) .andExpect(jsonPath("$.errorMessage").value("Input validation failed: Password cannot be empty")); } @Test public void emailCanNotbeNull() throws Exception { String EMPLOYEE_REQUEST = "{\"name\":\"Nim\",\"password\":\"1234\",\"blackListStatus\":\"false\",\"language\":{\"id\": \"1\"}}"; mockMvc.perform(post("/signup/add").content(EMPLOYEE_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().is4xxClientError()) .andExpect(jsonPath("$.errorMessage").value("Input validation failed: Email cannot be empty")); } @Test public void testWhenPasswordIsSmall() throws Exception { String USER_REQUEST = "{\"name\":\"Nimissshhhaaa\",\"email\":\"nimimim@gmail.com\",\"password\":\"44\",\"blackListStatus\":\"false\",\"language\":{\"id\": \"1\"}}"; mockMvc.perform(post("/signup/save").content(USER_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().is4xxClientError()).andExpect(jsonPath("$.errorMessage") .value("Input validation failed: Password must be 3 to 20 characters")); } @Test public void testWhenNameIsSmall() throws Exception { String USER_REQUEST = "{\"name\":\"nid\",\"email\":\"ankitani4@gmail.com\",\"password\":\"1233435\",\"blacklisted\":\"No\",\"language\":{\"id\": \"5\"}}"; mockMvc.perform(post("/signup/add").content(USER_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().is4xxClientError()).andExpect( jsonPath("$.errorMessage").value("Input validation failed: Name must be 4 to 30 characters")); } @Test public void testUserDetailsByEmail() throws Exception { mockMvc.perform(get("/signup/analystDetail/anki@gmail.com").contentType("application/json;charset=UTF-8")) .andExpect(status().isOk()).andDo(MockMvcResultHandlers.print()) .andExpect(jsonPath("$.email").value("anki@gmail.com")); } @Test public void testForChangedUserStatus() throws Exception { mockMvc.perform(get("/signup/saveUserStatus/anki@gmail.com").contentType("application/json;charset=UTF-8")) .andExpect(status().isOk()).andDo(MockMvcResultHandlers.print()) .andExpect(jsonPath("$.blacklisted").value("Yes")); } @Test public void addFavouriteArticleTest() throws Exception { String EMPLOYEE_REQUEST = "{\"email\" : \"anki@gmail.com\",\"favouriteArticle\" :[{\"title\":\"java\",\"description\":\"java java\",\"language\":{\"id\":2}}]}"; mockMvc.perform( post("/signup/articleList").content(EMPLOYEE_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().is2xxSuccessful()); } @Test public void loginTest() throws Exception { String EMPLOYEE_REQUEST = "{\"email\":\"anki@gmail.com\",\"password\":\"1234\"}"; mockMvc.perform(post("/authenticate").content(EMPLOYEE_REQUEST).contentType("application/json;charset=UTF-8")) .andExpect(status().isOk()); } }
true
986b301315c4960e76e1379f0e68512db1f86f36
Java
emrahdmr/techproedsummer2020turkish
/src/day13whiledowhileloops/WhileLoop01.java
UTF-8
345
3.109375
3
[]
no_license
package day13whiledowhileloops; public class WhileLoop01 { public static void main(String[] args) { //while loop kullanarak ilk 5 sayma sayisini ekrana yazidien prog yazin //Scanner scan = new Scanner(System.in); int sum = 0; int num=1; while(num<6) { sum= sum+num; num++; } System.out.println(sum); } }
true
faf60a2d86f4a725adb6dd13684e0e47b2c4c856
Java
arahansa/crawler4naverNews
/src/com/arahansa/domain/Article.java
UTF-8
769
2.25
2
[]
no_license
package com.arahansa.domain; public class Article { private String aLink; private String press; private String time; private String desc; public Article() { } public String getaLink() { return aLink; } public void setaLink(String aLink) { this.aLink = aLink; } public String getPress() { return press; } public void setPress(String press) { this.press = press; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "Article [\naLink=" + aLink + "\n, press=" + press + "\n, time=" + time + "\n, desc=" + desc + "]"; } }
true
603ef5557920ed82b3f6ba1ff53d337e2cea85c0
Java
elsudano/Napakalaki
/src/Main.java
UTF-8
2,313
3.3125
3
[]
no_license
import gui.Dice; import gui.NapakalakiView; import gui.PlayerNamesCapture; import napakalaki.Napakalaki; public class Main { public static void main(String[] args) { /** * Creamos el objeto que contendra la vista del programa. */ NapakalakiView napakalakiView = new NapakalakiView(); /** * Creamos el controlador que gestionara la logica del programa. */ Napakalaki game = Napakalaki.getInstance(); /** * Creamos la unica instancia del dado que habrá en el programa * esto lo hacemos aquí por que es el único sitio que se inicializa * el dado. */ Dice.createInstance (napakalakiView); /** * Creamos un objeto que será el que capture el nombre de los jugadores * tiene que ir en este orden para que funcione correctamente. */ PlayerNamesCapture namesCapture = new PlayerNamesCapture(napakalakiView, true); /** * Creamos un array de Strings que será el que contenga todos los nombres * y lo inicializamos con los datos que capturamos desde el objeto anterior * si nos damos cuenta lo que devuelve el metodo getName() del objeto * anterior es un array de Strings con los nombres. * * esta variable se puede odviar, puesto que la función se puede llamar * mientras se esta iniciando el juego. */ //ArrayList<String> names = namesCapture.getNames(); /** * Ahora inicializamos el juego con los datos de los jugadores que ya * hemos capturado con anterioridad. */ game.initGame(namesCapture.getNames()); /** * Asignamos el controlador a la vista, hay que tener en cuenta que el * controlador tiene que estar inicializado para que contenga los datos * que queremos pasarle a la vista, ya que si no lo hacemos en este * orden habrá datos que necesite la vista y que estén a NULL. */ napakalakiView.setNapakalaki(game); /** * Le decimos a la ventana de la vista que se muestre en la pantalla, * una vez que ya lo tenemos todo inicializado enseñamos la interfaz. */ napakalakiView.setVisible (true); } }
true
ac9ae9a40e2db63c5fa2ca2cc6ce6545015728bc
Java
imran1007/3BIN
/I314C_Design_Patterns/Revision/Seance07/src/PatternRobots.java
UTF-8
1,019
3.3125
3
[]
no_license
// Director public class PatternRobots { public static void fight(Robot robot1, Robot robot2) { int tick1=robot1.getFreq(); int tick2=robot2.getFreq(); while(robot2.diffLife(0)>0 && robot1.diffLife(0)>0) { int tick=Math.min(tick1, tick2); tick1-=tick; tick2-=tick; if (tick1==0) {// robot 1 feu tick1=shoot(robot1,robot2); } if (tick2==0) {// robot 2 feu tick2=shoot(robot2,robot1); } } } private static int shoot(Robot robot1, Robot robot2) { int dmg=Math.max(0,robot1.getCanon()-robot2.getShield()); int lost=robot2.diffLife(0)-robot2.diffLife(-dmg); System.out.println(robot1.getName()+" shoots for "+lost); if (robot2.diffLife(0)<=0) { System.out.println("Kabooom "+robot2.getName()); } return robot1.getFreq(); } public static void main(String[] args) { RobotFlyWeightFactory rbf = new RobotFlyWeightFactory(); fight(rbf.getFlyWeight(RobotFlyWeightFactory.PICVERT).create(), rbf.getFlyWeight(RobotFlyWeightFactory.GROSSEBERTA).create()); } }
true
05a6d707832831d06d12e7e76e3056f979ebd6cc
Java
xinpan0214/stornetonline
/src/main/java/com/ch/stornetonline/modules/app/filter/HttpServletFilter.java
UTF-8
1,043
2.046875
2
[]
no_license
package com.ch.stornetonline.modules.app.filter; import com.ch.stornetonline.modules.app.http.RequestWrapper; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @WebFilter(filterName = "HttpServletFilter", urlPatterns = "/*") public class HttpServletFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { ServletRequest requestWrapper = null; if (req instanceof HttpServletRequest) { requestWrapper = new RequestWrapper((HttpServletRequest) req); } if (requestWrapper == null) { chain.doFilter(req, resp); } else { chain.doFilter(requestWrapper, resp); } } public void init(FilterConfig config) throws ServletException { } }
true
24ecf64c0786479d7fa30feaa2f57d5fc21e2971
Java
t617/Digital-Image-Processing
/ScaleAndQuantizeImage/src/Quantize.java
GB18030
1,481
2.984375
3
[]
no_license
import javax.imageio.*; import java.awt.image.BufferedImage; import java.io.*; public class Quantize { public BufferedImage image; public Quantize(BufferedImage img, String outputImagePath, int level) throws IOException { testExample(img, outputImagePath, level); } public int changeLevelARGBToGray(int gray, int gap, int level) { /*͸ֵͨ*/ int A = (gray >> 24) & 0xFF; int temp = gray & 0xFF; double n = 256 / level; temp = (int)(temp / n) * gap; /*ԭҶͼ*/ int grayARGB = A << 24 | temp << 16 | temp << 8| temp; return grayARGB; } public BufferedImage quantizeImage(BufferedImage img, int level) throws IOException { int gap = (int) (255 / (level - 1)); int width = img.getWidth(); int height = img.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int grayARGB = img.getRGB(j, i); img.setRGB(j, i, changeLevelARGBToGray(grayARGB, gap, level)); } } return img; } public void testExample(BufferedImage img, String outputImagePath, int level) throws IOException { BufferedImage t1 = quantizeImage(img, level); outputImage(t1, outputImagePath, level); } public void outputImage(BufferedImage img, String outputImagePath, int level) throws IOException { OutputStream output = new FileOutputStream(outputImagePath + String.valueOf(level)+ "-level.png"); ImageIO.write(img, "png", output); } }
true
9ba294bd74075f9bd202e8a2cba5ea39d276a233
Java
gleclaire/findbugs-2.0.2
/server/common/src/java/edu/umd/cs/findbugs/flybush/QueryServlet.java
UTF-8
12,245
1.9375
2
[]
no_license
package edu.umd.cs.findbugs.flybush; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.Evaluation; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.FindIssues; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.FindIssuesResponse; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.GetRecentEvaluations; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.Issue; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.Issue.Builder; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.ProtoClasses.RecentEvaluations; import edu.umd.cs.findbugs.cloud.appEngine.protobuf.WebCloudProtoUtil; @SuppressWarnings("serial") public class QueryServlet extends AbstractFlybushServlet { @Override protected void handlePost(PersistenceManager pm, HttpServletRequest req, HttpServletResponse resp, String uri) throws IOException { if (uri.equals("/find-issues")) { findIssues(req, resp, pm); } else if (uri.equals("/get-recent-evaluations")) { getRecentEvaluations(req, resp, pm); } } private void findIssues(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm) throws IOException { FindIssues loginMsg = FindIssues.parseFrom(req.getInputStream()); if (loginMsg.hasVersionInfo()) { recordAppVersionStats(req.getRemoteAddr(), pm, loginMsg.getVersionInfo()); } List<String> hashes = WebCloudProtoUtil.decodeHashes(loginMsg.getMyIssueHashesList()); Map<String, DbIssue> issues = persistenceHelper.findIssues(pm, hashes); FindIssuesResponse.Builder issueProtos = FindIssuesResponse.newBuilder(); issueProtos.setCurrentServerTime(System.currentTimeMillis()); int found = 0; for (String hash : hashes) { DbIssue dbIssue = issues.get(hash); Builder issueBuilder = Issue.newBuilder(); if (dbIssue != null) { buildTerseIssueProto(dbIssue, issueBuilder); found++; } Issue protoIssue = issueBuilder.build(); issueProtos.addFoundIssues(protoIssue); } LOGGER.info("Found on server: " + found + ", missing from server: " + (hashes.size() - found)); resp.setStatus(200); issueProtos.build().writeTo(resp.getOutputStream()); } static final long ONE_DAY = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS); @SuppressWarnings("unchecked") private void getRecentEvaluations(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm) throws IOException { GetRecentEvaluations recentEvalsRequest = GetRecentEvaluations.parseFrom(req.getInputStream()); long startTime = Math.max(recentEvalsRequest.getTimestamp(), System.currentTimeMillis() - ONE_DAY); String limitParam = req.getParameter("_debug_max"); int limit = limitParam != null ? Integer.parseInt(limitParam) : 10; LOGGER.info("Looking for " + limit + " updates since " + new Date(startTime) + " for " + req.getRemoteAddr()); // we request limit+1 so we can tell the client whether there are more results beyond the limit they provided. int queryLimit = limit + 1; Query query = pm.newQuery(); query.setClass(persistenceHelper.getDbEvaluationClass()); query.setFilter("when > " + startTime); query.setOrdering("when ascending"); query.setRange(0, queryLimit); List<DbEvaluation> evaluations = (List<DbEvaluation>) query.execute(); int resultCount = evaluations.size(); LOGGER.fine(resultCount + " results"); RecentEvaluations.Builder issueProtos = RecentEvaluations.newBuilder(); issueProtos.setCurrentServerTime(System.currentTimeMillis()); Iterator<DbEvaluation> iterator = evaluations.iterator(); Map<String, SortedSet<DbEvaluation>> issues = groupUniqueEvaluationsByIssue(iterator, limit); boolean askAgain = false; try { for (SortedSet<DbEvaluation> evaluationsForIssue : issues.values()) { DbIssue issue = evaluationsForIssue.iterator().next().getIssue(); Issue issueProto = buildFullIssueProto(issue, evaluationsForIssue); issueProtos.addIssues(issueProto); LOGGER.fine(evaluationsForIssue.size() + " evals"); } } catch (RuntimeException e) { if (issueProtos.getIssuesCount() > 0) { LOGGER.log(Level.WARNING, e.getClass().getSimpleName() + ", returning only " + issueProtos.getIssuesCount() + " results", e); askAgain = true; } else { // just return 500 so the client tries again throw e; } } query.closeAll(); if (!askAgain) { askAgain = resultCount > limit; LOGGER.info("Returning " + issueProtos.getIssuesCount() + (askAgain ? " (more to come)" : "")); } issueProtos.setAskAgain(askAgain); resp.setStatus(200); issueProtos.build().writeTo(resp.getOutputStream()); } // ========================= end of request handling // ================================ @SuppressWarnings({"unchecked"}) protected void recordAppVersionStats(String ip, PersistenceManager pm, ProtoClasses.VersionInfo loginMsg) { String msg = "Ignoring exception that occurs while recording app version"; try { String appName = loginMsg.getAppName(); String appVer = loginMsg.getAppVersion(); if (appVer == null) appVer = "<notgiven>"; String fbVersion = loginMsg.getFindbugsVersion(); if (appName != null || fbVersion != null) { if (fbVersion == null) fbVersion = "<notgiven>"; LOGGER.info("FindBugs " + fbVersion + (appName != null ? " via " + appName + " " + appVer : "")); } if (appName != null) { long midnightToday = getMidnightToday(); msg = String.format("Ignoring exception that occurs while recording app %s version %s from %s on %tD", appName, appVer,ip, midnightToday); if (!persistenceHelper.shouldRecordClientStats(ip, appName, appVer, midnightToday)) { return; } Transaction tx = pm.currentTransaction(); tx.begin(); try { Query q = pm.newQuery("select from " + persistenceHelper.getDbClientVersionStatsClassname() + " where application == :name && version == :ver && dayStart == :todayStart"); List<DbClientVersionStats> results = (List<DbClientVersionStats>) q.execute(appName, appVer, midnightToday); DbClientVersionStats entry; if (results.isEmpty()) { LOGGER.info("First hit from this client/version today!"); entry = persistenceHelper.createDbClientVersionStats(appName, appVer, midnightToday); } else { entry = results.get(0); LOGGER.info("Increasing hit count to " + (entry.getHits() + 1)); } q.closeAll(); entry.incrHits(); pm.makePersistent(entry); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } } } } catch (Exception e) { LOGGER.log(Level.INFO, msg, e); } } private long getMidnightToday() { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(getCurrentTimeMillis()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); } private void buildTerseIssueProto(DbIssue dbIssue, Builder issueBuilder) { issueBuilder.setFirstSeen(dbIssue.getFirstSeen()).setLastSeen(dbIssue.getLastSeen()); if (dbIssue.getBugLink() != null) { issueBuilder.setBugLink(dbIssue.getBugLink()); String linkType = dbIssue.getBugLinkType(); if (linkType != null) issueBuilder.setBugLinkTypeStr(linkType); } if (dbIssue.hasEvaluations()) { addEvaluations(issueBuilder, dbIssue.getEvaluations()); } } private Issue buildFullIssueProto(DbIssue dbIssue, Set<? extends DbEvaluation> evaluations) { Issue.Builder issueBuilder = Issue.newBuilder() .setBugPattern(dbIssue.getBugPattern()) .setPriority(dbIssue.getPriority()) .setHash(WebCloudProtoUtil.encodeHash(dbIssue.getHash())) .setFirstSeen(dbIssue.getFirstSeen()) .setLastSeen(dbIssue.getLastSeen()) .setPrimaryClass(dbIssue.getPrimaryClass()); if (dbIssue.getBugLink() != null) { issueBuilder.setBugLink(dbIssue.getBugLink()); String linkType = dbIssue.getBugLinkType(); if (linkType != null) issueBuilder.setBugLinkTypeStr(linkType); } addEvaluations(issueBuilder, evaluations); return issueBuilder.build(); } private void addEvaluations(Builder issueBuilder, Set<? extends DbEvaluation> evaluations) { for (DbEvaluation dbEval : sortAndFilterEvaluations(evaluations)) { Evaluation.Builder eval = Evaluation.newBuilder() .setComment(dbEval.getComment()) .setDesignation(dbEval.getDesignation()) .setWhen(dbEval.getWhen()); if (dbEval.getEmail() != null) eval.setWho(dbEval.getEmail()); else LOGGER.warning("Warning: evaluation has no email address: " + "issue=" + dbEval.getIssue().getHash() + ", user=" + dbEval.getWhoId() + ", date=" + new Date(dbEval.getWhen())); issueBuilder.addEvaluations(eval.build()); } } private Map<String, SortedSet<DbEvaluation>> groupUniqueEvaluationsByIssue(Iterable<DbEvaluation> evaluations) { Iterator<DbEvaluation> iterator = evaluations.iterator(); return groupUniqueEvaluationsByIssue(iterator, Integer.MAX_VALUE); } private Map<String, SortedSet<DbEvaluation>> groupUniqueEvaluationsByIssue(Iterator<DbEvaluation> iterator, int limit) { Map<String, SortedSet<DbEvaluation>> issues = new HashMap<String, SortedSet<DbEvaluation>>(); for (int i = 0; iterator.hasNext() && i < limit; i++) { DbEvaluation dbEvaluation = iterator.next(); String issueHash = dbEvaluation.getIssue().getHash(); SortedSet<DbEvaluation> evaluationsForIssue = issues.get(issueHash); if (evaluationsForIssue == null) { evaluationsForIssue = new TreeSet<DbEvaluation>(); issues.put(issueHash, evaluationsForIssue); } // only include the latest evaluation for each user for (Iterator<DbEvaluation> it = evaluationsForIssue.iterator(); it.hasNext();) { DbEvaluation eval = it.next(); if (eval.getWho().equals(dbEvaluation.getWho())) it.remove(); } evaluationsForIssue.add(dbEvaluation); } return issues; } }
true
8aec9ae1bb9fe253e554d937c064552f7ef7c5a9
Java
marciopocebon/projetos-Springboot-1
/exemplopostconstructpredestroy/src/main/java/jardin/nicolas/exemplopostconstructpredestroy/model/Client.java
UTF-8
438
2.328125
2
[ "MIT" ]
permissive
package jardin.nicolas.exemplopostconstructpredestroy.model; import lombok.*; import org.springframework.stereotype.Component; /** * @author Nicólas * @version 1.0 * @since 6/11/2020 - 3:19 PM */ //Lombok @ToString @Getter @Setter @AllArgsConstructor //Sprintboot @Component public class Client { private String name; private String lastName; public Client() { System.out.println("Classe cliente"); } }
true
f58a54b125f83233f529a72d7989f0042fbb40cd
Java
AngelBanuelos/algorithms
/src/com/tuinsomniacorp/learning/sort/QuickSort.java
UTF-8
2,636
3.3125
3
[ "MIT" ]
permissive
package com.tuinsomniacorp.learning.sort; import com.tuinsomniacorp.learning.utils.Utils; /** * * @author Angel Banuelos ing.angel.banuelos@gmail.com */ public class QuickSort implements Sort { private long swapCount; private long comparisonCount; private long executionTime; @Override public long getSwapCount() { return swapCount; } @Override public long getComparisonCount() { return comparisonCount; } @Override public long getExecutionTime() { return executionTime; } @Override public String getSortingName() { return CountingSort.class.getName(); } @Override public void printAnalysis() { System.out.println(getSortingName() + ", " + getSwapCount() + ", " + getComparisonCount() + ", " + getExecutionTime()); } @Override public void reset() { comparisonCount = 0L; swapCount = 0L; executionTime = 0L; } @Override public int[] sort(int[] array) { int leftPointer = 0; int rightPointer = array.length - 1; return quickSort(array, leftPointer, rightPointer); } private int[] quickSort(int[] array, int leftPointer, int rightPointer) { if (rightPointer <= leftPointer || rightPointer - leftPointer == 1) { if (rightPointer > leftPointer && array[rightPointer] < array[leftPointer]) { Utils.swap(array, leftPointer, rightPointer); } return array; } else { int partitionPos = partition(array, leftPointer, rightPointer - 1, rightPointer); quickSort(array, leftPointer, partitionPos - 1); quickSort(array, partitionPos + 1, rightPointer); } return array; } private int partition(int[] array, int leftPointer, int rightPointer, int pivot) { int tempLeft = leftPointer, tempRigth = rightPointer; int pivotNum = array[pivot]; while (!(tempLeft >= tempRigth)) { while (tempLeft <= rightPointer && array[tempLeft] <= pivotNum) { tempLeft++; } while (tempRigth >= leftPointer && array[tempRigth] >= pivotNum) { tempRigth--; } if (tempLeft < tempRigth) { Utils.swap(array, tempLeft, tempRigth); tempLeft++; tempRigth--; } } if (tempLeft != pivot) { Utils.swap(array, tempLeft, pivot); } return tempLeft; } }
true
47b6f0ff5bcd30596205e2ea7569fc93ff96ad3c
Java
gameballers/gb-mobile-android
/gameballsdk/src/main/java/com/gameball/gameball/model/response/PlayerRegisterResponse.java
UTF-8
423
2.109375
2
[]
no_license
package com.gameball.gameball.model.response; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class PlayerRegisterResponse { @SerializedName("gameballId") @Expose() private String GameballId; public String getGameballId() { return GameballId; } public void setGameballId(String gameballId) { GameballId = gameballId; } }
true
3ba3220d94c518dfcec459f31b7c961ff0444c88
Java
JS-EDV/JHeli2D
/src/com/heligame/GamePanel.java
UTF-8
8,397
2.5
2
[]
no_license
package com.heligame; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import java.net.URL; import java.util.ArrayList; import java.util.ListIterator; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class GamePanel extends JPanel implements Runnable, KeyListener, ActionListener { private static final long serialVersionUID = 1L; JFrame frame; long delta = 0; long last = 0; long fps = 0; long gameover = 0; /* * Debugging [dbg = false] -> DebugMode off */ boolean dbg= true; // DebugSwitch long obs = 0; // Number of Objects actually shown onScreen long rmvdobs =0; // Number of all removed Objects this session long helis =0; // Number of Helicopters actually shown onScreen long clds=0; // Number of Clouds actually shown onScreen long rocks =0; // Number of Rockets actually shown onScreen long score=0; // Score of the actual game Heli copter; ArrayList<Sprite> actors; ArrayList<Sprite> painter; boolean up; boolean down; boolean left; boolean right; boolean started; int speed = 50; Timer timer; BufferedImage[] rocket; BufferedImage[] explosion; BufferedImage background; SoundLib soundLib; public static void main(String[] args) { new GamePanel(800, 600); } public GamePanel(int w, int h) { this.setPreferredSize(new Dimension(w, h)); this.setBackground(Color.blue); frame = new JFrame("Name of the Game"); frame.setLocation(100, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(this); frame.addKeyListener(this); frame.pack(); frame.setVisible(true); Thread th = new Thread(this); th.start(); } private void doInits() { last = System.nanoTime(); gameover = 0; BufferedImage[] heli = loadPics("com/heligame/pics/heli.gif", 4); rocket = loadPics("com/heligame/pics/rocket.gif", 8); background = loadPics("com/heligame/pics/background.jpg",1)[0]; explosion = loadPics("com/heligame/pics/explosion.gif", 5); actors = new ArrayList<Sprite>(); painter = new ArrayList<Sprite>(); copter = new Heli(heli, 400, 300, 100, this); createClouds(); actors.add(copter); soundLib = new SoundLib(); soundLib.loadSound("bumm", "com/heligame/sound/boom.wav"); soundLib.loadSound("rocket", "com/heligame/sound/rocket2_start.wav"); soundLib.loadSound("heli", "com/heligame/sound/heli.wav"); helis++; timer = new Timer(3000,this); timer.start(); started = true; } private void createClouds() { BufferedImage[] bi = loadPics("com/heligame/pics/cloud.gif", 1); for(int y=10; y<getHeight(); y+=50){ int x = (int)(Math.random()*getWidth()); Cloud cloud = new Cloud(bi, x, y, 1000, this); ListIterator<Sprite> itcC = actors.listIterator(); itcC.add(cloud); clds++; } } private void createRocket(){ int x = 0; int y = (int)(Math.random()*getHeight()); int hori = (int)(Math.random()*2); if(hori == 0){ x = -30; } else { x = getWidth()+30; } Rocket rock = new Rocket(rocket,x,y,100,this); if(x<0){ rock.setHorizontalSpeed(100); } else { rock.setHorizontalSpeed(-100); } ListIterator<Sprite> itcR = actors.listIterator(); itcR.add(rock); soundLib.playSound("rocket"); } public void createExplosion(int x, int y){ ListIterator<Sprite> itcE = actors.listIterator(); itcE.add(new Explosion(explosion, x, y, 100, this)); soundLib.playSound("bumm"); } @Override public void run() { while (frame.isVisible()) { computeDelta(); if(isStarted()){ checkKeys(); doLogic(); moveObjects(); cloneArrays(); } repaint(); try { Thread.sleep(10); } catch (InterruptedException e) {} } } @SuppressWarnings(value = {"unchecked"}) private void cloneArrays() { painter = (ArrayList<Sprite>) actors.clone(); } public boolean isStarted() { return started; } public void setStarted(boolean started){ this.started = started; } private void computeDelta() { delta = System.nanoTime() - last; last = System.nanoTime(); fps = ((long) 1e9) / delta; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(background, 0, 0, this); g.setColor(Color.MAGENTA); g.drawString("Score: " + Long.toString(score), 20, 10); if(dbg){ g.setColor(Color.green); g.drawString("FPS: " + Long.toString(fps), 20, 35); g.drawString("onScreen Objects: "+ Long.toString(obs),20,50); g.drawString("onScreen Helicopter:"+ Long.toString(helis),20,65); g.drawString("onScreen Clouds: "+ Long.toString(clds),20,80); g.drawString("onScreen Rockets: "+ Long.toString(rocks),20,95); g.drawString("Removed Rockets: "+ Long.toString(rmvdobs),20,110); } if (!started) { return; } if (painter != null) { for (ListIterator<Sprite> itpC = painter.listIterator(); itpC.hasNext();) { Sprite r = itpC.next(); r.drawObjects(g); } } } private void moveObjects() { for (ListIterator<Sprite> itmO = actors.listIterator(); itmO.hasNext();) { Sprite r = itmO.next(); r.move(delta); } } private void doLogic() { for (ListIterator<Sprite> itdL = actors.listIterator(); itdL.hasNext();) { Sprite r = itdL.next(); r.doLogic(delta); if(r.remove){ itdL.remove(); rmvdobs++; rocks--; score +=50; } } obs = actors.size(); for(int i =0;i<actors.size();i++){ for(int n = i+1;n<actors.size();n++){ Sprite s1 = actors.get(i); Sprite s2 = actors.get(n); s1.colliededWith(s2); } } if(copter.remove && gameover ==0){ gameover = System.currentTimeMillis(); } if(gameover>0){ if(System.currentTimeMillis()-gameover>1500){ stopGame(); } } } private void startGame(){ doInits(); setStarted(true); soundLib.loopSound("heli"); } private void stopGame() { timer.stop(); setStarted(false); soundLib.stopLoopSound(); } private void checkKeys() { if (up) { copter.setVerticalSpeed(-speed); } if (down) { copter.setVerticalSpeed(speed); } if (right) { copter.setHorizontalSpeed(speed); } if (left) { copter.setHorizontalSpeed(-speed); } if (!up && !down) { copter.setVerticalSpeed(0); } if (!left && !right) { copter.setHorizontalSpeed(0); } } private BufferedImage[] loadPics(String path, int pics) { BufferedImage[] anim = new BufferedImage[pics]; BufferedImage source = null; URL pic_url = getClass().getClassLoader().getResource(path); try { source = ImageIO.read(pic_url); } catch (IOException e) { } for (int x = 0; x < pics; x++) { anim[x] = source.getSubimage(x * source.getWidth() / pics, 0, source.getWidth() / pics, source.getHeight()); } return anim; } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { up = true; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { down = true; } if (e.getKeyCode() == KeyEvent.VK_LEFT) { left = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { right = true; } } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { up = false; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { down = false; } if (e.getKeyCode() == KeyEvent.VK_LEFT) { left = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { right = false; } if (e.getKeyCode() == KeyEvent.VK_ENTER){ if(!isStarted()){ startGame(); } } if (e.getKeyCode() == KeyEvent.VK_ESCAPE){ if(isStarted()){ stopGame(); }else{ frame.dispose(); } } } @Override public void keyTyped(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) { if(isStarted() && e.getSource().equals(timer)){ createRocket(); rocks++; } } }
true
8fde4806df0ee127b3b95aace67d97c3be46281b
Java
gaopan461/netty-server
/src/main/java/core/Node.java
UTF-8
4,874
2.40625
2
[]
no_license
package core; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import core.handler.MessagePackDecode; import core.handler.ServerHandler; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * 一个节点(进程) * @author gaopan */ public class Node { /** node的id */ private String id; /** node的监听端口 */ private int port; /** netty boss */ private NioEventLoopGroup boss; /** netty worker */ private NioEventLoopGroup worker; /** 已经编码后的ping消息 */ private MessagePack pingMessage; /** 远程节点列表 */ private Map<String, RemoteNode> remoteNodes = new ConcurrentHashMap<>(); /** 接收到待处理的请求 */ private Queue<MessagePack> receivedMessages = new ConcurrentLinkedQueue<>(); public Node(String id, int port) { this.id = id; this.port = port; this.pingMessage = MessagePack.buildPing(id, port); } public void startup() { boss = new NioEventLoopGroup(1); worker = new NioEventLoopGroup(1); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, -4, 4)); pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8)); pipeline.addLast(new MessagePackDecode()); pipeline.addLast(new ServerHandler(Node.this)); } }); bootstrap.bind(port); } public void shutdown() { worker.shutdownGracefully(); boss.shutdownGracefully(); } public void pulse() { MessagePack message; while ((message = receivedMessages.poll()) != null) { handleMessage(message); } for (RemoteNode remoteNode : remoteNodes.values()) { remoteNode.pulse(); } } private void handleMessage(MessagePack messagePack) { Log.core.info("[{} <--- {}]处理消息,消息={}", id, messagePack.getSender(), messagePack.getContext()); } public void handlePing(String nodeId, String ip, int port) { RemoteNode remoteNode = addRemoteNode(nodeId, ip, port); remoteNode.handlePing(); } public RemoteNode addRemoteNode(String nodeId, String ip, int port) { RemoteNode newNode = new RemoteNode(this, nodeId, ip, port); return remoteNodes.compute(nodeId, (k, v) -> { if (v == null) { newNode.startup(); return newNode; } else if (v.needRebuild(newNode)) { v.shutdown(); newNode.startup(); return newNode; } else { return v; } }); } public void delRemoteNode(String nodeId) { RemoteNode remoteNode = remoteNodes.remove(nodeId); if (remoteNode != null) { remoteNode.shutdown(); } } public void sendMessage(String nodeId, String message) { RemoteNode remoteNode = remoteNodes.get(nodeId); if (remoteNode != null) { remoteNode.sendMessage(MessagePack.buildMessage(id, message)); } else { Log.core.info("[{} ---> {}发送消息失败,未知的远程节点,message={}]", id, nodeId, message); } } public void addReceiveMessage(MessagePack messagePack) { receivedMessages.offer(messagePack); } public String getId() { return id; } public MessagePack getPingMessage() { return pingMessage; } }
true
f28872fd7c26f6d0e77b2a6ebbb0556dfe4da59d
Java
nolte/keenio-gateway
/src/main/java/de/noltarium/keenio/gateway/security/WebSecurityConfig.java
UTF-8
1,003
1.859375
2
[]
no_license
package de.noltarium.keenio.gateway.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @EnableWebSecurity @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private TravisCIAuthRequestFilter filter; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().addFilterBefore(filter, BasicAuthenticationFilter.class); } }
true
78e6c6a75afc38aacbb419061fac0405b0b3aa9a
Java
RogerRatu/PartD
/Assignment2PartD/src/PartD.java
UTF-8
313
3.03125
3
[]
no_license
public class PartD { public static void main(String[] args) { System.out.println("Hi, my name is_____"); System.out.println("My favourite colour is _____"); System.out.println("My favourite mode of transportation is_____"); System.out.println("The best day of the week is_____"); } }
true
7842647f9209735e7d7b0bfabc48131c5e0b97f2
Java
jsostaric/Algebra
/NetBeansProjects/Iznimke/src/iznimke/Iznimke.java
UTF-8
1,472
3.375
3
[]
no_license
package iznimke; import java.util.ArrayList; public class Iznimke { public static void main(String[] args) { /* ArrayList<String> nizovi = new ArrayList<>(); try { int a = 10; int b = 0; System.out.println(a/b); System.out.println("linija koda 1"); }catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } System.out.println("linija koda 2"); */ int broj = 0; String unos = "234d"; int[] polje = {1,2,3}; try { //1. greška // broj = new Integer(unos); //2.greška // broj = polje[5]; //3.greška broj = broj/0; }catch(NumberFormatException e) { System.out.println("Greška pri konverziji znakovnog niza u broj"); }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Greška pri pristupu elementu iz polja"); }catch(ArithmeticException e) { System.out.println("Greška prilikom dijeljenja sa nulom"); }catch(Exception e) { System.out.println("Sve ostale greške"); }finally{ System.out.println("Završetak programa"); } } //end of main }
true
03a9bc174e185caa746c185d285bc60020854fbc
Java
PoisonIvysaurBridge/profsmato
/src/test/java/main/StudentTest.java
UTF-8
1,922
2.796875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package main; import dao.DataSource; import java.beans.PropertyVetoException; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import model.Student; /** * * @author inoue */ public class StudentTest { public static void main(String[] args) { studentInstantiationTest(); } public static void studentInstantiationTest(){ Connection conn = null; PreparedStatement pStmt = null; ResultSet rs = null; Student student = null; try{ conn = DataSource.getInstance().getConnection(); student = new Student("yuta_inoue@dlsu.edu.ph", conn, pStmt, rs); } catch (IOException | SQLException | PropertyVetoException ex) { ex.printStackTrace(); }finally{ if(conn != null) try{ conn.close(); }catch(SQLException e){} if(pStmt != null) try{ pStmt.close(); }catch(SQLException e){} if(rs != null) try{ rs.close(); }catch(SQLException e){} } System.out.println("Email: " + student.getStudentEmail()); System.out.println("Username: " + student.getUsername()); System.out.println("Firstname: " + student.getFirstname()); System.out.println("Lastname: " + student.getLastname()); System.out.println("User Type: " + student.getUserType()); System.out.println("Degree: " + student.getProgram().getDegreeCode()); System.out.println("Degree Name: " + student.getProgram().getProgramName()); System.out.println("Attached College: " + student.getProgram().getAttachedCollege()); } }
true
c2a9c96e351210f3af3562a5c7556edc6e42f6b2
Java
Astor730/RoomLab
/src/Game/Board.java
UTF-8
803
3.296875
3
[]
no_license
package Game; import Rooms.Room; import Rooms.WinningRoom; public class Board { public Room[][] map = new Room[5][5]; private int x; private int y; public Board(int x,int y,Room[][]map) { this.x = x; this.y = y; this.map = map; } public void makeMap() { for(int i = 0;i<map.length;i++) { for(int x = 0; x<map[i].length;x++) { map[i][x] = new Room(i,x); } } } public void print() { String row = ""; for(int i = 0; i<map.length;i++) { row = ""; for(int x = 0;x<map[i].length;x++) { row = row + map[i][x].toString(); } System.out.println(row); } } }
true
04eb328c2d41c069da73d5f25883d40422f31240
Java
aarontoko/AndrewMac
/ACSWeiler/src/Lab11/TriangleFive.java
UTF-8
558
3.171875
3
[]
no_license
package Lab11; public class TriangleFive { // this lab is setup with a single static method // there are no instance variables or additional methods / constructors public static String createTriangle5(String let, int size) { String output = ""; int count = 0; int count2 = 0; char test = let.charAt(0); do{ for (int i = 1; i <= size-count; i++) { output += "\n"; for (int c = 1; c <= size-count; c++){ output += ((char)(test+count)) + ""; } } count++; }while(count<=size); return output; } }
true
4ca497b0646139463b4fa9ee6e55751621b9daa6
Java
gerker/onlineMall
/src/main/java/com/zyt/service/impl/orderTaskAndTaskItems/impl/OrderTaskDetailsServiceImpl.java
UTF-8
3,009
2.109375
2
[]
no_license
package com.zyt.service.impl.orderTaskAndTaskItems.impl; import com.zyt.entity.OrderTaskDetail; import com.zyt.mapper.OrderTaskDetailMapper; import com.zyt.service.orderTaskAndTaskItems.OrderTaskDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @ProjectName: online_drink_mall * @Package: com.zyt.service.impl.orderTaskAndTaskItems.impl * @ClassName: OrderTaskDetailsServiceImpl * @Author: zhou_yangtao@yeah.net * @Description: 订单工作单明细表服务层实现模块 * @Date: 17:25 2021/3/2 * @Version: 1.0 */ @Service(value = "orderTaskDetailsService") public class OrderTaskDetailsServiceImpl implements OrderTaskDetailsService { @Autowired private OrderTaskDetailMapper orderTaskDetailMapper; /** * @Method: saveOrderTaskDetails * @Author: zhou_yangtao@yeah.net * @Version 1.0 * @Description: * @Return: void * @Exception: * @Date: 2021/3/3 11:08 * @Param: * @param orderTaskDetail * @Return: void */ @Override public void saveOrderTaskDetails(OrderTaskDetail orderTaskDetail) { this.orderTaskDetailMapper.saveOrderTaskDetails(orderTaskDetail); } /** * @Method: getOrderTaskDetailsById * @Author: zhou_yangtao@yeah.net * @Version 1.0 * @Description:根据id查询订单工作单信息 * @Return: com.zyt.entity.OrderTaskDetail * @Exception: * @Date: 2021/3/3 14:02 * @Param: * @param detailsId * @Return: com.zyt.entity.OrderTaskDetail */ @Override public OrderTaskDetail getOrderTaskDetailsById(int detailsId) { return this.orderTaskDetailMapper.getOrderTaskDetailsById(detailsId) != null ? this.orderTaskDetailMapper.getOrderTaskDetailsById(detailsId) : null; } /** * @Method: updateOrderStockStatus * @Author: zhou_yangtao@yeah.net * @Version 1.0 * @Description:修改订单锁定状态信息 * @Return: void * @Exception: * @Date: 2021/3/3 15:39 * @Param: * @param id * @param status * @Return: void */ @Override public void updateOrderStockStatus(Integer id, int status) { this.orderTaskDetailMapper.updateOrderStockStatus(id,status); } /** * @Method: getOrderTaskDetailsByTaskIdAndStatus * @Author: zhou_yangtao@yeah.net * @Version 1.0 * @Description:获得当前订单未解所的所有订单信息 * @Return: java.util.List<com.zyt.entity.OrderTaskDetail> * @Exception: * @Date: 2021/3/3 19:23 * @Param: * @param orderDetailsId * @param status * @Return: java.util.List<com.zyt.entity.OrderTaskDetail> */ @Override public List<OrderTaskDetail> getOrderTaskDetailsByTaskIdAndStatus(Integer orderDetailsId, int status) { return this.orderTaskDetailMapper.getOrderTaskDetailsByTaskIdAndStatus(orderDetailsId,status) != null ? this.orderTaskDetailMapper.getOrderTaskDetailsByTaskIdAndStatus(orderDetailsId,status) :null; } }
true
19f708bfdc4e368e8c7867696108089b7365809d
Java
clilystudio/NetBook
/allsrc/com/ushaqi/zhuishushenqi/model/GirlTopicList.java
UTF-8
646
2.015625
2
[ "Unlicense" ]
permissive
package com.ushaqi.zhuishushenqi.model; public class GirlTopicList { private boolean ok; private GirlTopicSummary[] posts; public GirlTopicSummary[] getPosts() { return this.posts; } public boolean isOk() { return this.ok; } public void setOk(boolean paramBoolean) { this.ok = paramBoolean; } public void setPosts(GirlTopicSummary[] paramArrayOfGirlTopicSummary) { this.posts = paramArrayOfGirlTopicSummary; } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ushaqi.zhuishushenqi.model.GirlTopicList * JD-Core Version: 0.6.0 */
true
424ab4a239ad31a69e60b84e6f57c55f80eb1f20
Java
nob0dj/toby-spring-3.1
/spring31-3.5.2/src/springbook/user/dao/JdbcContext.java
UTF-8
2,173
2.9375
3
[]
no_license
package springbook.user.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; /** * * <pre> * template과 callback의 결합 * workWithStatementStrategy과 executeSql(callback생성)을 한 클래스에서 처리해서 userDao에서 좀더 간결하게 호출할 수 있도록 한다. * </pre> * * <img src="https://d.pr/i/jslTaC+" alt="" width="50%"/> */ public class JdbcContext { DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * template(context) : 변하지 않는 부분 * * @param stmt * @throws SQLException */ public void workWithStatementStrategy(StatementStrategy stmt) throws SQLException { Connection c = null; PreparedStatement ps = null; try { c = dataSource.getConnection(); ps = stmt.makePreparedStatement(c); ps.executeUpdate(); } catch (SQLException e) { throw e; } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) {} } if (c != null) { try {c.close(); } catch (SQLException e) {} } } } /** * client는 callback객체를 인자로 template를 호출한다. * * template(callback); * * @param query * @throws SQLException */ public void executeSql(final String query) throws SQLException { workWithStatementStrategy( new StatementStrategy() { public PreparedStatement makePreparedStatement(Connection c) throws SQLException { return c.prepareStatement(query); } } ); } /** * query에 대입할 값이 있는 경우 * * @param query * @throws SQLException */ public void executeSql(final String query, final Object... params) throws SQLException { workWithStatementStrategy( new StatementStrategy() { public PreparedStatement makePreparedStatement(Connection c) throws SQLException { PreparedStatement ps = c.prepareStatement(query); for(int i = 0; i < params.length; i++) { //System.out.println(params[i].getClass());//class java.lang.String ps.setObject(i + 1, params[i]); } return ps; } } ); } }
true
81560f6c130a4c28720d5aad841116cdfc47483c
Java
zaitsev726/nets_lab4_test
/testVersion/src/main/java/UserInterface/InteraceController.java
UTF-8
8,821
2.65625
3
[]
no_license
package UserInterface; import NetworkPart.GlobalController; import UserInterface.ConnectionPage.ConnectionPanel; import UserInterface.Frames.Window; import UserInterface.GamePage.GamePanel; import UserInterface.MenuPage.MenuPanel; import UserInterface.NetInfoEntryPage.NetInfoEntryPanel; import UserInterface.NewGamePage.NewGamePanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class InteraceController extends Thread { private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); private int sizeWidth = 1520; private int sizeHeight = 1045; private int locationX = (screenSize.width - sizeWidth) / 2; private int locationY = (screenSize.height - sizeHeight) / 2 - 20; private UserInterface.Frames.Window window; private MenuPanel menuPanel; private NewGamePanel newGamePanel; private GamePanel gamePanel; private ConnectionPanel connectionPanel; private NetInfoEntryPanel netInfoEntryPanel; private int heightSnakeField; private int widthSnakeField; private static InteraceController instance; public static InteraceController getInstance(){ InteraceController localInstance = instance; if(localInstance == null){ synchronized (InteraceController.class){ localInstance = instance; if(localInstance == null) instance = localInstance = new InteraceController(); } } return localInstance; } private InteraceController(){ window = new Window(sizeWidth,sizeHeight,locationX,locationY); menuPanel = new MenuPanel(sizeWidth,sizeHeight); newGamePanel = new NewGamePanel(); gamePanel = new GamePanel(); connectionPanel = new ConnectionPanel(); netInfoEntryPanel = new NetInfoEntryPanel(); window.add(menuPanel); initializationListeners(); window.setVisible(true); } private void initializationListeners(){ initializationMenuListeners(); initializationNewGamePanelListeners(); initializationGameListeners(); initializationConnectionListeners(); initializationNetInfoEntryListeners(); } private void initializationNetInfoEntryListeners() { netInfoEntryPanel.continueButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { window.remove(netInfoEntryPanel); window.add(menuPanel); window.revalidate(); window.repaint(); } }); netInfoEntryPanel.portField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Отображение введенного текста try { int w = Integer.parseInt(netInfoEntryPanel.portField.getText()); if (w > 6000 || w < 2000) { JOptionPane.showMessageDialog(window, "Введите число в диапазоне от 2000 до 6000, а не " + w); } else GlobalController.getInstance().setPort(w); } catch (NumberFormatException r) { JOptionPane.showMessageDialog(window, "Вы некорректно ввели цифры для port!"); } } }); } private void initializationConnectionListeners() { connectionPanel.backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { window.remove(connectionPanel); window.add(menuPanel); window.revalidate(); window.repaint(); } }); } private void initializationGameListeners() { gamePanel.backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(gamePanel.gameField.timer != null) gamePanel.gameField.timer.stop(); window.remove(gamePanel); window.add(newGamePanel); window.revalidate(); window.repaint(); } }); } private void initializationMenuListeners() { menuPanel.newGameButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { window.remove(menuPanel); window.add(newGamePanel); window.revalidate(); window.repaint(); } }); menuPanel.connectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { window.remove(menuPanel); window.add(connectionPanel); window.revalidate(); window.repaint(); } }); menuPanel.netInfoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { window.remove(menuPanel); window.add(netInfoEntryPanel); window.revalidate(); window.repaint(); } }); } private void initializationNewGamePanelListeners() { newGamePanel.widthField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Отображение введенного текста try { int w = Integer.parseInt(newGamePanel.widthField.getText()); if (w > 100 || w < 10) { JOptionPane.showMessageDialog(window, "Введите число в диапазоне от 10 до 100, а не " + w); } else setWidthSnakeField(w); } catch (NumberFormatException r) { JOptionPane.showMessageDialog(window, "Вы некорректно ввели цифры!"); } } }); newGamePanel.heightField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { int w = Integer.parseInt(newGamePanel.heightField.getText()); if (w > 100 || w < 10) { JOptionPane.showMessageDialog(window, "Введите число в диапазоне от 10 до 100, а не " + w); } else setHeightSnakeField(w); } catch (NumberFormatException r) { JOptionPane.showMessageDialog(window, "Вы некорректно ввели цифры!"); } } }); newGamePanel.backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { window.remove(newGamePanel); window.add(menuPanel); window.revalidate(); window.repaint(); } }); newGamePanel.continueButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { /* if(heightSnakeField < 10 || heightSnakeField > 100 || widthSnakeField < 10 || widthSnakeField > 100) // раскоментить в случае тестов! JOptionPane.showMessageDialog(window, "Вы ввели неправильный размер поля!"); else {*/ window.remove(newGamePanel); window.add(gamePanel); widthSnakeField = 20; heightSnakeField = 20; gamePanel.addGameField(widthSnakeField, heightSnakeField); gamePanel.gameField.initGame(widthSnakeField, heightSnakeField); gamePanel.setFocusable(true); gamePanel.requestFocus(); window.revalidate(); window.repaint(); } //} }); } private void setHeightSnakeField(int value){ if(value > 100 || value < 10) heightSnakeField = 0; else heightSnakeField = value; } private void setWidthSnakeField(int value){ if(value > 100 || value < 10) widthSnakeField = 0; else widthSnakeField = value; } }
true
fa19358fee08dd9612ed4ff771fd6bc93fb53598
Java
sridharsahu08/footballAPi
/src/main/java/com/sidd/football/footballrank/delegate/FootballApiLeagueDetailsDelegate.java
UTF-8
1,148
2.15625
2
[]
no_license
package com.sidd.football.footballrank.delegate; import java.util.List; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; import com.sidd.football.footballrank.model.LeagueDetails; import lombok.extern.slf4j.Slf4j; @Component @Slf4j public class FootballApiLeagueDetailsDelegate { public List<LeagueDetails> getLeagueDetails(String url) { try { log.info("uri : " + url); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<List<LeagueDetails>> leagueDetailsApiResponse = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<LeagueDetails>>() {}); ObjectMapper obj = new ObjectMapper(); // log.info(obj.writeValueAsString(leagueDetailsApiResponse.getBody())); return leagueDetailsApiResponse.getBody(); } catch (Exception ex) { log.error("Exception calling Client : " + ex.getMessage() + url); return null; } } }
true
7cf31b5c37c86ae5602ed602a4876b54be1f4850
Java
minisu/dwdemo
/src/main/java/DemoApplication.java
UTF-8
495
2.171875
2
[]
no_license
import io.dropwizard.Application; import io.dropwizard.setup.Environment; public class DemoApplication extends Application<DemoConfiguration> { @Override public void run(DemoConfiguration configuration, Environment environment) throws Exception { environment .jersey() .register(new DemoResource(configuration.getDefaultPartyDay())); } public static void main(String... args) throws Exception { new DemoApplication().run(args); } }
true
8f0a297b1ec127c3d743e7b4bed1ad6246cb427f
Java
nicovanderheide/editor
/src/main/java/nl/nicovanderheide/locale/properties/editor/support/ZipFileEntry.java
UTF-8
386
2.3125
2
[]
no_license
package nl.nicovanderheide.locale.properties.editor.support; import java.io.InputStream; public class ZipFileEntry { private String name; private InputStream is; public ZipFileEntry(String name, InputStream is) { super(); this.name = name; this.is = is; } public String getName() { return name; } public InputStream getIs() { return is; } }
true
b2fa8f02b649671a7da78ab542879bde1d6547f6
Java
PPPPPrerna/Check
/src/test/java/Rest/Action/Amazeee.java
UTF-8
897
1.65625
2
[]
no_license
package Rest.Action; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.testng.annotations.Test; public class Amazeee { @Test public void m1() { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20000000, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("https://www.amazon.in/"); WebElement w1=driver.findElement(By.xpath("//input[@id='twotabsearchtextbox']")); Actions a = new Actions(driver); a.moveToElement(w1).click().sendKeys("Prerna").doubleClick().build().perform(); } }
true
3f2689feae96694389fe269f9210257538f38f05
Java
goeh/grails-crm-core
/src/java/grails/plugins/crm/core/PagedResultList.java
UTF-8
1,593
2.234375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 Goran Ehrsson. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package grails.plugins.crm.core; import java.util.List; import java.util.AbstractList; /** * * @author Goran Ehrsson * @since 0.1 */ public class PagedResultList<E> extends AbstractList<E> { private List<E> resultList; private int totalCount; public PagedResultList(List<E> list, int totalCount) { this.resultList = list; this.totalCount = totalCount; } public PagedResultList(List<E> list) { this.resultList = list; this.totalCount = list.size(); } @Override public E get(int i) { return resultList.get(i); } @Override public E set(int i, E o) { return resultList.set(i, o); } @Override public E remove(int i) { return resultList.remove(i); } @Override public void add(int i, E o) { resultList.add(i, o); } @Override public int size() { return resultList.size(); } public int getTotalCount() { return this.totalCount; } }
true
401c94c90e8e657caf0467eb7055a8406ec79d79
Java
gabrielperalta93/desafioCalidad
/src/main/java/com/gabrielperalta/desafiocalidad/controllers/HotelController.java
UTF-8
2,863
2.390625
2
[]
no_license
package com.gabrielperalta.desafiocalidad.controllers; import com.gabrielperalta.desafiocalidad.dto.HotelPayloadDTO; import com.gabrielperalta.desafiocalidad.dto.StatusCodeDTO; import com.gabrielperalta.desafiocalidad.exceptions.EmptySearchException; import com.gabrielperalta.desafiocalidad.exceptions.IncorrectPlaceException; import com.gabrielperalta.desafiocalidad.exceptions.InvalidDateException; import com.gabrielperalta.desafiocalidad.exceptions.InvalidMailException; import com.gabrielperalta.desafiocalidad.services.HotelService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.text.ParseException; import java.util.Map; @RestController @RequestMapping("api/v1/") public class HotelController { private HotelService hotelService; public HotelController(HotelService hotelService) { this.hotelService = hotelService; } @GetMapping(value = "/hotels") public ResponseEntity getHotels(@RequestParam Map<String, String> requestParams) throws ParseException, InvalidDateException, EmptySearchException, IncorrectPlaceException { return new ResponseEntity(hotelService.getHotels(requestParams), HttpStatus.OK); } @PostMapping("/booking") public ResponseEntity createPayLoad(@RequestBody HotelPayloadDTO payloadDTO) throws Exception { return new ResponseEntity(hotelService.createPayload(payloadDTO), HttpStatus.CREATED); } @ExceptionHandler(EmptySearchException.class) public ResponseEntity handlerSearch(Exception exception){ StatusCodeDTO error = new StatusCodeDTO(); error.setCode(HttpStatus.NOT_FOUND.value()); error.setMessage(exception.getMessage()); return new ResponseEntity(error, HttpStatus.NOT_FOUND); } @ExceptionHandler(InvalidDateException.class) public ResponseEntity handlerInvalidDate(Exception exception){ StatusCodeDTO error = new StatusCodeDTO(); error.setCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(exception.getMessage()); return new ResponseEntity(error, HttpStatus.BAD_REQUEST); } @ExceptionHandler(InvalidMailException.class) public ResponseEntity handlerInvalidMail(Exception exception){ StatusCodeDTO error = new StatusCodeDTO(); error.setCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(exception.getMessage()); return new ResponseEntity(error, HttpStatus.BAD_REQUEST); } @ExceptionHandler(Exception.class) public ResponseEntity handlerException(Exception exception){ StatusCodeDTO error = new StatusCodeDTO(); error.setCode(HttpStatus.BAD_REQUEST.value()); error.setMessage(exception.getMessage()); return new ResponseEntity(error, HttpStatus.BAD_REQUEST); } }
true
52a6cf019c46c507d535bb493413f91ef498b92c
Java
alibaba/GraphScope
/analytical_engine/java/grape-jdk/src/main/java/com/alibaba/graphscope/ds/StringView.java
UTF-8
623
2.125
2
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "FSFAP", "BSD-3-Clause-Clear", "GPL-1.0-or-later", "BSD-2-Clause-Views", "Bitstream-Vera", "MPL-2.0", "LicenseRef-scancode-warranty-disclaimer", "OFL-1.1", "BSD-3-Clause", "APAFML", "0BSD", "LicenseRef-scancode-free-unknown", "CC-BY-4.0", "GPL-3.0-or-later", "LicenseRef-scancode-python-cwi", "Zlib", "Qhull", "u-boot-exception-2.0", "MIT", "ISC", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain", "CC0-1.0", "GPL-2.0-or-later", "BSD-2-Clause", "GCC-exception-3.1", "ZPL-1.1", "CC-BY-SA-4.0", "GPL-3.0-only", "LicenseRef-scancode-other-permissive", "Python-2.0", "X11", "TCL" ]
permissive
package com.alibaba.graphscope.ds; import static com.alibaba.graphscope.utils.CppHeaderName.VINEYARD_ARROW_UTILS_H; import com.alibaba.fastffi.CXXHead; import com.alibaba.fastffi.CXXOperator; import com.alibaba.fastffi.FFIGen; import com.alibaba.fastffi.FFIPointer; import com.alibaba.fastffi.FFIStringProvider; import com.alibaba.fastffi.FFITypeAlias; @FFIGen @CXXHead(VINEYARD_ARROW_UTILS_H) @FFITypeAlias("vineyard::arrow_string_view") public interface StringView extends FFIStringProvider, FFIPointer { long data(); @CXXOperator("[]") byte byteAt(long index); long size(); boolean empty(); }
true
824acc1911f11f97aaf0ad6ec05323ea5aacabac
Java
210712jwa/Reci-Peas_Project2
/src/main/java/com/codekages/dao/ListOfRecipeDAO.java
UTF-8
2,278
2.25
2
[]
no_license
package com.codekages.dao; import java.util.List; import javax.transaction.Transactional; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.codekages.dto.AddListOfRecipeDTO; import com.codekages.dto.IngredientDTO; import com.codekages.dto.ListOfRecipeDTO; import com.codekages.model.Ingredient; import com.codekages.model.ListOfRecipe; import com.codekages.model.Recipe; import com.codekages.model.RecipeList; import com.codekages.model.User; @Repository public class ListOfRecipeDAO { @Autowired private SessionFactory sessionFactory; @Transactional public ListOfRecipe addListOfRecipe(AddListOfRecipeDTO addListOfRecipeDTO, User user) { Session session = sessionFactory.getCurrentSession(); ListOfRecipe newListOfRecipe = new ListOfRecipe(addListOfRecipeDTO.getListOfRecipe(), user); session.persist(newListOfRecipe); return newListOfRecipe; } @Transactional public List<ListOfRecipe> getAllListOfRecipe() { Session session = sessionFactory.getCurrentSession(); List<ListOfRecipe> listofrecipe = session.createQuery("FROM ListOfRecipe").getResultList(); return listofrecipe; } @Transactional public List<ListOfRecipe> getAllListOfRecipeForUser(User user) { Session session = sessionFactory.getCurrentSession(); int id = user.getId(); List<ListOfRecipe> listofrecipe = session.createQuery("Select l FROM ListOfRecipe l Join l.user u WHERE u.id = :userid").setParameter("userid", id).getResultList(); return listofrecipe; } @Transactional public List<RecipeList> getAllRecipesInList(int id) { Session session = sessionFactory.getCurrentSession(); List<RecipeList> recipeList = session.createQuery("Select l.recipe FROM RecipeList l Join l.list r WHERE r.id = :listid").setParameter("listid", id).getResultList(); return recipeList; } @Transactional public RecipeList editListOfRecipe(ListOfRecipe list, Recipe recipe) { Session session = sessionFactory.getCurrentSession(); RecipeList listToAdd = new RecipeList(list, recipe); session.saveOrUpdate(listToAdd); return listToAdd; } }
true
39f165b2f2dfdefdb9b1710673c35011bd30bb5f
Java
mxr1047/NAO-GUI-Framework
/NAOHumanoid2/src/edu/sru/thangiah/nao/vision/CamFrameMouseAdapter.java
UTF-8
1,496
2.828125
3
[]
no_license
package edu.sru.thangiah.nao.vision; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import com.aldebaran.qi.helper.proxies.ALMotion; public class CamFrameMouseAdapter extends MouseAdapter{ private boolean movingHead = false; private int x = 0; private int y = 0; private ALMotion motion; private float widthMod = 0; private float heightMod = 0; public CamFrameMouseAdapter(ALMotion motion, int width, int height){ this.motion = motion; widthMod = width/2; heightMod = height/2; } @Override public void mouseExited(MouseEvent e) { movingHead = false; } @Override public void mousePressed(MouseEvent e) { movingHead = true; try { motion.setStiffnesses("Head", 1.0); } catch (Exception e1) { e1.printStackTrace(); } new Thread(new HeadMove()).start(); } public void mouseDragged(MouseEvent e){ x = e.getX(); y = e.getY(); } @Override public void mouseReleased(MouseEvent e) { movingHead = false; } private class HeadMove implements Runnable{ float yaw = 0; // -2.0857 - 2.0857 float pitch = 0; // -.6720 - .5149 @Override public void run() { while(movingHead){ yaw = -((float)x - widthMod)/500; pitch = ((float)y - heightMod)/500; try { motion.changeAngles("HeadYaw", yaw, .1f); motion.changeAngles("HeadPitch", pitch, .1f); Thread.sleep(50); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
true
649be3c7afb9a9609012fe3e8da5d231dc0fdda8
Java
PERES-Richard/APB-and-Parcoursup
/commons/src/main/java/commons/parser/ParserFile.java
UTF-8
9,198
3.046875
3
[]
no_license
package commons.parser; import commons.entity.School; import commons.entity.Student; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * @author Damien Montoya */ public class ParserFile { protected final List<School> schools; protected final List<Student> students; private final String inputFile; protected int numberStudents; protected int numberSchools; protected int numberStudentChoices; public ParserFile(String inputFile) { schools = new ArrayList<>(); students = new ArrayList<>(); this.inputFile = inputFile; } /** * The method will launch readStudent or readSchool by reading all lines in the file */ public void parse() { try { BufferedReader buff = new BufferedReader( new InputStreamReader( new FileInputStream(inputFile))); int lineNumber = 0; int studentIdNew = 0; int schoolIdNew = 0; String line; List<List<Integer>> schoolsChoicesOfStudents = new ArrayList<>(); //on en peux pas attribuer a la création les écoles aux éleves //car les écoles sont créer apres, on stock donc les id des écoles que l'on remplis apres while ((line = buff.readLine()) != null) { if (lineNumber == 0) readFirstLine(line); else if (lineNumber < numberStudents + 1) { readStudent(schoolsChoicesOfStudents, line, studentIdNew); studentIdNew++; } else if (lineNumber < numberSchools + numberStudents + 1) { readSchool(line, schoolIdNew); schoolIdNew++; } lineNumber++; } addStudentWish(schoolsChoicesOfStudents); if (numberStudents != students.size()) { System.out.println("Il n'y a pas autant d'eleves que prévu"); System.exit(1); } if (numberSchools != schools.size()) { System.err.println("Il n'y a pas autant d'écoles que prévu"); System.exit(1); } if (lineNumber > numberSchools + numberStudents + 1) { System.err.println("Il y a plus de lignes dans le fichier qu'il faut"); System.exit(1); } for (School school : schools) { for (Student studentId : school.getPrioryStutends()) { if (studentId.getId() > students.size() || studentId.getId() < 0) { System.err.println("un eleve n'existe pas"); System.exit(1); } } } for (Student student : students) { for (School schooldId : student.getPrioritySchools()) { if (schooldId.getId() > schools.size() || schooldId.getId() < 0) { System.err.println("Un élève se trouve dans une école qui n'existe pas"); System.exit(1); } } } for (School school : schools) { for (Student studentId : school.getPrioryStutends()) { if (studentId.getId() > students.size() || studentId.getId() < 0) { System.err.println("Une école a pris un élève qui n'existe pas"); System.exit(1); } } } buff.close(); } catch (IOException e) { e.printStackTrace(); System.exit(2); } } /** * To parse the first line of the file, containing the number of students, the number of schools and the number of students choices * * @param line the line to inspect */ protected void readFirstLine(String line) { String[] numbers = line.split("[ ]+"); if (numbers.length > 3) { System.err.println("la premiere ligne ne contient pas de nombre ou que les indices sont faux -> bad input file"); System.exit(1); } try { numberStudents = Integer.parseInt(numbers[0]); numberSchools = Integer.parseInt(numbers[1]); numberStudentChoices = Integer.parseInt(numbers[2]); } catch (NumberFormatException | IndexOutOfBoundsException e) { System.err.println("la premiere ligne ne contient pas de nombre ou que les indices sont faux -> bad input file"); System.exit(1); } } /** * To build a student * * @param student the line to analyse * @param id the id that student will have */ protected void readStudent(List<List<Integer>> schoolsChoicesOfStudents, String student, int id) { String[] studentSplitted = student.split("[ ]+"); List<Integer> theChoicesOfTheStudent = new ArrayList<>(); if (studentSplitted.length > 5 + numberStudentChoices) { System.err.println("Les élèves ont mis plus de choix que prévu"); System.exit(1); } stockStudentsSchoolsChoices(theChoicesOfTheStudent, studentSplitted, 5); schoolsChoicesOfStudents.add(theChoicesOfTheStudent); students.add(new Student(id)); } /** * Pour stocker les id des écoles que l'éleve veux pour les associer après aux écoles * * @param theChoicesOfTheStudent les id des écoles * @param lineSplitted la ligne contenant les informations de l'éleve * @param offset le nombre d'informations que contient un eleve et ou commencerà récuperer ses choix */ protected void stockStudentsSchoolsChoices(List<Integer> theChoicesOfTheStudent, String[] lineSplitted, int offset) { for (int i = 0; i < numberStudentChoices; i++) { //si la premiere ligne ne contient pas de nombre ou que les indices sont faux -> bad input file try { theChoicesOfTheStudent.add(Integer.parseInt(lineSplitted[offset + i])); } catch (NumberFormatException | IndexOutOfBoundsException e) { System.err.println("Un élève n'est pas bon"); e.printStackTrace(); System.exit(1); } } } /** * Add to the list the wish of the student * * @param schoolsChoosen the list that contain the id of the school */ private void addStudentWish(List<List<Integer>> schoolsChoosen) { for (int i = 0; i < schoolsChoosen.size(); i++) { List<School> schoolsOfTheStudent = new ArrayList<>(); for (int j = 0; j < schoolsChoosen.get(i).size(); j++) { schoolsOfTheStudent.add(schools.get(schoolsChoosen.get(i).get(j))); } students.get(i).setPrioritySchools(schoolsOfTheStudent); } } /** * To build a school * * @param school the line to analyse * @param id the id of the school */ protected void readSchool(String school, int id) { String[] studentSplitted = school.split("[ ]+"); int capacityOfSchool = Integer.parseInt(studentSplitted[1]); List<Student> studentsChoosen = new ArrayList<>(); int numberTheyChoose = Integer.parseInt(studentSplitted[3]); if (studentSplitted.length > 4 + numberTheyChoose) { System.err.println("L'ecole n'a pas le bon nombre d'élèves qu'il veulent"); System.exit(1); } addSchoolWish(studentsChoosen, studentSplitted, 4, numberTheyChoose); schools.add(new School(id, capacityOfSchool, studentsChoosen)); } /** * Add the rank of the students they want to take * * @param studentsChoosen the list to add students id * @param studentSplitted the line to analyse * @param offset the offeset to begin * ex : CPGE_Lycée_Bellevue 1 Toulouse 5 2 9 1 7 4 * -> offset est 4 car la liste des souhaits commence au 2 * @param numberTheyChoose the number of student they take */ protected void addSchoolWish(List<Student> studentsChoosen, String[] studentSplitted, int offset, int numberTheyChoose) { for (int i = 0; i < numberTheyChoose; i++) { //si la premiere ligne ne contient pas de nombre ou que les indices sont faux -> bad input file try { studentsChoosen.add(students.get(Integer.parseInt(studentSplitted[offset + i]))); } catch (NumberFormatException | IndexOutOfBoundsException e) { e.printStackTrace(); System.exit(1); } } } public List<School> getSchools() { return schools; } public List<Student> getStudents() { return students; } public String getInputFile() { return inputFile; } }
true
ac3c41661cf497474bb67a73d23f6f211c4dc354
Java
KingJA/RentManager
/app/src/main/java/com/kingja/cardpackage/util/VerifyCode.java
UTF-8
1,327
2.375
2
[]
no_license
package com.kingja.cardpackage.util; import android.util.Log; import com.tdr.wisdome.util.CRC16M; /** * Description:校验码 * Create Time:2016/9/1 15:22 * Author:KingJA * Email:kingjavip@gmail.com */ public class VerifyCode { private static final String TAG = "VerifyCode"; public static String checkDeviceCode(String base) { byte[] b = TendencyEncrypt.decode(base.getBytes()); if (b.length != 8) { return ""; } byte[] c = new byte[6]; for (int i = 0; i < c.length; i++) { c[i] = b[i]; } Log.i(TAG, "base" + TendencyEncrypt.bytesToHexString(b)); Log.i(TAG, "key" + TendencyEncrypt.bytesToHexString(c)); String key = TendencyEncrypt.encode(c); short sh = CRC16M.CalculateCrc16(key.getBytes()); byte d = (byte) (0xff & sh); Log.i(TAG, "d: " + TendencyEncrypt.bytesToHexString(new byte[]{d})); byte g = (byte) (0xff & sh >> 8); Log.i(TAG, "g: " + TendencyEncrypt.bytesToHexString(new byte[]{g})); if (d == b[6] && g == b[7]) { byte[] h = TendencyEncrypt.decode(key.getBytes()); key = TendencyEncrypt.bytesToHexString(h); Log.e("good", key); return key.toUpperCase(); } else { return ""; } } }
true
bccb381ea731b09b6798b04bdf6eeb5ce0dad614
Java
shawbirendra/Design-Patterns
/DesignPatterns/src/com/training/servicelocator/InitialContext.java
UTF-8
420
2.53125
3
[]
no_license
package com.training.servicelocator; //work for any service public class InitialContext { public Object lookup(String jndiName) { if (jndiName.equalsIgnoreCase("db")) { System.out.println("Looking for DB service and crearting"); return new DBService(); } if (jndiName.equalsIgnoreCase("erp")) { System.out.println("Looking for ERP service and create"); return new ERPService(); } return null; } }
true
f8fbeace856e05d28f148346479f1dfa2bc26298
Java
jdb2modi/Android-Workspace
/StudInfoPro/src/com/zaptech/studinfopro/UpdateCollegeActivity.java
UTF-8
3,647
2.203125
2
[]
no_license
package com.zaptech.studinfopro; import java.util.ArrayList; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; public class UpdateCollegeActivity extends Activity implements OnClickListener { EditText edClgName, edClgUniversity; Button btnUpdateNow, btnCancel; DBHelper dbHelper; Spinner spinClgId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.update_college); init(); loadSpinData(); // setEditText(); } public void init() { edClgName = (EditText) findViewById(R.id.edCollegeNameToUpdate); edClgUniversity = (EditText) findViewById(R.id.edCollegeUniversityToUpdate); btnUpdateNow = (Button) findViewById(R.id.btnUpdateCollegeNow); btnCancel = (Button) findViewById(R.id.btnUpdateCancel); dbHelper = new DBHelper(this); spinClgId = (Spinner) findViewById(R.id.spinCollegeNameToUpdate); // Adding Listeners btnUpdateNow.setOnClickListener(this); btnCancel.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnUpdateCollegeNow: dbHelper.updateCollegeData(Integer.parseInt(spinClgId .getSelectedItem().toString()), edClgName.getText() .toString(), edClgUniversity.getText().toString()); Toast.makeText(UpdateCollegeActivity.this, getResources().getString(R.string.toastUpdateSuccessful), Toast.LENGTH_SHORT).show(); break; case R.id.btnUpdateCancel: clear(); break; default: break; } } public void loadSpinData() { String sqlLoadData = "SELECT * FROM tbCollege"; ArrayList<String> loadClgIds = new ArrayList<String>(); Cursor selectCursor = dbHelper.getDB().rawQuery(sqlLoadData, null); if (selectCursor != null) { if (selectCursor.moveToFirst()) { do { loadClgIds.add(selectCursor.getString(selectCursor .getColumnIndex("CollegeId"))); } while (selectCursor.moveToNext()); } } ArrayAdapter<String> adpt = new ArrayAdapter<String>( UpdateCollegeActivity.this, android.R.layout.simple_dropdown_item_1line, loadClgIds); spinClgId.setAdapter(adpt); } public void setEditText() { spinClgId.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { String sqlLoadData = "SELECT * FROM tbCollege where CollegeId=" + spinClgId.getSelectedItem().toString(); Cursor selectCursor = dbHelper.getDB().rawQuery(sqlLoadData, null); edClgName.setText(selectCursor.getString(selectCursor .getColumnIndex(DBHelper.COL_CLGNAME))); edClgUniversity.setText(selectCursor.getString(selectCursor .getColumnIndex(DBHelper.COL_ClGUNIVERSITY))); Log.d("CLGNAME===========================>", selectCursor .getString(selectCursor .getColumnIndex(DBHelper.COL_CLGNAME))); Log.d("CLGUNIVERSITY========================>", selectCursor .getString(selectCursor .getColumnIndex(DBHelper.COL_ClGUNIVERSITY))); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); } public void clear() { edClgName.setText(""); edClgUniversity.setText(""); } }
true
1b840eb86a58c7db7f97a0a3a7e75dfee499abbd
Java
peterkwan/Udacity-Android-PopularMovies-Stage2
/app/src/main/java/org/peterkwan/udacity/popularmovies/MovieTrailerListAsyncTaskLoader.java
UTF-8
5,390
2.234375
2
[]
no_license
package org.peterkwan.udacity.popularmovies; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.AsyncTaskLoader; import android.util.Log; import org.json.JSONException; import org.peterkwan.udacity.popularmovies.data.MovieTrailer; import org.peterkwan.udacity.popularmovies.provider.MovieContract.MovieTrailerEntry; import org.peterkwan.udacity.popularmovies.utils.JsonUtils; import org.peterkwan.udacity.popularmovies.utils.NetworkUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MovieTrailerListAsyncTaskLoader extends AsyncTaskLoader<List<MovieTrailer>> { private static final String LOG_TAG = MovieTrailerListAsyncTaskLoader.class.getSimpleName(); private static final String MOVIE_ID = "movieId"; private List<MovieTrailer> trailerList; private final Bundle loaderArgs; private final ContentResolver resolver; public MovieTrailerListAsyncTaskLoader(Context context, Bundle args) { super(context); loaderArgs = args; resolver = context.getContentResolver(); } @Override protected void onStartLoading() { super.onStartLoading(); if (trailerList != null) deliverResult(trailerList); else forceLoad(); } @Nullable @Override public List<MovieTrailer> loadInBackground() { if (loaderArgs == null || !loaderArgs.containsKey(MOVIE_ID)) return null; String movieId = loaderArgs.getString(MOVIE_ID); if (NetworkUtils.isNetworkDisconnected(getContext())) return retrieveTrailerDataFromDatabase(movieId); try { String resultJson = NetworkUtils.retrieveMovieTrailerListFromTMdb(loaderArgs.getString(MOVIE_ID)); List<MovieTrailer> trailerList = JsonUtils.constructMovieTrailerListFromJson(resultJson); updateTrailerListInDatabase(movieId, trailerList); return trailerList; } catch (IOException e) { Log.e(LOG_TAG, "Error loading data from network", e); return retrieveTrailerDataFromDatabase(movieId); } catch (JSONException e) { Log.e(LOG_TAG, "Error parsing data from network", e); return null; } } @Override public void deliverResult(@Nullable List<MovieTrailer> data) { trailerList = data; super.deliverResult(data); } private List<MovieTrailer> retrieveTrailerDataFromDatabase(String movieId) { List<MovieTrailer> trailerList = null; if (resolver != null && movieId != null) { Cursor cursor = resolver.query( MovieTrailerEntry.CONTENT_URI, null, null, new String[] { movieId }, null); if (cursor != null) { if (cursor.getCount() > 0) { trailerList = new ArrayList<>(); cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { MovieTrailer trailer = MovieTrailer.builder() .id(cursor.getLong(cursor.getColumnIndex(MovieTrailerEntry.COLUMN_MOVIE_ID))) .type(cursor.getString(cursor.getColumnIndex(MovieTrailerEntry.COLUMN_TYPE))) .name(cursor.getString(cursor.getColumnIndex(MovieTrailerEntry.COLUMN_NAME))) .videoUrl(cursor.getString(cursor.getColumnIndex(MovieTrailerEntry.COLUMN_VIDEO_URL))) .imageUrl(cursor.getString(cursor.getColumnIndex(MovieTrailerEntry.COLUMN_THUMBNAIL_URL))) .build(); trailerList.add(trailer); cursor.moveToNext(); } } cursor.close(); } } return trailerList; } private void updateTrailerListInDatabase(String movieId, List<MovieTrailer> trailerList) { if (resolver != null && movieId != null) { resolver.delete(MovieTrailerEntry.CONTENT_URI, null, new String[] { movieId }); if (trailerList != null) { List<ContentValues> contentValueList = new ArrayList<>(); for (MovieTrailer trailer : trailerList) contentValueList.add(constructContentValues(trailer)); resolver.bulkInsert(MovieTrailerEntry.CONTENT_URI, contentValueList.toArray(new ContentValues[0])); } } } private ContentValues constructContentValues(MovieTrailer trailer) { ContentValues values = new ContentValues(); values.put(MovieTrailerEntry.COLUMN_MOVIE_ID, trailer.getId()); values.put(MovieTrailerEntry.COLUMN_TYPE, trailer.getType()); values.put(MovieTrailerEntry.COLUMN_NAME, trailer.getName()); values.put(MovieTrailerEntry.COLUMN_VIDEO_URL, trailer.getVideoUrl()); values.put(MovieTrailerEntry.COLUMN_THUMBNAIL_URL, trailer.getImageUrl()); return values; } }
true
e2552714115d416ba3d57c7c07c125cb40a23e5d
Java
obelisk0114/LeetCode
/src/OJ0131_0140/Single_Number.java
UTF-8
1,113
3.640625
4
[]
no_license
package OJ0131_0140; import java.util.Map; import java.util.HashMap; public class Single_Number { /* * https://en.wikipedia.org/wiki/Exclusive_or * a ^ b = b ^ a * a ^ (b ^ c) = (a ^ b) ^ c * a ^ 0 = a * a ^ a = 0 * a ^ b ^ b = a ^ 0 = a * * Rf : * https://discuss.leetcode.com/topic/47560/xor-java-solution * https://discuss.leetcode.com/topic/41157/my-java-solution-in-o-n-time-complexity-and-o-1-space-complexity-using-xor/2 */ int singleNumber(int[] nums) { int out = nums[0]; for (int i = 1; i < nums.length; i++) { out ^= nums[i]; } return out; } // space complexity : O(n) int singleNumber_map(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i])) { map.put(nums[i], 2); } else { map.put(nums[i], 1); } } for (Integer key : map.keySet()) { if (map.get(key) == 1) { return key; } } return -1; } }
true
80aa93327068e1a71f8cb6d4f10ffb44a4f13934
Java
DrPrimus/korzun
/src/main/java/Headphones/JsonDecodeDemo.java
UTF-8
1,413
2.59375
3
[]
no_license
package headphones; import org.codehaus.jackson.map.ObjectMapper; import org.json.JSONException; import org.json.JSONObject; import java.io.FileWriter; import java.io.IOException; class JsonDecodeDemo { public static void main(String[] args) throws JSONException { Headphones panasonik = new Headphones(); panasonik.setSize(12); panasonik.setColor("черный"); ObjectMapper mapper = new ObjectMapper(); JSONObject obj = new JSONObject(); obj.put("Size",panasonik.getSize()); obj.put("Color",panasonik.getColor()); //obj.put("Volume",panasonik.volume); obj.put("num", new String("Panasonik")); obj.put("model", new Integer(123212)); obj.put("turnon", new Boolean(true)); try (FileWriter file = new FileWriter("C:\\Users\\Vova\\korzun\\src\\main\\resources\\headphones\\test.json")) { file.write(obj.toString()); file.flush(); } catch (IOException e) { e.printStackTrace(); } /*System.out.print(obj); obj.put("name", "headphones"); obj.put("num", new String("Panasonik")); obj.put("model", new Integer(123212)); obj.put("turnon", new Boolean(true)); StringWriter out = new StringWriter(); obj.write(out); String jsonText = out.toString(); System.out.print(jsonText); */ } }
true
a23d77f7d19714ad43470889cc681cf5e2d86125
Java
tsuzcx/qq_apk
/com.tencent.mm/classes.jar/com/tencent/mm/compatible/util/r.java
UTF-8
4,876
1.898438
2
[]
no_license
package com.tencent.mm.compatible.util; import com.tencent.matrix.trace.core.AppMethodBeat; import java.io.CharArrayWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.security.AccessController; import java.util.BitSet; public final class r { static BitSet lZj; static String lZk; static { AppMethodBeat.i(155915); lZk = null; lZj = new BitSet(256); int i = 97; while (i <= 122) { lZj.set(i); i += 1; } i = 65; while (i <= 90) { lZj.set(i); i += 1; } i = 48; while (i <= 57) { lZj.set(i); i += 1; } lZj.set(45); lZj.set(95); lZj.set(46); lZj.set(42); lZk = (String)AccessController.doPrivileged(new i("file.encoding")); AppMethodBeat.o(155915); } public static String as(String paramString1, String paramString2) { AppMethodBeat.i(155914); StringBuffer localStringBuffer = new StringBuffer(paramString1.length()); CharArrayWriter localCharArrayWriter = new CharArrayWriter(); if (paramString2 == null) { paramString1 = new NullPointerException("charsetName"); AppMethodBeat.o(155914); throw paramString1; } int j; for (;;) { Charset localCharset; int k; try { localCharset = Charset.forName(paramString2); j = 0; i = 0; if (i >= paramString1.length()) { break; } k = paramString1.charAt(i); if (lZj.get(k)) { if (k == 32) { j = 1; } localStringBuffer.append((char)k); i += 1; continue; } j = k; } catch (IllegalCharsetNameException paramString1) { paramString1 = new UnsupportedEncodingException(paramString2); AppMethodBeat.o(155914); throw paramString1; } catch (UnsupportedCharsetException paramString1) { paramString1 = new UnsupportedEncodingException(paramString2); AppMethodBeat.o(155914); throw paramString1; } int m; do { localCharArrayWriter.write(j); k = i; if (j >= 55296) { k = i; if (j <= 56319) { k = i; if (i + 1 < paramString1.length()) { j = paramString1.charAt(i + 1); k = i; if (j >= 56320) { k = i; if (j <= 57343) { localCharArrayWriter.write(j); k = i + 1; } } } } } k += 1; if (k >= paramString1.length()) { break; } paramString2 = lZj; m = paramString1.charAt(k); j = m; i = k; } while (!paramString2.get(m)); localCharArrayWriter.flush(); String str = new String(localCharArrayWriter.toCharArray()); new q(); byte[] arrayOfByte = str.getBytes(localCharset); paramString2 = arrayOfByte; if (arrayOfByte == null) { paramString2 = str.getBytes(); } int i = 0; while (i < paramString2.length) { localStringBuffer.append('%'); char c2 = Character.forDigit(paramString2[i] >> 4 & 0xF, 16); char c1 = c2; if (Character.isLetter(c2)) { c1 = (char)(c2 - ' '); } localStringBuffer.append(c1); c2 = Character.forDigit(paramString2[i] & 0xF, 16); c1 = c2; if (Character.isLetter(c2)) { c1 = (char)(c2 - ' '); } localStringBuffer.append(c1); i += 1; } localCharArrayWriter.reset(); j = 1; i = k; } if (j != 0) { paramString1 = localStringBuffer.toString(); AppMethodBeat.o(155914); return paramString1; } AppMethodBeat.o(155914); return paramString1; } @Deprecated public static String cg(String paramString) { AppMethodBeat.i(155913); Object localObject = null; try { paramString = as(paramString, lZk); AppMethodBeat.o(155913); return paramString; } catch (UnsupportedEncodingException paramString) { for (;;) { paramString = localObject; } } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes7.jar * Qualified Name: com.tencent.mm.compatible.util.r * JD-Core Version: 0.7.0.1 */
true
1dbb36fbba9dc72ff355b69fa7442c4848143458
Java
ethayu/USACO-Practice
/Silver_Practice/src/Contiguous_Sequence.java
UTF-8
1,247
3.375
3
[]
no_license
import java.util.*; public class Contiguous_Sequence { static boolean check (int[] temp, int[] b) { for (int i = 0; i < b.length - temp.length; i++) { int[] a = Arrays.copyOfRange(b, i, i + temp.length); for (int j = 0; j < temp.length; j++) { if (temp[j] != a[j]) break; if (j == temp.length - 1) return true; } } return false; } public static void main( String [] args) { Scanner sc = new Scanner ( System.in); int x = sc.nextInt(); int y = sc.nextInt(); int[] a = new int[x]; int[] b = new int[y]; for (int i = 0; i < x; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < y; i++) { b[i] = sc.nextInt(); } int sizeoftemp = 0; for (int i = 0; i < a.length; i++) { for (int j = a.length - 1; j > i; j--) { if ((j - i) < sizeoftemp) break; int[] temp = Arrays.copyOfRange(a, i, j); if (check(temp, b)) { sizeoftemp = temp.length; break; }; } } System.out.println(sizeoftemp); } }
true
1fbe52a2e522d4bfc4f33dcdbbc7f0dec2967840
Java
Gingigo/lz
/algorithm/src/main/java/leetcode/leetcode/editor/cn/_104_MaximumDepthOfBinaryTree.java
UTF-8
843
3.171875
3
[]
no_license
package leetcode.leetcode.editor.cn; //给定一个二叉树,找出其最大深度。 // // 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 // // 说明: 叶子节点是指没有子节点的节点。 // // 示例: //给定二叉树 [3,9,20,null,null,15,7], // // 3 // / \ // 9 20 // / \ // 15 7 // // 返回它的最大深度 3 。 // Related Topics 树 深度优先搜索 递归 // 👍 851 👎 0 //_104_MaximumDepthOfBinaryTree //leetcode submit region begin(Prohibit modification and deletion) class _104_MaximumDepthOfBinaryTree { public int maxDepth(TreeNode root) { if(root==null){ return 0; } return 1+Math.max(maxDepth(root.left),maxDepth(root.right)); } } //leetcode submit region end(Prohibit modification and deletion)
true
a27f8ce2f5309842d927673ecd7cee023bc87087
Java
tlchun/FutureHome
/module-sign/src/main/java/com/goldze/sign/model/MqttModel.java
UTF-8
1,769
2.375
2
[ "Apache-2.0" ]
permissive
package com.goldze.sign.model; import java.io.Serializable; public class MqttModel implements Serializable { private int id; private String username; private String password; private String showPassword; private String salt; private boolean isSuperuser; private boolean created; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getShowPassword() { return showPassword; } public void setShowPassword(String showPassword) { this.showPassword = showPassword; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public boolean isSuperuser() { return isSuperuser; } public void setSuperuser(boolean superuser) { isSuperuser = superuser; } public boolean isCreated() { return created; } public void setCreated(boolean created) { this.created = created; } @Override public String toString() { return "MqttModel{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", showPassword='" + showPassword + '\'' + ", salt='" + salt + '\'' + ", isSuperuser=" + isSuperuser + ", created=" + created + '}'; } }
true
436f6665c70d1c33182b38ac7d6a53ea0cce8e2c
Java
google/closure-compiler
/src/com/google/javascript/jscomp/Es6RewriteBlockScopedFunctionDeclaration.java
UTF-8
3,409
2.203125
2
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "GPL-1.0-or-later", "MIT", "CPL-1.0", "NPL-1.1", "MPL-1.1" ]
permissive
/* * Copyright 2017 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.jscomp.parsing.parser.FeatureSet; import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; /** * Rewrite block-scoped function declarations as "let"s. This pass must happen before * Es6RewriteBlockScopedDeclaration, which rewrites "let" to "var". */ public final class Es6RewriteBlockScopedFunctionDeclaration extends AbstractPostOrderCallback implements CompilerPass { private final AbstractCompiler compiler; private static final FeatureSet transpiledFeatures = FeatureSet.BARE_MINIMUM.with(Feature.BLOCK_SCOPED_FUNCTION_DECLARATION); public Es6RewriteBlockScopedFunctionDeclaration(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { TranspilationPasses.processTranspile(compiler, root, transpiledFeatures, this); TranspilationPasses.maybeMarkFeaturesAsTranspiledAway(compiler, root, transpiledFeatures); } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isFunction() && parent != null && parent.isBlock() && !parent.getParent().isFunction()) { // Only consider declarations (all expressions have non-block parents) that are not directly // within a function or top-level. visitBlockScopedFunctionDeclaration(t, n, parent); } } /** * Rewrite the function declaration from: * * <pre> * function f() {} * FUNCTION * NAME x * PARAM_LIST * BLOCK * </pre> * * to * * <pre> * let f = function() {}; * LET * NAME f * FUNCTION * NAME (w/ empty string) * PARAM_LIST * BLOCK * </pre> * * This is similar to {@link Normalize.NormalizeStatements#rewriteFunctionDeclaration} but * rewrites to "let" instead of "var". */ private void visitBlockScopedFunctionDeclaration(NodeTraversal t, Node n, Node parent) { // Prepare a spot for the function. Node oldNameNode = n.getFirstChild(); Node fnNameNode = oldNameNode.cloneNode(); Node let = IR.declaration(fnNameNode, Token.LET).srcref(n); NodeUtil.addFeatureToScript(t.getCurrentScript(), Feature.LET_DECLARATIONS, compiler); // Prepare the function. oldNameNode.setString(""); compiler.reportChangeToEnclosingScope(oldNameNode); // Move the function to the front of the parent. n.detach(); parent.addChildToFront(let); compiler.reportChangeToEnclosingScope(let); fnNameNode.addChildToFront(n); } }
true
b399cd97fdff5253f72adf729552ff8cf72639a6
Java
igormelao/doctor-labelling-service
/src/main/java/com/doctorlabel/service/LabelProxy.java
UTF-8
1,055
2.375
2
[]
no_license
package com.doctorlabel.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import com.doctorlabel.model.Label; /** * * Interface class responsible to comunicate with a third service DoctorLabel Label service application. * * Configurations: * * <ol> * <li>name = This is the name of the service that will be call</li> * <li>url = This is the url resource that we will connect to retrieve data</li> * </ol> * @author Igor Melão (igormelao@gmail.com) * @Date: 14-03-2021 * @since 0.0.1-SNAPSHOT */ @FeignClient(name="doctor-label-service", url="localhost:8080") public interface LabelProxy { /** * <p>This is a resource to return Label informations by your ID accessing a third party application</p> * * @author Igor Melão (igormelao@gmail.com) * @param * @return Label @see(com.doctorlabel.model.Label) * @since 0.0.1-SNAPSHOT */ @GetMapping("/labels/{id}") public Label retrieveLabel(@PathVariable String id); }
true
c9b8ab19533f1e0187c0673be1856ad7fb355aac
Java
ruanbaojun1105/BabySave
/src/me/hibb/mybaby/android/openIM/NotifacationListMerge.java
UTF-8
14,512
1.703125
2
[]
no_license
package me.hibb.mybaby.android.openIM; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.alibaba.mobileim.contact.IYWContact; import com.alibaba.mobileim.conversation.IYWConversationService; import com.alibaba.mobileim.conversation.YWConversation; import com.alibaba.mobileim.conversation.YWConversationType; import com.alibaba.mobileim.conversation.YWP2PConversationBody; import com.alibaba.mobileim.conversation.YWTribeConversationBody; import com.alibaba.mobileim.gingko.model.tribe.YWTribe; import com.alibaba.mobileim.kit.common.IMUtility; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import mybaby.Constants; import mybaby.action.Action; import mybaby.action.P2PChattingAction; import mybaby.action.TribeChattingAciton; import mybaby.action.TribeSpaceAction; import mybaby.action.TribeSystemManagerAction; import mybaby.cache.CacheDataTask; import mybaby.models.notification.NotificationCategory; import mybaby.models.notification.TribeNotificationCategory; import mybaby.ui.AppConfig; import mybaby.ui.MyBabyApp; import mybaby.ui.Notification.adapter.SortNotificationList; import mybaby.ui.main.MyBayMainActivity; import mybaby.util.ImageHelper; /** * Created by bj */ public class NotifacationListMerge { private static NotifacationListMerge merge; public static NotifacationListMerge getInstance() { if (merge == null) merge = new NotifacationListMerge(); return merge; } /** * 删除是从会话转为NotificationCategory的列表项 */ public List<NotificationCategory> delConversationList(List<NotificationCategory> itemList) { if (itemList!=null&&itemList.size()>0) { Iterator ite=itemList.iterator(); while(ite.hasNext()){ NotificationCategory category= (NotificationCategory) ite.next(); if (category.getKey().equals(Constants.Conversation_Key)) { ite.remove(); } } } return itemList; } /** * 保存缓存并排序 * @param itemList * @return */ public List<NotificationCategory> saveNotificationCategoryList(Context context,List<NotificationCategory> itemList) { if (itemList!= null && itemList.size() > 0) { CacheDataTask.putCache(context,itemList.toArray(),Constants.CacheKey_CommunityActivity_NotificationCategory,true); } return itemList; } /** * 获得最新转换会话后的NotificationCategory的列表项 */ public List<NotificationCategory> getNtcLatestList(Context context,List<YWConversation> list,List<NotificationCategory> newCategoryList) { List<NotificationCategory> itemList=new ArrayList<>(); /*if (newCategoryList != null && newCategoryList.size() > 0) { for (NotificationCategory category:newCategoryList) itemList.add(category); }*/ if (newCategoryList != null) itemList.addAll(newCategoryList);//方便拓展 if (MyBabyApp.getSharedPreferences().getBoolean("tribeHasInvite",false)){ String title=MyBabyApp.getSharedPreferences().getString("tribeTitle", "群系统消息"); String url=MyBabyApp.getSharedPreferences().getString("tribeUrl", ""); long time=MyBabyApp.getSharedPreferences().getLong("tribeTime", System.currentTimeMillis()); String content=MyBabyApp.getSharedPreferences().getString("tribeContent", "有新消息"); int tribeUnreadNum=MyBabyApp.getSharedPreferences().getInt("tribeUnreadNum",0); Boolean has = false;//有则更新无则加 NotificationCategory sysCategory=newNifcForTribeManager(url, title, content, time, tribeUnreadNum); for (int i = 0; i < itemList.size(); i++) { if (itemList.get(i).getKey().equals(Constants.ConversationManager_Key)) { itemList.set(i,sysCategory); has=true; break; } } if (!has) itemList.add(sysCategory); } //本地服务器 List<NotificationCategory> spaceNtfcList=new ArrayList<>(); Object[] categories= CacheDataTask.getObjs(context, Constants.CacheKey_NotificationCategory_Self); if (categories != null && categories.length > 0) { for (Object categorie:categories) { NotificationCategory category= (NotificationCategory) categorie; if (category.getAction().contains(TribeSpaceAction.TribeSpaceAction)) spaceNtfcList.add(category); else itemList.add(category); } } //List<NotificationCategory> itemList2=delConversationList(itemList); //云旺 if (list != null && list.size() > 0) { for (YWConversation conversation:list) { NotificationCategory category=converToNotica(conversation,spaceNtfcList); if (!TextUtils.isEmpty(category.getTitle())) itemList.add(category); } } itemList=saveNotificationCategoryList(context,itemList); Collections.sort(itemList, new SortNotificationList()); return itemList; } /** * 處理數據 :合併數組並且排序 * @param * @return */ public static List<NotificationCategory> getNtcList(Context context) { List<NotificationCategory> itemList=new ArrayList<>(); Object[] categories= CacheDataTask.getObjs(context, Constants.CacheKey_CommunityActivity_NotificationCategory); if (categories != null && categories.length > 0) { for (Object item:categories){ NotificationCategory castItem= (NotificationCategory) item; boolean isHas=false; for (NotificationCategory itme:itemList){ if (itme.getTribe_id()!=0&&itme.getTribe_id()==castItem.getTribe_id()){ isHas=true; break; } } if (isHas) continue; else itemList.add(castItem); } Log.e("服务器消息列表缓存数据num", categories.length + ""); } Collections.sort(itemList, new SortNotificationList()); return itemList; } /** * 新建一个群系统消息会话 * @param ImageUrl * @param title * @param content * @param time * @return */ public static NotificationCategory newNifcForTribeManager(String ImageUrl,String title,String content,long time,int unread) { NotificationCategory category=new NotificationCategory(); category.setAction(Action.newActionLink(null, TribeSystemManagerAction.actionUrl)); category.setImageUrl(ImageUrl); category.setTitle(title);//"群系统消息" category.setKey(Constants.ConversationManager_Key); category.setNewestDatetime_gmt(time); category.setUnreadCount(unread); category.setNewestDesc(content);//"你有新的群邀请" category.setStrongRemind(true);//是强提醒 有数字是强提醒1,红点是弱提醒-1 return category; } public NotificationCategory converToNotica(YWConversation conversation,List<NotificationCategory> spaceNtfcList) { NotificationCategory category=new NotificationCategory(); category.setKey(Constants.Conversation_Key); category.setNewestDatetime_gmt(conversation.getLatestTimeInMillisecond());//或者conversation.getLatestTime()*1000 category.setUnreadCount(conversation.getUnreadCount()); //String time1 = IMUtil.getFormatTime(conversation.getLatestTime() * 1000L, WXAPI.getInstance().getServerTime()); // 获取会话管理类 if (conversation.getConversationType()== YWConversationType.Tribe) { YWTribeConversationBody body= (YWTribeConversationBody) conversation.getConversationBody(); YWTribe tribe=body.getTribe(); IYWContact ywContact = IMUtility.getContactProfileInfo(conversation.getLatestMessageAuthorId(), conversation.getLatestMessageAuthorAppKey()); String [][] aa={{"im_tribeid",tribe.getTribeId()+""},{"tribe_name", tribe.getTribeName()}}; category.setTribe_id(tribe.getTribeId()); category.setAction(Action.newActionLink(aa, TribeChattingAciton.TribeChattingAciton)); category.setImageUrl(TribeHelper.getTribeIconUrl(tribe.getTribeId())); category.setTitle(tribe.getTribeName()); category.setStrongRemind(MyBabyApp.getSharedPreferences().getBoolean("canSendPush"+tribe.getTribeId() + "", true));//根据是否推送选择强弱提醒 String content=conversation.getLatestContent(); /*if (content.startsWith("欢迎")||content.startsWith("您已加入群")||content.endsWith("退出了群聊")||content.contains(MyBabyApp.currentUser.getName())|| MyBabyApp.currentUser.getImUserName().equals(conversation.getLatestMessageAuthorId())){ }*/ ywContact = IMUtility.getContactProfileInfo(conversation.getLatestMessageAuthorId(), conversation.getLatestMessageAuthorAppKey()); if (ywContact!=null) { String name = ywContact.getShowName(); if(MyBabyApp.currentUser.getImUserName().equals(conversation.getLatestMessageAuthorId())) { if (content.startsWith("您已加入群")){ content="欢迎您加入 "+tribe.getTribeName(); }else { content = "我: " + content; } }else if (content.contains(conversation.getLatestMessageAuthorId())){ content.replace(conversation.getLatestMessageAuthorId(), name); }else { if (content.startsWith("欢迎新成员")&&content.endsWith("加入群")) content="欢迎新成员\""+name+"\"加入群"; else if (!content.startsWith(name)) content=name+": "+content; } } category.setNewestDesc(content); TribeNotificationCategory tribeNtfc=new TribeNotificationCategory(category); for (NotificationCategory spaceItem:spaceNtfcList){ if (spaceItem.getTribe_id()==tribe.getTribeId()) { tribeNtfc.setSpace_isStrong(spaceItem.isStrongRemind()); //tribeNtfc.setStrongRemind(spaceItem.isStrongRemind()); tribeNtfc.setNewestDesc(spaceItem.getNewestDesc());//内容更新一下 if (spaceItem.isStrongRemind()){ if (category.isStrongRemind()==false) { tribeNtfc.setStrongRemind(true); if (MyBabyApp.getSharedPreferences().getBoolean("canSendPush"+tribe.getTribeId() + "", true)==false){ tribeNtfc.setStrongRemind(false); tribeNtfc.setSpace_isStrong(false); } tribeNtfc.setUnreadCount(category.getUnreadCount() + spaceItem.getUnreadCount()); }else { tribeNtfc.setUnreadCount(category.getUnreadCount()+ spaceItem.getUnreadCount()); } }else { if (spaceItem.getUnreadCount()!=0) { tribeNtfc.setStrongRemind(false); tribeNtfc.setUnreadCount(-1); }else tribeNtfc.setStrongRemind(true); } SharedPreferences.Editor edit = MyBabyApp.getSharedPreferences().edit(); edit.putBoolean("canSendPush", spaceItem.getUnreadCount()!=0?spaceItem.isStrongRemind():true); edit.commit(); tribeNtfc.setSpace_unread(spaceItem.getUnreadCount()); /*boolean a1=category.isStrongRemind(); boolean a2=MyBabyApp.getSharedPreferences().getBoolean("tribe_space_strong" + id, true); int b1=category.getUnreadCount(); int b2=MyBabyApp.getSharedPreferences().getInt("tribe_space_unread" + id, 0); category.setStrongRemind(a1?true:(a2?true:false)); category.setUnreadCount(b1+b2);*/ break; } } return tribeNtfc; }else if(conversation.getConversationType()== YWConversationType.P2P) { YWP2PConversationBody p2pBody = (YWP2PConversationBody) conversation.getConversationBody(); final IYWContact ywContact = IMUtility.getContactProfileInfo(p2pBody.getContact().getUserId(), p2pBody.getContact().getAppKey()); String username = ""; String url = ""; if (ywContact != null) { username = ywContact.getShowName(); url = TextUtils.isEmpty(ywContact.getAvatarPath()) ? ImageHelper.getMotherPicUrl() : ywContact.getAvatarPath(); } else { url = ImageHelper.getMotherPicUrl(); } final String finalUsername = username; String[][] aa = {{"im_userid", p2pBody.getContact().getUserId()}, {"username", finalUsername}}; category.setAction(Action.newActionLink(aa, P2PChattingAction.P2PChattingAction)); category.setImageUrl(url); category.setTitle(username); category.setStrongRemind(true);//默认是强提醒 category.setNewestDesc(conversation.getLatestContent()); } return category; } public int getUnreadCount(Context context){ IYWConversationService conversationService=MyBayMainActivity.getmIMKit().getConversationService(); List<NotificationCategory> listNC=getNtcLatestList(context, conversationService == null ? null : conversationService.getConversationList(), null); int unread=0; for(NotificationCategory category:listNC) unread+=category.isStrongRemind() ?category.getUnreadCount():0; return unread; } }
true
6c4101b6d1a7d6ec2da30cf217afc93b2875ed53
Java
on-full-hack/rankr-backend-deprecated
/src/main/java/pl/on/full/hack/league/service/LeaguePlayerService.java
UTF-8
5,402
2.171875
2
[]
no_license
package pl.on.full.hack.league.service; import javassist.NotFoundException; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.on.full.hack.auth.entity.RankrUser; import pl.on.full.hack.auth.exception.UnauthorizedException; import pl.on.full.hack.auth.repository.UserRepository; import pl.on.full.hack.league.entity.League; import pl.on.full.hack.league.entity.LeaguePlayer; import pl.on.full.hack.league.entity.LeaguePlayerId; import pl.on.full.hack.league.exception.PendingRequestException; import pl.on.full.hack.league.repository.LeaguePlayerRepository; import pl.on.full.hack.league.repository.LeagueRepository; import java.util.List; import java.util.Optional; @Service public class LeaguePlayerService { private LeaguePlayerRepository repository; private LeagueRepository leagueRepository; private UserRepository userRepository; @Autowired public LeaguePlayerService (LeaguePlayerRepository repository, UserRepository userRepository, LeagueRepository leagueRepository){ this.repository = repository; this.userRepository = userRepository; this.leagueRepository = leagueRepository; } public void joinToLeague(@NonNull final Long league_id,@NonNull final String username) throws NotFoundException, PendingRequestException{ final Optional<League> leagueOptional = leagueRepository.findById(league_id); final League league = leagueOptional .orElseThrow(() -> new NotFoundException("No league with id " + league_id)); //TODO: 1. Do we should check if the user is an admin? //TODO: 2. Create league -> add new user as admin? final RankrUser rankrUser = userRepository.findByUsername(username); final LeaguePlayerId leaguePlayerId = new LeaguePlayerId(rankrUser.getId(), league_id); Optional<LeaguePlayer> checkIfPlayerExists = repository.findById(leaguePlayerId); if(checkIfPlayerExists.isPresent()){ throw new PendingRequestException(); } LeaguePlayer player = new LeaguePlayer(leaguePlayerId, rankrUser, league, 0L, false); repository.save(player); } public void joinToLeagueByLink(@NonNull final String leagueCodeToJoin, @NonNull final String username) throws NotFoundException, PendingRequestException{ final League leagueToJoin = leagueRepository.findByCodeToJoin(leagueCodeToJoin); if(leagueToJoin == null){ throw new NotFoundException("No league with provided link found"); } final League league = leagueToJoin; //TODO: 1. Do we should check if the user is an admin? //TODO: 2. Create league -> add new user as admin? final RankrUser rankrUser = userRepository.findByUsername(username); final LeaguePlayerId leaguePlayerId = new LeaguePlayerId(rankrUser.getId(), league.getId()); LeaguePlayer player = new LeaguePlayer(leaguePlayerId, rankrUser, league, 0L, true); repository.save(player); } public void inviteToLeague(@NonNull final LeaguePlayerId leaguePlayerId, @NonNull final String username) throws NotFoundException, UnauthorizedException{ final RankrUser leagueAdmin = userRepository.findByUsername(username); final Optional<League> leagueOptional = leagueRepository.findById(leaguePlayerId.getLeagueId()); final League league = leagueOptional .orElseThrow(() -> new NotFoundException("No league with id " + leaguePlayerId.getLeagueId())); //TODO: 1. Check all users which has admin access granted //TODO: 2. Generate link for league to automatically add by using it if(leagueAdmin.getId() != league.getCreator().getId()){ throw new UnauthorizedException(); } Optional<RankrUser> rankrUserOptional = userRepository.findById(leaguePlayerId.getUserId()); RankrUser rankrUser = rankrUserOptional .orElseThrow(() -> new NotFoundException("No player with id " + leaguePlayerId.getLeagueId())); LeaguePlayer newPlayer = new LeaguePlayer(leaguePlayerId, rankrUser, league, 0L, true); repository.save(newPlayer); } public void removeFromLeague(@NonNull final LeaguePlayerId leaguePlayerId, @NonNull final String username) throws NotFoundException, UnauthorizedException{ final RankrUser userAuthenticated = userRepository.findByUsername(username); final Optional<League> leagueOptional = leagueRepository.findById(leaguePlayerId.getLeagueId()); final League league = leagueOptional .orElseThrow(() -> new NotFoundException("No league with id " + leaguePlayerId.getLeagueId())); //TODO: check all users which has admin access granted if(leaguePlayerId.getUserId() != userAuthenticated.getId() && userAuthenticated.getId() != league.getCreator().getId()){ throw new UnauthorizedException(); } Optional<RankrUser> rankrUserOptional = userRepository.findById(leaguePlayerId.getUserId()); RankrUser rankrUser = rankrUserOptional .orElseThrow(() -> new NotFoundException("No player with id " + leaguePlayerId.getLeagueId())); LeaguePlayer playerToRemove = new LeaguePlayer(leaguePlayerId, rankrUser, league, 0L, true); repository.delete(playerToRemove); } }
true
4aae6bd52a80fbce871f628c13d07e2122053b31
Java
trauvmfpt/proj-thymeleaf
/src/main/java/com/fpt/t1708e/photoplatform/repository/ProductRepository.java
UTF-8
1,761
2.015625
2
[]
no_license
package com.fpt.t1708e.photoplatform.repository; import com.fpt.t1708e.photoplatform.entity.Album; import com.fpt.t1708e.photoplatform.entity.Product; import com.fpt.t1708e.photoplatform.entity.StudioInfo; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import javax.transaction.Transactional; import java.util.List; public interface ProductRepository extends JpaRepository<Product,Long> { @Query(nativeQuery = true,value = "select * FROM product where destination like %:key% order by destination desc limit 5") List<Product> getTop5(@Param("key") String key); @Transactional @Modifying @Query(nativeQuery = true, value = "alter table product AUTO_INCREMENT = 1") void resetIncrement(); @Query(nativeQuery = true,value = "select * FROM product where category_id = :cateId order by price_discount desc limit 1") Product getTop1DiscountByCategory(@Param("cateId") long cateId); @Query(nativeQuery = true,value = "select * FROM product order by average_rate desc limit 10") List<Product> getTop10Rating(); List<Product> getProductByPhotographerInfoId(@Param("photographer") long id); List<Product> getProductByStudioInfoId(@Param("studio") long id); @Query("SELECT c FROM Product c where c.name LIKE %:key% or c.description LIKE %:key% or c.content LIKE %:key% ") List<Product> getAllByKey(String key); @Query(nativeQuery = true,value = "select * FROM product where status = :id order by average_rate desc limit 5") List<Product> getTop5ByStatus(@Param("id") int i); }
true
7e7049d046d2b7e2fd52a75f6033e490d25943a2
Java
keshav1234/kpp
/src/main/java/com/emts/dao/CountryDao.java
UTF-8
277
1.820313
2
[]
no_license
package com.emts.dao; import java.util.List; import com.emts.model.Country; public interface CountryDao { public void addCountryname(Country country); public List<Object> getContent(); public void removeContent(Integer Id); public List<Object> editContent(Integer Id); }
true
c192de12df307fca2c0340d59847aa01a59a62a6
Java
Diviercadavid/Ejercicios-Java-Primeros-Pasos
/PruebaJAVAFX/src/pruebajavafx/FXMLDocumentController.java
UTF-8
1,606
2.15625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pruebajavafx; import java.net.URL; import java.sql.*; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; /** * * @author Dcadavid */ public class FXMLDocumentController implements Initializable { Connection conectar = null; @FXML private TextField txb_nombre; @FXML private TextField txb_apellido; @FXML private TextField txb_datos; @FXML // fx:id="btn_generar" private Button btn_generar; // Value injected by FXMLLoader // @FXML // private void accionMostrar(ActionEvent evento) { // // txb_datos.setText("Holaa!!"); // System.out.println("No sirve"); // } @Override public void initialize(URL url, ResourceBundle rb) { // TODO accionesBotones(); } private void accionesBotones() { btn_generar.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent arg0) { txb_datos.setText("Holaa!!"); System.out.println("No sirve"); } }); } }
true
32f41312a9f7ff9494c906140e4084b1123b00e5
Java
ntejapermana/springmvc-starter-project
/jpa-xmlconfig/src/main/java/com/starter/springmvc/persistence/domain/User.java
UTF-8
1,325
2.25
2
[]
no_license
package com.starter.springmvc.persistence.domain; import java.io.Serializable; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="users") public class User implements Serializable { private static final long serialVersionUID = 3097214440934265L; @Id private String username; private String password; private int enabled; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="user") private Set<Authority> roles; public User() {} public User(String username, String password, int enabled) { this.username = username; this.password = password; this.enabled = enabled; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getEnabled() { return enabled; } public void setEnabled(int enabled) { this.enabled = enabled; } public Set<Authority> getRoles() { return roles; } public void setRoles(Set<Authority> roles) { this.roles = roles; } }
true
abf34c6461f7b6549f29f42d4cba7d890bdf1c6e
Java
jingtonglong/Project
/app/src/main/java/com/jtlrm/ckd/mvp/view/activity/ForgetPasswordActivity.java
UTF-8
4,457
2.234375
2
[]
no_license
package com.jtlrm.ckd.mvp.view.activity; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.base.sdk.base.net.CommonObserver; import com.base.sdk.util.ValidateUtils; import com.jtlrm.ckd.R; import com.jtlrm.ckd.base.acitvity.TitleBarActivity; import com.jtlrm.ckd.entity.LoginResult; import com.jtlrm.ckd.entity.YanZhengMaEntity; import com.jtlrm.ckd.mvp.model.UserModel; import com.jtlrm.ckd.mvp.model.dao.UserHelper; import butterknife.BindView; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; public class ForgetPasswordActivity extends TitleBarActivity { @BindView(R.id.phone) EditText phoneE; @BindView(R.id.yanzhengma) EditText yanZhengMaE; @BindView(R.id.get_yanzhengma) TextView getYanZhengMaE; String phone; UserModel userModel; String yanZhengMa; boolean canSend = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected String getTitleText() { return "忘记密码"; } @Override protected void setContentLayout() { setContentView(R.layout.activity_forget_password); } @Override protected void initView() { userModel = new UserModel(); } @Override protected void obtainData() { } @Override protected void initEvent() { getYanZhengMaE.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!canSend) { return; } phone = phoneE.getText() + ""; if (ValidateUtils.Mobile(phone)) { if (!notEmpty(UserHelper.getInstance(context).getToken())) { showLoadingDialog("加载中"); updateToken(); } else { sendMessage(); } } else { showToast("请输入正确的手机号"); } } }); } private void updateToken() { userModel.getToken(new Observer<LoginResult>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(LoginResult loginResult) { UserHelper.getInstance(context).setLogin(loginResult); sendMessage(); } @Override public void onError(Throwable e) { dismissLoadingDialog(); showToast("获取token失败"); } @Override public void onComplete() { } }, lifecycleSubject); } private void sendMessage() { userModel.sendForgetMessage(phone, new CommonObserver<YanZhengMaEntity>() { @Override public void onError(int errType, String errMessage) { dismissLoadingDialog(); showToast(errMessage); canSend = true; } @Override public void onResult(YanZhengMaEntity data) { dismissLoadingDialog(); showToast("已发送验证,注意查收"); yanZhengMa = data.getCode(); countDownTimer.start(); canSend = false; } }, lifecycleSubject); } CountDownTimer countDownTimer = new CountDownTimer(60 * 1000, 1000) { @Override public void onTick(long millisUntilFinished) { getYanZhengMaE.setText((millisUntilFinished / 1000) + "s后重新获取"); } @Override public void onFinish() { canSend = true; getYanZhengMaE.setText("获取验证码"); } }; public void next(View view){ if (!notEmpty(yanZhengMa)) { showToast("请获取验证码"); return; } if (inputEmpty(yanZhengMaE)) { showToast("请输入验证码"); return; } if (!yanZhengMa.equals(yanZhengMaE.getText() + "")) { showToast("验证码输入有误"); return; } RebuilPasswordActivity.goSetting(context, phone); finish(); } }
true
a4dd6852292e60a2df011c3c2c8a95f92797d9cb
Java
RobertZenz/Garbagecan
/slick/NoiseGeneration/src/noisegeneration/maps/Linear.java
UTF-8
1,978
2.828125
3
[ "LicenseRef-scancode-public-domain" ]
permissive
/* * Public Domain */ package noisegeneration.maps; import noisegeneration.Helper; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; /** * * @author Robert 'Bobby' Zenz */ public class Linear extends Map { private Image buffer; @Override public void generate(long seed, int width, int resolution) throws SlickException { super.generate(seed, width, resolution); buffer = new Image(width, width); Graphics g = buffer.getGraphics(); for (int x = 0; x < width / resolution - 1; x++) { for (int y = 0; y < width / resolution - 1; y++) { int idxTopLeft = x * resolution + y; int idxTopRight = (x + 1) * resolution + y; int idxBottomLeft = x * resolution + (y + 1); int idxBottomRight = (x + 1) * resolution + (y + 1); double valueTopLeft = points.get(idxTopLeft); double valueTopRight = points.get(idxTopRight); double valueBottomLeft = points.get(idxBottomLeft); double valueBottomRight = points.get(idxBottomRight); for (int x2 = x * resolution; x2 < (x + 1) * resolution; x2++) { int relativeX = x2 - x * resolution; double valueTop = Helper.interpolate(valueTopLeft, valueTopRight, (double) relativeX / resolution); double valueBottom = Helper.interpolate(valueBottomLeft, valueBottomRight, (double) relativeX / resolution); for (int y2 = y * resolution; y2 < (y + 1) * resolution; y2++) { int relativeY = y2 - y * resolution; double value = Helper.interpolate(valueTop, valueBottom, (double) relativeY / resolution); Color color = Color.black; color.r = color.g = color.b = (float) value; g.setColor(color); g.fillRect(x2, y2, 1, 1); } } } } g.flush(); } @Override public void render(GameContainer container, Graphics g) throws SlickException { g.drawImage(buffer, 0, 0); super.render(container, g); } }
true
74d9d7726b86cfae2432e51cc2d6be5a5cbe6175
Java
micorochio/ZingAndroid
/zinglibrary/src/main/java/com/bb/zinglibrary/http/RequestCallback.java
UTF-8
248
1.882813
2
[]
no_license
package com.bb.zinglibrary.http; import retrofit2.Callback; /** * Created by zing on 2016/12/4. */ public interface RequestCallback <T> { void onStart(); void onResponse(T o); void onError(Throwable e); void onCompleted(); }
true
65f47e3206cc15cb6ca53f43b2c7f8fb362a0fe3
Java
ilikemovingmoving/hfnu
/zhpcxt/src/test/Test.java
UTF-8
544
2.390625
2
[]
no_license
package test; import org.apache.commons.lang.StringUtils; public class Test { public static void main(String[] args) { // String s="909090"; // System.out.println(s.lastIndexOf("0")==s.length()-1); String s="安徽省芜湖市无为县石涧镇"; System.out.println(s.split("省")[0]); System.out.println(s.split("省")[1].split("市")[0]); System.out.println(s.split("省")[1].split("市")[1].split("县|区")[0]); System.out.println(s.split("省")[1].split("市")[1].split("县|区")[1].split("镇")[0]); } }
true
603e2cc9c8b629122f069f26199d7aa3d7a57d0d
Java
designwithabhishek/emailClient
/EmailClient/src/com/myapplication/controller/MainController.java
UTF-8
9,189
1.929688
2
[]
no_license
package com.myapplication.controller; import java.io.IOException; import java.net.URL; import java.util.Comparator; import java.util.ResourceBundle; import com.myapplication.controller.service.CreateAndRegisterEmailAccountService; import com.myapplication.controller.service.FolderUpdateService; import com.myapplication.controller.service.MessageRendererService; import com.myapplication.controller.service.SaveAttachmentService; import com.myapplication.model.EmailAccountBean; import com.myapplication.model.EmailMessengerBean; import com.myapplication.model.Singleton; import com.myapplication.model.folder.EmailFolderBean; import com.myapplication.model.table.RowFactory; import com.myapplication.view.ViewFactory; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.ProgressBar; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.scene.web.WebView; import javafx.stage.Stage; public class MainController extends AbstractController implements Initializable{ public MainController(ModelAccess modelAccess) { super(modelAccess); } EmailFolderBean<String> root; //private Singleton singleton; @FXML private Label downattachlabel; @FXML private ProgressBar downattachprogress; @FXML private Button readcontrol; @FXML private TreeView<String> emailtreeview; private MenuItem showDetails=new MenuItem("showDetails"); @FXML private TableView<EmailMessengerBean> emailBox; @FXML private TableColumn<EmailMessengerBean, String> subjectCol; @FXML private TableColumn<EmailMessengerBean, String> senderCol; @FXML private TableColumn<EmailMessengerBean, String> sizeCol; @FXML private WebView messageRenderer; private MessageRendererService messageRendererService; private SaveAttachmentService saveAttachmentService; @FXML private Button compose; @FXML private Button downattachbutton; @FXML void downloadingattachment(ActionEvent event) { System.out.println("downloadingattachment"); EmailMessengerBean message=emailBox.getSelectionModel().getSelectedItem(); System.out.println(message.getAttachmentList().toString()); if(message!=null&&message.hasAttachment()) { saveAttachmentService.setMessageToDownload(message); saveAttachmentService.restart(); } } @FXML void composeAction(ActionEvent event) { Scene scene=ViewFactory.default_factory.getComposeMessageScene(); Stage stage=new Stage(); stage.setScene(scene); stage.show(); } @FXML private Button addaccountbtn; @FXML void addaccountaction(ActionEvent event) { //AddAccountController addAccountController=new AddAccountController(getModelAccess(),root); Scene scene=ViewFactory.default_factory.getAddAccountScene(); Stage stage=new Stage(); stage.setScene(scene); stage.show(); Thread mythread=new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while(!getModelAccess().isStatus()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(getModelAccess().isStatus()); { CreateAndRegisterEmailAccountService emailService=new CreateAndRegisterEmailAccountService(getModelAccess().getEmailAddress(),getModelAccess().getPassword(),root,getModelAccess()); emailService.start(); getModelAccess().setStatus(false); } } }); mythread.start(); } /* @FXML void changeReadStatus(ActionEvent event) { EmailMessengerBean item=getModelAccess().getMessage(); if(item!=null) { boolean value = item.isRead(); item.setRead(!value); EmailFolderBean<String> selectedFolder=getModelAccess().getSelectedFolder(); if(selectedFolder!=null) { if(value) { selectedFolder.incrementUnreadMessagesCount(1); } else { selectedFolder.decrementUnreadMessagesCount(); } } } } */ /*final ObservableList<EmailMessengerBean> data=FXCollections.observableArrayList( new EmailMessengerBean("hello from abhi","abhianil96@gmail.com",66666), new EmailMessengerBean("hello from Mommy","abhianil96@gmail.com",665466), new EmailMessengerBean("hello from kushaal","abhianil96@gmail.com",96666), new EmailMessengerBean("hello from abhi","abhianil96@gmail.com",26366) ); */ @Override public void initialize(URL arg0, ResourceBundle arg1) { // TODO Auto-generated method stub //messageRenderer.getEngine().loadContent("<html>lets dothis</html>"); downattachlabel.setVisible(false); downattachprogress.setVisible(false); messageRendererService=new MessageRendererService(messageRenderer.getEngine()); saveAttachmentService=new SaveAttachmentService(downattachprogress,downattachlabel); downattachprogress.progressProperty().bind(saveAttachmentService.progressProperty()); ViewFactory viewFactory=ViewFactory.default_factory; emailBox.setRowFactory(e->new RowFactory<>()); subjectCol.setCellValueFactory(new PropertyValueFactory<EmailMessengerBean, String>("subject")); senderCol.setCellValueFactory(new PropertyValueFactory<EmailMessengerBean, String>("sender")); sizeCol.setCellValueFactory(new PropertyValueFactory<EmailMessengerBean, String>("size")); sizeCol.setComparator(new Comparator<String>() { Integer i1 , i2; public int compare(String s1,String s2) { i1=EmailMessengerBean.formattedValues.get(s1); i2=EmailMessengerBean.formattedValues.get(s2); return i1.compareTo(i2); } }); /* emailtreeview.setRoot(root); root.setValue("example@gmail.com"); root.setGraphic(viewFactory.resolveIcon(root.getValue())); TreeItem<String> inbox=new TreeItem<String>("Inbox",viewFactory.resolveIcon("Inbox")); TreeItem<String> sent=new TreeItem<String>("Sent",viewFactory.resolveIcon("Sent")); TreeItem<String> spam=new TreeItem<String>("Spam",viewFactory.resolveIcon("Spam")); TreeItem<String> trash=new TreeItem<String>("Trash",viewFactory.resolveIcon("Trash")); root.getChildren().addAll(inbox,sent,spam,trash); root.setExpanded(true); */ root=new EmailFolderBean<String>(""); emailtreeview.setRoot(root); emailtreeview.setShowRoot(true); FolderUpdateService folderUpdateService=new FolderUpdateService(getModelAccess().getFoldersList()); folderUpdateService.start(); //specify your username and password //CreateAndRegisterEmailAccountService emailService=new CreateAndRegisterEmailAccountService("designwithabhishek1996@gmail.com","qwer0192",root,getModelAccess()); //emailService.start(); /* CreateAndRegisterEmailAccountService emailService2=new CreateAndRegisterEmailAccountService("designwithabhishek1996@gmail.com","qwer0192",root,getModelAccess()); emailService2.start(); */ emailBox.setContextMenu(new ContextMenu(showDetails)); emailtreeview.setOnMouseClicked(e->{ EmailFolderBean<String> item=(EmailFolderBean<String>)emailtreeview.getSelectionModel().getSelectedItem(); if(item!=null&&!item.isTopElement()) emailBox.setItems(item.getData()); getModelAccess().setSelectedFolder(item); }); emailBox.setOnMouseClicked(e->{ EmailMessengerBean message=emailBox.getSelectionModel().getSelectedItem(); if(message!=null) { //messageRenderer.getEngine().loadContent(message.getContent()); getModelAccess().setMessage(message); messageRendererService.setMessageToRender(message); messageRendererService.restart(); //Platform.runLater(messageRendererService); //singleton.setMessage(message); } }); showDetails.setOnAction(e->{ Scene scene=viewFactory.getEmailDetailsScene(); Stage stage=new Stage(); stage.setScene(scene); stage.show(); }); //singleton=Singleton.getInstance(); } }
true
3d8786af819da14b8abf72449f98d1750f934156
Java
shonore/Hotfoot
/InformationFooter.java
UTF-8
772
2.09375
2
[ "Apache-2.0" ]
permissive
package net.androidbootcamp.hotfoot; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListAdapter; /** * Created by Stephanie on 6/13/16. */ public class InformationFooter extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.footer); Button next1 = (Button)findViewById(R.id.btnInfo); next1.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ startActivity(new Intent(InformationFooter.this, Day_1.class)); } }); } }
true
524e682fa6ad549220aa2154ae1ee49717781e43
Java
isaaceindhoven/isaac-dotcms-advancedsearch
/src/main/java/nl/isaac/dotcms/searcher/status/TemplateStatus.java
UTF-8
2,065
2.4375
2
[ "CC-BY-3.0", "MIT" ]
permissive
package nl.isaac.dotcms.searcher.status; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.DotStateException; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.templates.model.Template; import nl.isaac.dotcms.searcher.shared.Status; import nl.isaac.dotcms.searcher.shared.Status.StatusEnum; public class TemplateStatus implements StatusInterface { @Override public Status getStatus(Object object, Status expectingStatus) { if(object instanceof Template) { Status status = new Status(); Template template = (Template) object; try { if((expectingStatus.getStatus().equals(StatusEnum.ALL) || expectingStatus.getStatus().equals(StatusEnum.UNPUBLISHED)) && !template.isArchived() && !template.isLive()) { Template published = null; try { published = APILocator.getTemplateAPI().findLiveTemplate(template.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false); } catch(Exception e) { /* Do nothing, Published version doesn't exists */ } if(published != null && !published.getInode().equalsIgnoreCase(template.getInode())) { status.setStatus(StatusEnum.SAVED); status.setObject(published); return status; } else { status.setStatus(StatusEnum.UNPUBLISHED); return status; } } else if((expectingStatus.getStatus().equals(StatusEnum.ALL) || expectingStatus.getStatus().equals(StatusEnum.PUBLISHED)) && !template.isArchived() && template.isLive()) { status.setStatus(StatusEnum.PUBLISHED); return status; } else if((expectingStatus.getStatus().equals(StatusEnum.ALL) || expectingStatus.getStatus().equals(StatusEnum.ARCHIVED)) && template.isArchived() && !template.isLive()) { status.setStatus(StatusEnum.ARCHIVED); return status; } } catch (DotStateException | DotDataException | DotSecurityException e) { throw new RuntimeException(e.toString(), e); } } return null; } }
true
7b0f63033c2681daf3306bbdd0701a3b55d9d64e
Java
bellmit/Intkr_SAAS_BEIDEN
/com/intkr/saas/module/screen/saas/sys/StatisticsMgr.java
UTF-8
1,020
1.898438
2
[ "Apache-2.0" ]
permissive
package com.intkr.saas.module.screen.saas.sys; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.intkr.saas.domain.bo.sys.StatisticsBO; import com.intkr.saas.manager.sys.StatisticsManager; import com.intkr.saas.module.action.sys.StatisticsAction; import com.intkr.saas.util.claz.IOC; /** * * @author Beiden * @date 2011-10-2 上午11:31:26 * @version 1.0 */ public class StatisticsMgr { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private StatisticsManager statisticsManager = IOC.get(StatisticsManager.class); public void execute(HttpServletRequest request, HttpServletResponse response) { StatisticsBO query = StatisticsAction.getParameter(request); query.setQuery("orderBy", "id"); query.setQuery("order", "desc"); statisticsManager.selectAndCount(query); request.setAttribute("query", query); request.setAttribute("list", query.getDatas()); } }
true
fc53fbabc52fe61734bc9d44f2bf7a5dff2cf140
Java
Sewriugin/HackerU_OOP
/src/com/company/Main.java
UTF-8
11,934
3.421875
3
[]
no_license
/* ДЗ_Перегрузка методов ShowTime_1 package com.company; public class Main { public static void main(String[] args) { // write your code here showTime(2); showTime(2,5); showTime(2,5 ,8); } public static void showTime(int hours) { System.out.println(hours + " -часов, " + 0 + " -минут, " + 0 + " -секунд "); } public static void showTime(int hours, int minutes) { System.out.println(hours + " -часов, " + minutes + " -минут, " + 0 + " -секунд "); } public static void showTime(int hours, int minutes, int seconds) { System.out.println(hours + " -часов, " + minutes + " -минут, " + seconds + " -секунд "); } } */ /* Циклы_2 package com.company; public class Main { public static void main(String[] args) { // write your code here int count = 5; for (int x = 0; count >= 1; x = x + 1){ count = count - 1; if ((count % 2) != 0) System.out.println("нечетные числа count - " + count); else if (count > 0) System.out.println("четные числа count - " + count); if (count == 0) System.out.println("нулевое значение числа count - " + count); } } } */ /* ДЗ_Массивы_3 package com.company; public class Main { public static void main(String[] args) { String [] array = {" I ", " like ", " to ", " program ", " in ", " Java "}; String result = ""; for (int i = 0; i < array.length; i++) { if(i == 5 || i == 1 || i == 0) result = result + array[i]; } System.out.println(result); } } */ /* //RadioStation_4 package com.company; public class Main { public static void main(String[] args) { // write your code here RadioStation FM = new RadioStation("FM",88.8f,"fm"); //FM.frequency = 88.8f; без конструктора RadioStation AM = new RadioStation("AM",101.2f,"am"); //AM.frequency = 101.2f; без конструктора RadioStation FM_AM = new RadioStation(100f); FM.name(); FM.frequency(); FM.format(); AM.name(); AM.frequency(); AM.format(); FM_AM.frequency(); } } */ //Run_5 /* package com.company; public class Main { public static void main(String[] args) { // write your code here Run run1 = new Run(10, "+++", 0); Run run2 = new Run(5, "---"); System.out.println("Кличество бегунов - " + run1.numberOfRunners); System.out.println("Погода - " + run1.Weather); System.out.println("Кличество бегунов - " + run2.numberOfRunners); System.out.println("Погода - " + run2.Weather); Run run3 = new Run(run1); System.out.println("Кличество бегунов - " + run3.numberOfRunners); System.out.println("Погода - " + run3.Weather); } } */ //Hause_6 /* package com.company; public class Main { public static void main(String[] args) { // write your code here Hause dom1 = new Hause(); Hause dom2 = new Hause(); dom1.setColor("green"); dom1.setHeight(14); dom2.setColor("red"); dom2.setHeight(17); System.out.println(dom1.getColor() + " " + dom1.getHeight()); System.out.println(dom2.getColor() + " " + dom2.getHeight()); } } */ //Conference_7 /*package com.company; public class Main { public static void main(String[] args) { // write your code here Conference.PERIOD = 1; Conference.showPeriod(); Conference medicalConference = new Conference(); medicalConference.setTopic("New in therapy"); medicalConference.showTopic(); Conference IT_CONFERENCE = Conference.IT_CONFERENCE(); System.out.println(IT_CONFERENCE.getTopic()); } } */ //Car_8 /* package com.company; public class Main { public static void main(String[] args) { // write your code here Car car1 = new Car(0,100); //Car car2 = car1; //1-ая часть //System.out.println("maxSpeed car1 " + car1.maxSpeed + "; maxSpeed car2 " + car2.maxSpeed); //car2.setMaxSpeed(200); //System.out.println("maxSpeed car1 " + car1.maxSpeed + "; maxSpeed car2 " + car2.maxSpeed); car1.setMaxSpeed(100); Car car2 = new Car(0, 100); System.out.println("maxSpeed car1 " + car1.maxSpeed + "; maxSpeed car2 " + car2.maxSpeed); car2.setMaxSpeed(200); System.out.println("maxSpeed car1 " + car1.maxSpeed + "; maxSpeed car2 " + car2.maxSpeed); } } */ //Laptop_9 /* package com.company; public class Main { private static Object Laptop; public static void main(String[] args) { // write your code here com.company.Laptop Samsung = new Laptop("silver", "Samsung"); com.company.Laptop HP = new Laptop("silver", "HP"); //1) System.out.println(Samsung==HP); //1) System.out.println(Samsung.equals(HP)); //2) Samsung.setBrand("HP"); //2) Laptop HP = new Laptop("silver","Samsung"); //System.out.println(Samsung==HP); System.out.println(Samsung.equals(HP)); } } */ //Airplane_10 /* package com.company; public class Main { private static Object Airoplane; public static void main(String[] args) { // write your code here com.company.Airplane S7 = new Airplane(); com.company.Airplane UralAirlines = new Airplane(); System.out.println(S7.equals(UralAirlines)); } } */ //Math_11 /* package com.company; public class Main { public static void main(String[] args) { // write your code here Object object1 = new Math(); Object object2 = new Math(); object1.equals(object2); System.out.println(object1.equals(object2)); System.out.println(); } } */ //1) Stack_12 /* package com.company; public class Main { public static void main(String[] args) { // write your code here System.out.println(" main "); method1(); System.out.println(" main "); } public static void method1(){ System.out.println(" method1 "); method2(); System.out.println(" method1 "); } public static void method2(){ System.out.println(" method2 "); method3(); System.out.println(" method2 "); } public static void method3(){ System.out.println(" method3 "); } } */ //2) Stack_12 /* package com.company; public class Main { public static void method1() { System.out.println(" method1 "); method2(); method1(); } public static void method2() { method3(); System.out.println(" method2 "); } public static void method3() { System.out.println(" method3 "); } public static void main(String[] args) { // write your code here method1(); } } */ //Hash Code (частично)_13 /* package com.company; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { public static void main(String[] args) { // write your code here; //Dog dog1 = new Dog("Rex1", 10, 20); //Dog dog2 = new Dog("Rex2",10,20); //System.out.println(dog1.hashCode()); //System.out.println(dog2.hashCode()); List<Dog> list = new ArrayList<>(); list.add(new Dog()); list.add(new Dog()); System.out.println(); Set<Dog> set = new HashSet<Dog>(); set.add(new Dog()); set.add(new Dog()); System.out.println(); } } */ // Grandfather_14 /* package com.company; public class Main { public static void main(String[] args) { // write your code here Grandfather grandfather = new Grandfather(); grandfather.knowsWholsLenin(); System.out.println(" grandfather.knowsWholsLenin" ); Father father = new Father(); father.listenTheBeatles(); father.knowsWholsLenin(); System.out.println(" father.listenTheBeatles " + " father.knowsWholsLenin "); Son son = new Son(); son.learnJava(); son.knowsWholsLenin(); son.listenTheBeatles(); System.out.println(" son.learnJava " + " son.knowsWholsLenin " + " son.listenTheBeatles "); Daughter daughter = new Daughter(); daughter.learnJavaAndSql(); daughter.knowsWholsLenin(); daughter.listenTheBeatles(); System.out.println(" daughter.learnJavaAndSql " + " daughter.knowsWholsLenin " + " daughter.listenTheBeatles "); } } */ // TireFitting_15 /* package com.company; public class Main { public static void main(String[] args) { // write your code here TireFitting.makeService(); } } */ // Heroes_16 (запутался..) /* package com.company; import mutants.Deadpool; import mutants.Spiderman; import people.IronMan; import people.Superman; public class Main { public static void main(String[] args) { // write your code here Spiderman spiderman = new Spiderman(); System.out.println(spiderman.breath); System.out.println(new Deadpool()); System.out.println(new Superman()); System.out.println(new IronMan()); } } */ //Appliance_17 /*package com.company; public class Main { public static void main(String[] args) { // write your code here //Kettle kettle = new Kettle(); //kettle.doWork(); //Dishwasher dishwasher = new Dishwasher(); //dishwasher.doWork(); //Appliance [] Appliances = {new Kettle(), new Dishwasher()}; Appliance[] appliances = {new Kettle(), new Dishwasher()}; for (Appliance appliance : appliances) { System.out.println(" Kettle " + " Dishwasher"); } } } */ //Appliance Again_18 /* package com.company; public class Main { public static void main(String[] args) { // write your code here //1) Kettle kettle = new Kettle(); //1) kettle.doWork(); //1) Dishwasher dishwasher = new Dishwasher(); //1) dishwasher.doWork(); //1) Appliance [] Appliances = {new Kettle(), new Dishwasher()}; //2) Appliance[] appliances = {new Kettle(), new Dishwasher()}; //2) for (Appliance appliance : appliances) { //2) System.out.println(" Kettle " + " Dishwasher"); //2) } Object object1 = new Dishwasher(); Object object2 = new Kettle(); //Appliance[] appliances = {new Kettle(), new Dishwasher()}; // for (Appliance appliance : appliances) { // appliance.doWork(); // System.out.println(" Kettle " + " Dishwasher"); ApplianceAgain[] applianceAgains = {new Kettle(), new Dishwasher()}; for (ApplianceAgain applianceAgain : applianceAgains) { ApplianceAgain.doWork(); System.out.println(" Kettle " + " Dishwasher"); } } } */
true
9215c7d0f4c7dbf3f9513f2906feaa7c9fa9764c
Java
gorghino/diceliar
/diceLiar/src/diceliar/Board.java
UTF-8
3,595
3
3
[]
no_license
package diceliar; import java.util.concurrent.ThreadLocalRandom; import java.util.Random; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author proietfb */ public class Board { int nTurn; int nPlayers; Bet currentBet; Players currentPlayers; Player playingPlayer; public Board(int _nTurn, int _nPlayers){ nTurn = _nTurn; nPlayers = _nPlayers; //currentBet = new Bet(2,2); currentPlayers = new Players(_nPlayers); currentPlayers.getAllId(); currentPlayers.getVectorPlayers()[0].makeChoice(); } void initGame(Board startBoard){ int playerStarterID = startBoard.setStarter(); Player playerStarter = startBoard.getCurrentPlayers().getVectorPlayers()[playerStarterID]; setPlayingPlayer(playerStarter); System.out.println("Inizia a giocare il giocatore numero " + playerStarterID); playerStarter.setTurn(true); gameLoop(startBoard, playerStarter); } private void gameLoop(Board board, Player player){ while(true){ System.out.println("* Giocatore " + getPlayingPlayer().getMyID()+ " tocca a te!"); System.out.println("Turno: " + this.getnTurn()); player.makeChoice(); player.setTurn(false); //Non tocca più a questo player //Il turno passa al giocatore successivo board.setnTurn(getnTurn() + 1); board.setPlayingPlayer(board.getCurrentPlayers().getVectorPlayers()[(getPlayingPlayer().getMyID() + 1) % nPlayers]); player = board.getCurrentPlayers().getVectorPlayers()[(getPlayingPlayer().getMyID() + 1) % nPlayers]; player.setTurn(true); } } public boolean checkBet(){ if(currentBet.getAmount() > currentPlayers.getAllDice()[currentBet.getValueDie()-1]) //Ci sono più o uguale dadi di quelli della scommessa --> OK return true; else return false; } public int getnTurn() { return nTurn; } public void setnTurn(int _nTurn) { this.nTurn = _nTurn; } public int getnPlayers() { return nPlayers; } public void setnPlayers(int _nPlayers) { this.nPlayers = _nPlayers; } public Players getCurrentPlayers() { return currentPlayers; } public void setCurrentPlayers(Players currentPlayers) { this.currentPlayers = currentPlayers; } public int setStarter(){ return ThreadLocalRandom.current().nextInt(0, nPlayers); } public Bet getCurrentBet() { return currentBet; } public void setCurrentBet(Bet _currentBet) { this.currentBet = _currentBet; } public Player getPlayingPlayer() { return playingPlayer; } public void setPlayingPlayer(Player playingPlayer) { this.playingPlayer = playingPlayer; } void newTurn(Board currentBoard, int starterIDPlayer, Bet starterBet) { System.out.println("--------------- NUOVO TURNO ---------------------\n"); this.getCurrentPlayers().resetAllDice(); currentPlayers.printDice(); currentBoard.setCurrentBet(starterBet); currentBoard.getCurrentPlayers().getVectorPlayers()[starterIDPlayer].setTurn(true); } }
true
7892f5e0636d50fd784f890d793b12e6a81dec72
Java
elifsagban/DesignPatterns
/midterm/midterm/observer/myclasses/NumberPublisherDemo.java
UTF-8
580
2.9375
3
[]
no_license
package myclasses; public class NumberPublisherDemo { public static void main(String[] args) throws InterruptedException { NumberPublisher subject = new NumberPublisher(); new BinaryView(subject); new HexaDecimalView(subject); new DecimalView(subject); int publishCount = 5; for (int i =0; i<publishCount; i++){ int number = i*20; System.out.println("\nPublishing with Observer Interface:" + number); subject.NumberPublisher(number); Thread.sleep(1000); } } }
true
38e47ca2c36a1bd3e1dc5ebce91050933d673724
Java
nubiofs/mapfaces
/library/templates/mochafaces/src/main/java/org/mochafaces/renderkit/objectInterface/BodyDesktopHeaderRenderer.java
UTF-8
5,438
1.773438
2
[]
no_license
/* * MDweb - Open Source tool for cataloging and locating environmental resources * http://mdweb.codehaus.org * * Copyright (c) 2007-2009, Institut de Recherche pour le Développement (IRD) * Copyright (c) 2009, Geomatys * * This file is part of MDweb. * * MDweb is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 3.0 of the License. * * MDweb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details: * http://www.gnu.org/licenses/lgpl-3.0.html * */ package org.mochafaces.renderkit.objectInterface; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.component.html.HtmlOutputText; import javax.faces.context.FacesContext; import org.mochafaces.component.html.UIDiv; import org.mochafaces.component.objectInterface.UIBodyDesktopAppNavBar; import org.mochafaces.component.objectInterface.UIBodyDesktopHeader; import org.mochafaces.component.objectInterface.UIBodyDesktopTopNavBar; import org.mochafaces.renderkit.html.DivRenderer; /** * * @author kevindelfour */ public class BodyDesktopHeaderRenderer extends DivRenderer { private final static String DESKTOPHEADER_ID = "desktopHeader"; private final static String DESKTOPTITLEBARWRAPPER_ID = "desktopTitlebarWrapper"; private final static String DESKTOPNAVBARWRAPPER_ID = "desktopNavbar"; private final static String DESKTOPTITLEBAR_ID = "desktopTitlebar"; private final static String APPLICATIONTITLE_CLASS = "applicationTitle"; private final static String TAGLINE_CLASS = "tagline"; @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { final UIBodyDesktopHeader uibdh = (UIBodyDesktopHeader) component; if (uibdh.isEnableApplicationTitleBar()) { final UIDiv desktopTitlebarWrapper = new UIDiv(); final UIDiv desktopTitlebar = new UIDiv(); for (UIComponent uIComponent : uibdh.getChildren()) { if (uIComponent instanceof UIBodyDesktopTopNavBar) { desktopTitlebar.getChildren().add(uIComponent); } } final UIDiv applicationTitleBar = new UIDiv(); desktopTitlebarWrapper.setId(DESKTOPTITLEBARWRAPPER_ID); desktopTitlebar.setId(DESKTOPTITLEBAR_ID); applicationTitleBar.setStyleClass(APPLICATIONTITLE_CLASS); if (uibdh.getApplicationLogoURL() != null) { final String logoUrl = "background: transparent url('" + uibdh.getApplicationLogoURL() + "') no-repeat scroll 0% 0%;"; desktopTitlebar.setStyle(logoUrl); } if (uibdh.getApplicationTitle() != null) { final HtmlOutputText applicationTitle = new HtmlOutputText(); applicationTitle.setValue(uibdh.getApplicationTitle()); applicationTitle.setStyleClass(APPLICATIONTITLE_CLASS); desktopTitlebar.getChildren().add(applicationTitle); } if (uibdh.getApplicationTagline() != null) { final HtmlOutputText applicationTagline = new HtmlOutputText(); applicationTagline.setValue(uibdh.getApplicationTagline()); applicationTagline.setStyleClass(TAGLINE_CLASS); desktopTitlebar.getChildren().add(applicationTagline); } desktopTitlebarWrapper.getChildren().add(desktopTitlebar); uibdh.getChildren().add(desktopTitlebarWrapper); } else { for (UIComponent uIComponent : uibdh.getChildren()) { if (uIComponent instanceof UIBodyDesktopTopNavBar) { uIComponent.setRendered(false); } } } if (uibdh.isEnableApplicationMainNavBar()) { final UIDiv desktopNavbarWrapper = new UIDiv(); desktopNavbarWrapper.setId(DESKTOPNAVBARWRAPPER_ID); for (UIComponent uIComponent : uibdh.getChildren()) { if (uIComponent instanceof UIBodyDesktopAppNavBar) { UIBodyDesktopAppNavBar tmp = (UIBodyDesktopAppNavBar) uIComponent; desktopNavbarWrapper.getChildren().add(tmp); if (tmp.getStyle() != null){ desktopNavbarWrapper.setStyle(tmp.getStyle()); tmp.setStyle(null); } if (tmp.getStyleClass() != null){ desktopNavbarWrapper.setStyleClass(tmp.getStyleClass()); tmp.setStyleClass(null); } } } uibdh.getChildren().add(desktopNavbarWrapper); } else { for (UIComponent uIComponent : uibdh.getChildren()) { if (uIComponent instanceof UIBodyDesktopAppNavBar) { uIComponent.setRendered(false); } } } //Fix this div id for help Mocha to know where start the desktop uibdh.setId(DESKTOPHEADER_ID); super.encodeBegin(context, uibdh); } }
true
4d756dfc2e3eb0529c4d04b1e51655cb7a6b327e
Java
ievgen2701/spring-boot-hocon-config
/hocon-demo/src/main/java/faam/boot/hocondemo/HoconDemoApplication.java
UTF-8
317
1.757813
2
[]
no_license
package faam.boot.hocondemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HoconDemoApplication { public static void main(String[] args) { SpringApplication.run(HoconDemoApplication.class, args); } }
true
233be70bd6f3233bb2e0b0051ce751d52dfb669f
Java
saopayne/wordifi
/build/real/Nokia/N97/en_US/source/de/enough/polish/ui/itemviews/ExplodingParticlesItemView.java
UTF-8
4,844
2.109375
2
[]
no_license
//#condition polish.usePolishGui /* * Created on Sep 16, 2007 at 3:09:31 PM. * * Copyright (c) 2010 Robert Virkus / Enough Software * * This file is part of J2ME Polish. * * J2ME Polish is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * J2ME Polish is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with J2ME Polish; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Commercial licenses are also available, please * refer to the accompanying LICENSE.txt or visit * http://www.j2mepolish.org for details. */ package de.enough.polish.ui.itemviews; import javax.microedition.lcdui.Graphics; import de.enough.polish.ui.ClippingRegion; import de.enough.polish.ui.Item; import de.enough.polish.ui.ItemView; import de.enough.polish.ui.UiAccess; import de.enough.polish.util.DrawUtil; import de.enough.polish.util.ImageUtil; /** * <p>Splits the affected item into single pixels that quickly expand.</p> * <p>usage (e.g. for visualizing a pressed state): * <pre> * .myItem { * font-color: blue; * } * .myItem:hover { * font-color: red; * } * .myItem:pressed { * view-type: particle; * } * </pre> * </p> * * <p>Copyright Enough Software 2007 - 2010</p> * <pre> * history * Sep 16, 2007 - rob creation * </pre> * @author Robert Virkus, j2mepolish@enough.de */ public class ExplodingParticlesItemView extends ItemView { private int scaleFactor = 260; private int steps = 10; private int currentStep; private int[] originalRgb; private int[] scaledRgb; private boolean isDirectionUp; private int paintWidth; private int paintHeight; /** * Creates a new view */ public ExplodingParticlesItemView() { // nothing to initialize } /* (non-Javadoc) * @see de.enough.polish.ui.ItemView#initContent(de.enough.polish.ui.Item, int, int) */ protected void initContent(Item parent, int firstLineWidth, int availWidth, int availHeight) { initContentByParent(parent, firstLineWidth, availWidth, availHeight); //#if polish.midp2 int width = (this.contentWidth * this.scaleFactor) / 100; int height = (this.contentHeight * this.scaleFactor) / 100; int[] rgbData = new int[ width * height]; int x = (width - this.contentWidth) >> 1; int y = (height - this.contentHeight) >> 1; UiAccess.getRgbDataOfContent(parent, rgbData, x, y, width ); int[] target = new int[ rgbData.length ]; System.arraycopy( rgbData, 0, target, 0, rgbData.length ); this.paintWidth = width; this.paintHeight = height; this.isDirectionUp = true; this.originalRgb = rgbData; this.scaledRgb = target; //#endif } /* (non-Javadoc) * @see de.enough.polish.ui.ItemView#animate(long, de.enough.polish.ui.ClippingRegion) */ public void animate(long currentTime, ClippingRegion repaintRegion) { if (this.scaledRgb == null) { return; } super.animate(currentTime, repaintRegion); int step = this.currentStep; if (this.isDirectionUp) { step++; if (step >= this.steps) { this.isDirectionUp = false; } } else { step--; if (step <= 0) { step = 0; this.isDirectionUp = true; } } this.currentStep = step; int factor = 100 + (this.scaleFactor - 100) * (step * step) / ( (this.steps - 1) * (this.steps - 1)); ImageUtil.particleScale(factor, this.paintWidth, this.paintHeight, this.originalRgb, this.scaledRgb); Item item = this.parentItem; repaintRegion.addRegion( item.getAbsoluteX() - ((this.paintWidth - item.itemWidth) >> 1), item.getAbsoluteY() - ((this.paintHeight - item.itemHeight) >> 1), this.paintWidth, this.paintHeight ); } /* (non-Javadoc) * @see de.enough.polish.ui.ItemView#paintContent(de.enough.polish.ui.Item, int, int, int, int, javax.microedition.lcdui.Graphics) */ protected void paintContent(Item parent, int x, int y, int leftBorder, int rightBorder, Graphics g) { if (this.scaledRgb == null) { super.paintContentByParent(parent, x, y, leftBorder, rightBorder, g); return; } //#if polish.midp2 DrawUtil.drawRgb(this.scaledRgb, x - ((this.paintWidth - this.contentWidth)>>1), y - ((this.paintHeight - this.contentHeight)>>1), this.paintWidth, this.paintHeight, true, g ); //#endif } }
true
1a6c82d8ca23460484285af26c91853c5caf5945
Java
bryanduxbury/hank
/src/java/com/rapleaf/hank/storage/curly/Curly.java
UTF-8
21,829
1.6875
2
[]
no_license
/** * Copyright 2011 Rapleaf * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rapleaf.hank.storage.curly; import com.rapleaf.hank.compress.CompressionCodec; import com.rapleaf.hank.compress.NoCompressionCodec; import com.rapleaf.hank.config.DataDirectoriesConfigurator; import com.rapleaf.hank.coordinator.Domain; import com.rapleaf.hank.coordinator.DomainVersion; import com.rapleaf.hank.coordinator.DomainVersionPropertiesSerialization; import com.rapleaf.hank.hasher.Hasher; import com.rapleaf.hank.hasher.Murmur64Hasher; import com.rapleaf.hank.storage.*; import com.rapleaf.hank.storage.Reader; import com.rapleaf.hank.storage.Writer; import com.rapleaf.hank.storage.cueball.Cueball; import com.rapleaf.hank.storage.cueball.CueballMerger; import com.rapleaf.hank.storage.cueball.CueballStreamBufferMergeSort; import com.rapleaf.hank.storage.incremental.IncrementalDomainVersionProperties; import com.rapleaf.hank.util.FsUtils; import java.io.*; import java.nio.ByteBuffer; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Curly is a storage engine designed for larger, variable-sized values. It uses * Cueball under the hood. */ public class Curly implements StorageEngine { private static final Pattern BASE_OR_REGEX_PATTERN = Pattern.compile(".*(\\d{5})\\.((base)|(delta))\\.curly"); static final String BASE_REGEX = ".*\\d{5}\\.base\\.curly"; static final String DELTA_REGEX = ".*\\d{5}\\.delta\\.curly"; public static class Factory implements StorageEngineFactory { public static final String REMOTE_DOMAIN_ROOT_KEY = "remote_domain_root"; public static final String RECORD_FILE_READ_BUFFER_BYTES_KEY = "record_file_read_buffer_bytes"; public static final String HASH_INDEX_BITS_KEY = "hash_index_bits"; public static final String MAX_ALLOWED_PART_SIZE_KEY = "max_allowed_part_size"; public static final String KEY_HASH_SIZE_KEY = "key_hash_size"; public static final String FILE_OPS_FACTORY_KEY = "file_ops_factory"; public static final String HASHER_KEY = "hasher"; private static final String COMPRESSION_CODEC = "compression_codec"; public static final String NUM_REMOTE_LEAF_VERSIONS_TO_KEEP = "num_remote_leaf_versions_to_keep"; public static final String VALUE_FOLDING_CACHE_CAPACITY = "value_folding_cache_capacity"; public static final String KEY_FILE_PARTITION_CACHE_CAPACITY = "key_file_partition_cache_capacity"; public static final String RECORD_FILE_PARTITION_CACHE_CAPACITY = "record_file_partition_cache_capacity"; private static final String BLOCK_COMPRESSION_CODEC = "block_compression_codec"; private static final String COMPRESSED_BLOCK_SIZE_THRESHOLD = "compressed_block_size_threshold"; private static final String OFFSET_IN_BLOCK_NUM_BYTES = "offset_in_block_num_bytes"; private static final Set<String> REQUIRED_KEYS = new HashSet<String>(Arrays.asList(REMOTE_DOMAIN_ROOT_KEY, RECORD_FILE_READ_BUFFER_BYTES_KEY, HASH_INDEX_BITS_KEY, MAX_ALLOWED_PART_SIZE_KEY, KEY_HASH_SIZE_KEY, FILE_OPS_FACTORY_KEY, HASHER_KEY, NUM_REMOTE_LEAF_VERSIONS_TO_KEEP)); @Override public StorageEngine getStorageEngine(Map<String, Object> options, Domain domain) throws IOException { for (String requiredKey : REQUIRED_KEYS) { if (options == null || options.get(requiredKey) == null) { throw new RuntimeException("Required key '" + requiredKey + "' was not found!"); } } Hasher hasher; PartitionRemoteFileOpsFactory fileOpsFactory; Class<? extends CompressionCodec> compressionCodecClass; try { hasher = (Hasher) Class.forName((String) options.get(HASHER_KEY)).newInstance(); fileOpsFactory = (PartitionRemoteFileOpsFactory) Class.forName((String) options.get(FILE_OPS_FACTORY_KEY)).newInstance(); String compressionCodecClassName = (String) options.get(COMPRESSION_CODEC); if (compressionCodecClassName == null) { compressionCodecClass = NoCompressionCodec.class; } else { compressionCodecClass = (Class<? extends CompressionCodec>) Class.forName(compressionCodecClassName); } } catch (Exception e) { throw new RuntimeException(e); } final long maxAllowedPartSize = options.get(MAX_ALLOWED_PART_SIZE_KEY) instanceof Long ? (Long) options.get(MAX_ALLOWED_PART_SIZE_KEY) : ((Integer) options.get(MAX_ALLOWED_PART_SIZE_KEY)).longValue(); // num remote bases to keep Integer numRemoteLeafVersionsToKeep = (Integer) options.get(NUM_REMOTE_LEAF_VERSIONS_TO_KEEP); // Value folding cache size Integer valueFoldingCacheCapacity = (Integer) options.get(VALUE_FOLDING_CACHE_CAPACITY); if (valueFoldingCacheCapacity == null) { valueFoldingCacheCapacity = -1; } // Cache capacity Integer keyFilePartitionCacheCapacity = (Integer) options.get(KEY_FILE_PARTITION_CACHE_CAPACITY); if (keyFilePartitionCacheCapacity == null) { keyFilePartitionCacheCapacity = -1; } Integer recordFilePartitionCacheCapacity = (Integer) options.get(RECORD_FILE_PARTITION_CACHE_CAPACITY); if (recordFilePartitionCacheCapacity == null) { recordFilePartitionCacheCapacity = -1; } // Block compression BlockCompressionCodec blockCompressionCodec = null; String blockCompressionCodecStr = (String) options.get(BLOCK_COMPRESSION_CODEC); if (blockCompressionCodecStr != null) { blockCompressionCodec = BlockCompressionCodec.valueOf(blockCompressionCodecStr.toUpperCase()); } Integer compressedBlockSizeThreshold = (Integer) options.get(COMPRESSED_BLOCK_SIZE_THRESHOLD); if (compressedBlockSizeThreshold == null) { compressedBlockSizeThreshold = -1; } Integer offsetInBlockNumBytes = (Integer) options.get(OFFSET_IN_BLOCK_NUM_BYTES); if (offsetInBlockNumBytes == null) { offsetInBlockNumBytes = -1; } return new Curly((Integer) options.get(KEY_HASH_SIZE_KEY), hasher, maxAllowedPartSize, (Integer) options.get(HASH_INDEX_BITS_KEY), (Integer) options.get(RECORD_FILE_READ_BUFFER_BYTES_KEY), (String) options.get(REMOTE_DOMAIN_ROOT_KEY), fileOpsFactory, compressionCodecClass, domain, numRemoteLeafVersionsToKeep, valueFoldingCacheCapacity, keyFilePartitionCacheCapacity, recordFilePartitionCacheCapacity, blockCompressionCodec, compressedBlockSizeThreshold, offsetInBlockNumBytes); } @Override public String getPrettyName() { return "Curly"; } @Override public String getDefaultOptions() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println("---"); pw.println("# The path where your remote domain files reside."); pw.println(REMOTE_DOMAIN_ROOT_KEY + ": # FILL THIS IN!!!"); pw.println(); pw.println("# The File Ops Factory lets Curly know where to retrieve remote data from."); pw.println("# If you're running over NFS or something like that, leave this alone."); pw.println("# If you are using Hadoop, switch to the HdfsFileOpsFactory."); pw.println(FILE_OPS_FACTORY_KEY + ": " + LocalPartitionRemoteFileOps.Factory.class.getName()); pw.println("#" + FILE_OPS_FACTORY_KEY + ": " + HdfsPartitionRemoteFileOps.Factory.class.getName()); pw.println(); pw.println("# This allows partitions up to 1TB in size. If you don't need"); pw.println("# them that big, try reducing this value to 4294967296 (4GB)"); pw.println("# to reduce the offset size to 4 bytes."); pw.println(MAX_ALLOWED_PART_SIZE_KEY + ": " + (1L << 40)); pw.println(); pw.println("# The class name of the hasher you want to use. You should only"); pw.println("# need to adjust this if you have very particular needs."); pw.println(HASHER_KEY + ": " + Murmur64Hasher.class.getName()); pw.println(); pw.println("# 12-byte hashes are more than sufficient for most people,"); pw.println("# unless you have just tons of keys."); pw.println(KEY_HASH_SIZE_KEY + ": 12"); pw.println(); pw.println("# This setting adjusts the number of bits used for the hash index prefixes."); pw.println("# Reducing this number can reduce memory usage, but increase the size of blocks."); pw.println("# Adjust with caution."); pw.println(HASH_INDEX_BITS_KEY + ": 15"); pw.println(); pw.println("# This value should be set to a number around the size of your"); pw.println("# average value, but not much smaller than 32KB. You can safely"); pw.println("# ignore it in most cases."); pw.println(RECORD_FILE_READ_BUFFER_BYTES_KEY + ": " + (32 * 1024)); pw.println(); pw.println("# Set the number of newest full versions (bases + deltas) to keep on remote storage. 0 means keep all versions."); pw.println(NUM_REMOTE_LEAF_VERSIONS_TO_KEEP + ": " + 0); pw.println(); pw.println("# Optional: compression codec. If no codec is specified,"); pw.println("# no compression will be used. Be sure to verify that compression"); pw.println("# actually helps you! If you are just using arbitrary hashed keys,"); pw.println("# it will probably make things worse!"); pw.println("#" + COMPRESSION_CODEC + ": " + NoCompressionCodec.class.getName()); return sw.toString(); } } private final Domain domain; private final int recordFilePartitionCacheCapacity; private final int offsetNumBytes; private final int recordFileReadBufferBytes; private final Cueball cueballStorageEngine; private final String remoteDomainRoot; private final int keyHashSize; private final PartitionRemoteFileOpsFactory partitionRemoteFileOpsFactory; private final int hashIndexBits; private final Class<? extends CompressionCodec> keyFileCompressionCodecClass; private final int numRemoteLeafVersionsToKeep; private final int valueFoldingCacheCapacity; private final BlockCompressionCodec blockCompressionCodec; private final int compressedBlockSizeThreshold; private final int offsetInBlockNumBytes; public Curly(int keyHashSize, Hasher hasher, long maxAllowedPartSize, int hashIndexBits, int recordFileReadBufferBytes, String remoteDomainRoot, PartitionRemoteFileOpsFactory partitionRemoteFileOpsFactory, Class<? extends CompressionCodec> keyFileCompressionCodecClass, Domain domain, int numRemoteLeafVersionsToKeep, int valueFoldingCacheCapacity, int keyFilePartitionCacheCapacity, int recordFilePartitionCacheCapacity, BlockCompressionCodec blockCompressionCodec, int compressedBlockSizeThreshold, int offsetInBlockNumBytes) { this.keyHashSize = keyHashSize; this.hashIndexBits = hashIndexBits; this.recordFileReadBufferBytes = recordFileReadBufferBytes; this.remoteDomainRoot = remoteDomainRoot; this.partitionRemoteFileOpsFactory = partitionRemoteFileOpsFactory; this.keyFileCompressionCodecClass = keyFileCompressionCodecClass; this.domain = domain; this.numRemoteLeafVersionsToKeep = numRemoteLeafVersionsToKeep; this.valueFoldingCacheCapacity = valueFoldingCacheCapacity; this.recordFilePartitionCacheCapacity = recordFilePartitionCacheCapacity; this.blockCompressionCodec = blockCompressionCodec; this.compressedBlockSizeThreshold = compressedBlockSizeThreshold; this.offsetInBlockNumBytes = offsetInBlockNumBytes; this.offsetNumBytes = (int) (Math.ceil(Math.ceil(Math.log(maxAllowedPartSize) / Math.log(2)) / 8.0)); // Determine size of values in Cueball. If we are using block compression in Curly, // the offsets stored in Cueball are appended with the offset in the block. int cueballValueNumBytes = offsetNumBytes; if (blockCompressionCodec != null) { cueballValueNumBytes += offsetInBlockNumBytes; } this.cueballStorageEngine = new Cueball(keyHashSize, hasher, cueballValueNumBytes, hashIndexBits, remoteDomainRoot, partitionRemoteFileOpsFactory, keyFileCompressionCodecClass, domain, numRemoteLeafVersionsToKeep, keyFilePartitionCacheCapacity); } @Override public Reader getReader(DataDirectoriesConfigurator configurator, int partitionNumber) throws IOException { return new CurlyReader(CurlyReader.getLatestBase(getLocalDir(configurator, partitionNumber)), recordFileReadBufferBytes, cueballStorageEngine.getReader(configurator, partitionNumber), recordFilePartitionCacheCapacity, blockCompressionCodec, offsetNumBytes, offsetInBlockNumBytes); } @Override public Writer getWriter(DomainVersion domainVersion, PartitionRemoteFileOps partitionRemoteFileOps, int partitionNumber) throws IOException { Writer cueballWriter = cueballStorageEngine.getWriter(domainVersion, partitionRemoteFileOps, partitionNumber); return getWriter(domainVersion, partitionRemoteFileOps, partitionNumber, cueballWriter); } // Helper private Writer getWriter(DomainVersion domainVersion, PartitionRemoteFileOps partitionRemoteFileOps, int partitionNumber, Writer keyFileWriter) throws IOException { IncrementalDomainVersionProperties domainVersionProperties = getDomainVersionProperties(domainVersion); OutputStream outputStream = partitionRemoteFileOps.getOutputStream(getName(domainVersion.getVersionNumber(), domainVersionProperties.isBase())); return new CurlyWriter(outputStream, keyFileWriter, offsetNumBytes, valueFoldingCacheCapacity, blockCompressionCodec, compressedBlockSizeThreshold, offsetInBlockNumBytes); } private IncrementalDomainVersionProperties getDomainVersionProperties(DomainVersion domainVersion) throws IOException { IncrementalDomainVersionProperties result; try { result = (IncrementalDomainVersionProperties) domainVersion.getProperties(); } catch (ClassCastException e) { throw new IOException("Failed to load properties of version " + domainVersion); } if (result == null) { throw new IOException("Null properties for version " + domainVersion); } return result; } public static String padVersionNumber(int versionNumber) { return String.format("%05d", versionNumber); } @Override public PartitionUpdater getUpdater(DataDirectoriesConfigurator configurator, int partitionNumber) throws IOException { File localDir = new File(getLocalDir(configurator, partitionNumber)); if (!localDir.exists() && !localDir.mkdirs()) { throw new RuntimeException("Failed to create directory " + localDir.getAbsolutePath()); } return getFastPartitionUpdater(localDir.getAbsolutePath(), partitionNumber); } @Override public Compactor getCompactor(DataDirectoriesConfigurator configurator, int partitionNumber) throws IOException { File localDir = new File(getLocalDir(configurator, partitionNumber)); if (!localDir.exists() && !localDir.mkdirs()) { throw new RuntimeException("Failed to create directory " + localDir.getAbsolutePath()); } return getCompactor(localDir.getAbsolutePath(), partitionNumber); } @Override public Writer getCompactorWriter(DomainVersion domainVersion, PartitionRemoteFileOps fileOps, int partitionNumber) throws IOException { Writer cueballWriter = cueballStorageEngine.getCompactorWriter(domainVersion, fileOps, partitionNumber); return getWriter(domainVersion, fileOps, partitionNumber, cueballWriter); } private Compactor getCompactor(String localDir, int partitionNumber) throws IOException { return new CurlyCompactor(domain, partitionRemoteFileOpsFactory.getPartitionRemoteFileOps(remoteDomainRoot, partitionNumber), localDir, new CurlyCompactingMerger(recordFileReadBufferBytes), new CueballStreamBufferMergeSort.Factory(keyHashSize, offsetNumBytes, hashIndexBits, getCompressionCodec(), null), new ICurlyReaderFactory() { @Override public ICurlyReader getInstance(CurlyFilePath curlyFilePath) throws IOException { // Note: key file reader is null as it will *not* be used return new CurlyReader(curlyFilePath, recordFileReadBufferBytes, null, -1, blockCompressionCodec, offsetNumBytes, offsetInBlockNumBytes); } } ); } private CurlyFastPartitionUpdater getFastPartitionUpdater(String localDir, int partNum) throws IOException { return new CurlyFastPartitionUpdater(domain, partitionRemoteFileOpsFactory.getPartitionRemoteFileOps(remoteDomainRoot, partNum), new CurlyMerger(), new CueballMerger(), keyHashSize, offsetNumBytes, offsetInBlockNumBytes, hashIndexBits, getCompressionCodec(), localDir); } private CompressionCodec getCompressionCodec() throws IOException { try { return keyFileCompressionCodecClass.newInstance(); } catch (Exception e) { throw new IOException(e); } } @Override public Deleter getDeleter(DataDirectoriesConfigurator configurator, int partitionNumber) throws IOException { String localDir = getLocalDir(configurator, partitionNumber); return new CurlyDeleter(localDir); } @Override public ByteBuffer getComparableKey(ByteBuffer key) { return cueballStorageEngine.getComparableKey(key); } @Override public PartitionRemoteFileOpsFactory getPartitionRemoteFileOpsFactory() { return partitionRemoteFileOpsFactory; } private String getLocalDir(DataDirectoriesConfigurator configurator, int partNum) { ArrayList<String> l = new ArrayList<String>(configurator.getDataDirectories()); Collections.sort(l); return l.get(partNum % l.size()) + "/" + domain.getName() + "/" + partNum; } public static int parseVersionNumber(String name) { Matcher matcher = BASE_OR_REGEX_PATTERN.matcher(name); if (!matcher.matches()) { throw new IllegalArgumentException("string " + name + " isn't a path that parseVersionNumber can parse!"); } return Integer.parseInt(matcher.group(1)); } public static SortedSet<CurlyFilePath> getBases(String... dirs) { SortedSet<CurlyFilePath> result = new TreeSet<CurlyFilePath>(); Set<String> paths = FsUtils.getMatchingPaths(BASE_REGEX, dirs); for (String path : paths) { result.add(new CurlyFilePath(path)); } return result; } public static SortedSet<CurlyFilePath> getDeltas(String... dirs) { SortedSet<CurlyFilePath> result = new TreeSet<CurlyFilePath>(); Set<String> paths = FsUtils.getMatchingPaths(DELTA_REGEX, dirs); for (String path : paths) { result.add(new CurlyFilePath(path)); } return result; } public static String getName(int versionNumber, boolean base) { String s = padVersionNumber(versionNumber) + "."; if (base) { s += "base"; } else { s += "delta"; } return s + ".curly"; } public static String getName(DomainVersion domainVersion) throws IOException { return getName(domainVersion.getVersionNumber(), IncrementalDomainVersionProperties.isBase(domainVersion)); } @Override public String toString() { return "Curly [compressionCodecClass=" + keyFileCompressionCodecClass + ", cueballStorageEngine=" + cueballStorageEngine + ", domainName=" + domain.getName() + ", fileOpsFactory=" + partitionRemoteFileOpsFactory + ", hashIndexBits=" + hashIndexBits + ", keyHashSize=" + keyHashSize + ", offsetNumBytes=" + offsetNumBytes + ", recordFileReadBufferBytes=" + recordFileReadBufferBytes + ", remoteDomainRoot=" + remoteDomainRoot + ", numRemoteLeafVersionsToKeep=" + numRemoteLeafVersionsToKeep + ", valueFoldingCacheSize=" + valueFoldingCacheCapacity + ", blockCompressionCodec=" + blockCompressionCodec + ", compressedBlockSizeThreshold=" + compressedBlockSizeThreshold + ", offsetInBlockNumBytes=" + offsetInBlockNumBytes + "]"; } @Override public RemoteDomainVersionDeleter getRemoteDomainVersionDeleter() throws IOException { return new CurlyRemoteDomainVersionDeleter(domain, remoteDomainRoot, partitionRemoteFileOpsFactory); } @Override public RemoteDomainCleaner getRemoteDomainCleaner() throws IOException { return new CurlyRemoteDomainCleaner(domain, numRemoteLeafVersionsToKeep); } @Override public DomainVersionPropertiesSerialization getDomainVersionPropertiesSerialization() { return new IncrementalDomainVersionProperties.Serialization(); } }
true
72d2e237b29f1521a0a466cc3d23a2e76e0e6a8d
Java
An-Dang/ContinuITy
/continuity.cli/src/main/java/org/continuity/cli/commands/GlobalCommands.java
UTF-8
5,509
2.296875
2
[ "Apache-2.0" ]
permissive
package org.continuity.cli.commands; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.continuity.cli.config.PropertiesProvider; import org.continuity.cli.manage.CliContextManager; import org.continuity.cli.manage.Shorthand; import org.jline.utils.AttributedString; import org.jline.utils.AttributedStyle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.shell.ExitRequest; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import org.springframework.shell.standard.ShellOption; import org.springframework.shell.standard.commands.Quit; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * @author Henning Schulz * */ @ShellComponent public class GlobalCommands implements Quit.Command { private static final String DEFAULT_VALUE = "$DEFAULT$"; @Autowired private PropertiesProvider propertiesProvider; @Autowired private CliContextManager contextManager; @Autowired private RestTemplate restTemplate; @Autowired private ObjectMapper mapper; @ShellMethod(key = { "props" }, value = "Loads a properties file or shows the current content.") public String loadProperties(@ShellOption(help = "If not set, the current content is printed.", defaultValue = DEFAULT_VALUE) String path) throws FileNotFoundException, IOException { if (DEFAULT_VALUE.equals(path)) { return "Properties at " + propertiesProvider.getPath() + ":\n" + propertiesProvider.get().toString(); } else { propertiesProvider.init(path); new File(propertiesProvider.get().getProperty(PropertiesProvider.KEY_WORKING_DIR)).mkdirs(); return "Successfully loaded the properties file. Content is:\n" + propertiesProvider.get(); } } @ShellMethod(key = { "props-store", "props-save" }, value = "Stores the current properties to a file. Will be automatically done when exiting with \"exit\"") public String storeProperties() throws FileNotFoundException, IOException { propertiesProvider.save(); return "Successfully stored the properties."; } @ShellMethod(key = { "working-directory", "wd" }, value = "Sets the working directory, where files are stored.") public String setWorkingDir(@ShellOption(help = "If not set, the current working directory is printed.", defaultValue = DEFAULT_VALUE) String path) { String currWd = propertiesProvider.get().getProperty(PropertiesProvider.KEY_WORKING_DIR); if (DEFAULT_VALUE.equals(path)) { return "Current working directory is " + currWd; } else { propertiesProvider.get().put(PropertiesProvider.KEY_WORKING_DIR, path); new File(path).mkdirs(); return "Set working directory. Old one was " + currWd; } } @ShellMethod(key = { "url" }, value = "Sets the URL where ContinuITy is running.") public String setUrl(@ShellOption(help = "If not set, the current url is printed.", defaultValue = DEFAULT_VALUE) String url) { String currUrl = propertiesProvider.get().getProperty(PropertiesProvider.KEY_URL); if (DEFAULT_VALUE.equals(url)) { return "Current url is " + currUrl; } else { propertiesProvider.get().put(PropertiesProvider.KEY_URL, url); return currUrl == null ? "Set the new URL." : "Replaced " + currUrl; } } @ShellMethod(key = { "get" }, value = "Gets an artifact.") public String get(String link) throws JsonProcessingException { ResponseEntity<JsonNode> response = restTemplate.getForEntity(link, JsonNode.class); if (!response.getStatusCode().is2xxSuccessful()) { return "Could not access the link! Response code is " + response.getStatusCode(); } return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()); } @ShellMethod(key = { ".." }, value = "Goes one context up.") public void goUp() { contextManager.removeTopmostContext(); } @ShellMethod(key = { "shorthands" }, value = "Lists all available shorthands.") public AttributedString listShorthands() { List<Shorthand> shorthands = new ArrayList<>(); shorthands.addAll(contextManager.getAllAvailableShorthands().values()); Collections.sort(shorthands); AttributedString description; if (shorthands.isEmpty()) { description = new AttributedString("-"); } else { description = AttributedString.join(new AttributedString("\n "), shorthands.stream().map(this::formatShorthand).collect(Collectors.toList())); } return AttributedString.join(new AttributedString("\n "), new AttributedString("Available Shorthands", AttributedStyle.BOLD), description); } private AttributedString formatShorthand(Shorthand shorthand) { return AttributedString.join(new AttributedString(": "), new AttributedString(shorthand.getShorthandName(), AttributedStyle.BOLD), new AttributedString("Shorthand for '" + shorthand.getCommandName() + "'")); } /** * Overrides the default exit command and stores the properties before exiting. */ @ShellMethod(value = "Exit the shell.", key = { "quit", "exit" }) public void quit() { if (propertiesProvider.isInitialized()) { try { propertiesProvider.save(); } catch (IOException e) { e.printStackTrace(); } } throw new ExitRequest(); } }
true
41586429c4aa0e761d7f412da9767bf9f474f829
Java
rayhan-ferdous/code2vec
/codebase/dataset/t1/2247_frag1.java
UTF-8
1,538
2.578125
3
[]
no_license
bytes = s.getBytes(); } bytes = decode(bytes, 0, bytes.length, options); if (bytes != null && bytes.length >= 4) { int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream(bytes); gzis = new java.util.zip.GZIPInputStream(bais); while ((length = gzis.read(buffer)) >= 0) { baos.write(buffer, 0, length); } bytes = baos.toByteArray(); } catch (java.io.IOException e) { } finally { try { baos.close(); } catch (Exception e) { } try { gzis.close(); } catch (Exception e) { } try { bais.close(); } catch (Exception e) { } } } } return bytes; }
true
116c557814236b10828348ee7c6dcccbb79bc7e7
Java
JASantacruz/ISOFT2-2021-C03
/Presentacion/src/test/java/Presentacion/IU_CocineroTest.java
UTF-8
189
1.5625
2
[]
no_license
package Presentacion; import static org.junit.Assert.*; import org.junit.Test; public class IU_CocineroTest { @Test public void test() { IU_Cocinero ioCoci=new IU_Cocinero(); } }
true
ea51989f4649ee537ec75ec07506f0e6f278ffb3
Java
chennh/app-web-demo
/src/main/java/com/vma/demo/web/app/router/SystemRouter.java
UTF-8
557
1.976563
2
[]
no_license
package com.vma.demo.web.app.router; import com.vma.web.mvc.router.CenterRouter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * DESCRIPTION * * @author: chennaihua * @version: 1.created by chennaihua on 2019/8/7. */ @Controller @RequestMapping(value = SystemRouter.BASE_ROUTER) public class SystemRouter extends CenterRouter { static final String BASE_ROUTER = "/app/system/"; @Override protected String baseRouterMapping() { return BASE_ROUTER; } }
true
9064ba1b96a874fe463abc08e3946b41861134ea
Java
BAMSU/testWeb
/src/main/java/meal/model/mealDAO.java
UTF-8
256
1.90625
2
[]
no_license
package meal.model; import java.util.List; public interface mealDAO { public List getMealList(int idx); public List getMealList2(int idx); public int insertM(mealDTO dto); public int updateM(mealDTO dto); public int deleteM(int idx); }
true
dda6b7731e7192c1f459e80b807eff0dc56ca692
Java
Arielce/Maintenance
/library/src/main/java/ren/solid/library/widget/RectImageView.java
UTF-8
593
2.3125
2
[]
no_license
package ren.solid.library.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; public class RectImageView extends ImageView { public RectImageView(Context context) { super(context); } public RectImageView(Context context, AttributeSet attrs) { super(context, attrs); } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); this.setMeasuredDimension(this.getMeasuredWidth(), this.getMeasuredWidth()/2); } }
true
9bb44d414697ef438cf3a7dd1255e0f7b23668d4
Java
projectcsc571/MyselfZura
/Person.java
UTF-8
928
2.859375
3
[]
no_license
package com.example.e_resumemobileapplication; public class Person { Contact detail; String[] educations; String[] skills; String[] awards; String[] hobbies; String[] languages; String[] experiences; String imagePath; public Person() {} public Person(String name,String phone,String email,int age,String[] educations,String[] skills,String[] awards,String[] hobbies,String[] languages,String[] experiences,String imagePath) { this.detail = new Contact(name,email,phone,age); for(int i=0; i< 4; i++) { this.educations[i] = educations[i]; this.skills[i] = skills[i]; this.awards[i] = awards[i]; this.hobbies[i] = hobbies[i]; this.languages[i] = languages[i]; this.experiences[i] = experiences[i]; } this.imagePath = imagePath; } }
true
bbd513f0eda84bbe87f60c732d0c7e3b9197a49f
Java
gonr1001/diamant
/src/dInterface/dAffectation/EventsDlg.java
UTF-8
5,167
2.046875
2
[]
no_license
//package dInterface.dAffectation; // ///** // * <p>Title: Diamant</p> // * <p>Description: timetable construction</p> // * <p>Copyright: Copyright (c) 2002</p> // * <p>Company: UdeS</p> // * @author unascribed // * @version 1.0 // */ // //import java.awt.event.ActionEvent; // //import javax.swing.JFrame; // //import dConstants.DConst; //import developer.DxFlags; //import dInterface.DlgIdentification; //import dInterface.dAssignementDlgs.DxEditEventDlg; //import dInterface.dUtil.ButtonsPanel; //import dInterface.dUtil.DxTools; //import dInterface.dUtil.TwoButtonsPanel; //import dInternal.DModel; //import eLib.exit.dialog.InformationDlg; // //public class EventsDlg extends EventsDlgInterface implements DlgIdentification { // private String[] _arrowsNames = { DConst.TO_RIGHT, DConst.TO_LEFT, }; // // // private boolean _withRoomFunction; // // /** // * Constructor // * // * @param dApplic // * The application // * @param String // * the title of the dialog // * @boolean if false use EditActivityDld (the old dialog without room // * function and room state) else if true use EditEventDlg (the new // * dialog with room function and room state) // */ //// public EventsDlg(DApplication dApplic) { //// super(dApplic, DConst.EVENTS_DLG_TITLE); //// // _withRoomFunction = withRoomFunction; //// buildArrowButtons(true); //// initialize(); //// }// end method // // public EventsDlg(JFrame jFrame, DModel dModel) { // super(jFrame, dModel, DConst.EVENTS_DLG_TITLE); // // _withRoomFunction = withRoomFunction; // buildArrowButtons(true); // initialize(); // }// end method // // public ButtonsPanel setButtons() { // // _applyPanel // String[] a = { DConst.BUT_APPLY, DConst.BUT_CLOSE }; // _buttonsPanel = new TwoButtonsPanel(this, a); // // Setting the button APPLY disable // _buttonsPanel.setFirstDisable(); // return _buttonsPanel; // // } // // /** // * build buttom to use in the dialog // */ // public void buildArrowButtons(boolean enableArrows) { // _leftArrowsPanel = DxTools.arrowsPanel(this, "left", _arrowsNames, // enableArrows); // _rightArrowsPanel = DxTools.arrowsPanel(this, "right", _arrowsNames, // enableArrows); // } // // public void actionPerformed(ActionEvent e) { // if ((e.getActionCommand().equalsIgnoreCase("left" + _arrowsNames[0])) // || (e.getActionCommand().equalsIgnoreCase("left" // + _arrowsNames[1]))) { // // if "toRight" button // if (e.getActionCommand().equalsIgnoreCase("left" + _arrowsNames[0])) // DxTools.listTransfers(_leftList, _centerList, _leftVector, // _centerVector, 1); // else // DxTools.listTransfers(_centerList, _leftList, _centerVector, // _leftVector, 1); // // _leftLabel.setText(String.valueOf(_leftVector.size())); // _centerLabel.setText(String.valueOf(_centerVector.size())); // _buttonsPanel.setFirstEnable(); // }// end if ( // // (e.getSource().equals(_leftArrowsPanel.getComponent(0)))) || // // (e.getSource().equals(_leftArrowsPanel.getComponent(1)))) ) // // if the source is one of the the _rightArrowsPanel buttons // if ((e.getActionCommand().equalsIgnoreCase("right" + _arrowsNames[0])) // || (e.getActionCommand().equalsIgnoreCase("right" // + _arrowsNames[1]))) { // // if "toRight" button // if (e.getActionCommand() // .equalsIgnoreCase("right" + _arrowsNames[0])) // DxTools.listTransfers(_centerList, _rightList, _centerVector, // _rightVector, 1); // else // DxTools.listTransfers(_rightList, _centerList, _rightVector, // _centerVector, 1); // _rightLabel.setText(String.valueOf(_rightVector.size())); // _centerLabel.setText(String.valueOf(_centerVector.size())); // _buttonsPanel.setFirstEnable(); // }// end if ( // // (e.getSource().equals(_rightArrowsPanel.getComponent(0))) || // // (e.getSource().equals(_rightArrowsPanel.getComponent(1))) ) // // if Button CLOSE is pressed // if (e.getActionCommand().equals(DConst.BUT_CLOSE)) // dispose(); // // if Button APPLY is pressed // if (e.getActionCommand().equals(DConst.BUT_APPLY)) { // setUnities(); // _dModel.changeInDModel( // this.idDlgToString()); // _buttonsPanel.setFirstDisable(); // }// end if Button APPLY // }// end method // // /** // * // */ // protected void doubleClicMouseProcess() { // if (!_buttonsPanel.isFirstEnable()) { // // if (this._withRoomFunction) // if (DxFlags.newEditEventDlg) { //// new DxEditEventDlg(_jDialog, _dApplic, //// (String) selectedItems[0], false); // new DxEditEventDlg(_jDialog, _dModel, // (String) selectedItems[0], false); // } //// } else { //// new EditEventDlg(_jDialog, _dApplic, (String) selectedItems[0], //// this, false); //// } // // // else // // new EditActivityDlg(_jDialog,_dApplic, (String)selectedItems[0], // // this, false); // _buttonsPanel.setFirstDisable(); // } else { // new InformationDlg(_jDialog, "Appliquer ou fermer pour continuer", // "Operation interdite"); // } // } // end doubleClicMouseProcess // // public String idDlgToString() { // return this.getClass().toString(); // } // //}// end EventsDlg
true
cc4b0781999f6e7afbee259794d26ab6d5666d05
Java
ncarenton/exercices
/src/test/java/com/cracking_the_coding_itw/arrays_and_strings/MatricSet0Test.java
UTF-8
783
2.59375
3
[]
no_license
package com.cracking_the_coding_itw.arrays_and_strings; import org.junit.Assert; import org.junit.Test; import com.craking_the_coding_itw.arrays_and_strings.MatrixSet0; public class MatricSet0Test { private MatrixSet0 matrixSet0 = new MatrixSet0(); @Test public void test() { int[][] matrix = new int[3][4]; matrix[0] = new int[] { 4, 1, 2, 2 }; matrix[1] = new int[] { 0, 4, 5, 3 }; matrix[2] = new int[] { 6, 7, 8, 4 }; int[][] expectedMatrix = new int[3][3]; expectedMatrix[0] = new int[] { 0, 1, 2, 2 }; expectedMatrix[1] = new int[] { 0, 0, 0, 0 }; expectedMatrix[2] = new int[] { 0, 7, 8, 4 }; matrixSet0.set0(matrix); Assert.assertArrayEquals(expectedMatrix, matrix); } }
true
a75fa338362a0083bd7104270f87b30f132b67bf
Java
SimonPDooley/Assignment13
/Assignment13/src/main/java/com/coderscampus/assignment13/repository/AccountRepository.java
UTF-8
613
2.203125
2
[]
no_license
package com.coderscampus.assignment13.repository; import java.util.List; import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.coderscampus.assignment13.domain.Account; import com.coderscampus.assignment13.domain.User; @Repository public interface AccountRepository extends JpaRepository<Account, Long>{ Set<Account> findByUsersIn(List<User> users); @Query("select a from Account a where accountId = :accountId") Account findAccountById(Long accountId); }
true
67353a6ed20a73537f5709da0e1319e45fc9eef2
Java
SuperCraig/AndroidFile
/WaveLoadingView-master/sample/src/main/java/me/itangqi/waveloadingview/UDPSender.java
UTF-8
5,297
2.6875
3
[ "Apache-2.0" ]
permissive
package me.itangqi.waveloadingview; /** * Created by Craig on 2017/11/2. */ import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.HashMap; public class UDPSender extends AsyncTask<HashMap, Integer, String>{ public UDPUtils delegate = null; /** * Function for send an UDP datagram. * * @param params msg, ip and port for sending * @return */ @Override protected String doInBackground(HashMap... params) { //Retrieve params HashMap<String, Object> p = params[0]; String testServer = (String) p.get("ip"); String udpMsg = (String) p.get("msg"); udpMsg += "\r\n\0"; Integer port = (int) p.get("port"); boolean broadcast = (boolean) p.get("bdc"); InetAddress serverAddr = null; DatagramSocket ds = null; DatagramPacket dp = null; Log.v("BROADCAST SEND", String.valueOf(broadcast) ); try { serverAddr = InetAddress.getByName(testServer); } catch (UnknownHostException e) { e.printStackTrace(); } try { ds = new DatagramSocket(); ds.setBroadcast(broadcast); } catch (SocketException e) { e.printStackTrace(); } if (broadcast) { try { dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), getBroadcastAddress(), port); } catch (Exception e){} /*catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }*/ } else { dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, port); } try { Log.v("Sending UDP", "Sending udp pckg, msg: " + udpMsg + " " + testServer + ":" + String.valueOf(port)); ds.send(dp); } catch (IOException e) { e.printStackTrace(); } ds.close(); return "TX|" +testServer + ":" + p.get("port") + "-> " + udpMsg.substring(0, udpMsg.indexOf("\r") ); } @Override protected void onPreExecute() { } @Override protected void onPostExecute(String result) { delegate.processFinish(result); } public InetAddress getBroadcastAddress() { InetAddress broadcastAddress = null; try { Enumeration<NetworkInterface> networkInterface = NetworkInterface .getNetworkInterfaces(); while (broadcastAddress == null && networkInterface.hasMoreElements()) { NetworkInterface singleInterface = networkInterface .nextElement(); String interfaceName = singleInterface.getName(); if (interfaceName.contains("wlan0") || interfaceName.contains("eth0")) { for (InterfaceAddress infaceAddress : singleInterface .getInterfaceAddresses()) { broadcastAddress = infaceAddress.getBroadcast(); if (broadcastAddress != null) { break; } } } } } catch (SocketException e) { e.printStackTrace(); } return broadcastAddress; } /* public static InetAddress getNetworkLocalBroadcastAddressdAsInetAddress() throws IOException { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); if(Build.VERSION.SDK_INT < 9) { if(!intf.getInetAddresses().nextElement().isLoopbackAddress()){ byte[] quads = intf.getInetAddresses().nextElement().getAddress(); quads[0] = (byte)255; quads[1] = (byte)255; return InetAddress.getByAddress(quads); } }else{ if(!intf.isLoopback()){ List<InterfaceAddress> intfaddrs = intf.getInterfaceAddresses(); return intfaddrs.get(0).getBroadcast(); //return first IP address } } } return null; }*/ /*public static String getBroadcast() throws SocketException { System.setProperty("java.net.preferIPv4Stack", "true"); for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements();) { NetworkInterface ni = niEnum.nextElement(); if (!ni.isLoopback()) { for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) { return interfaceAddress.getBroadcast().toString().substring(1); } } } return null; }*/ }
true
c287013d599e09f849dbf071a1df4fc912c1a3ea
Java
off/FreezeServer
/src/com/glenjendary/freeze/events/FreezeServer.java
UTF-8
3,717
2.671875
3
[]
no_license
package com.glenjendary.freeze.events; /* Freeze Created by Glenjendary on 4/07/2017. */ import com.glenjendary.freeze.Main; import com.glenjendary.freeze.commands.Freeze; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.*; public class FreezeServer implements Listener { private Main plugin; public FreezeServer(Main plugin) { this.plugin = plugin; } @EventHandler public void onPlayerChat (AsyncPlayerChatEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } Player player = event.getPlayer(); if (Freeze.isFrozen) { if (!(player.hasPermission("sfreeze.bypass"))){ player.sendMessage(ChatColor.RED + "The server is currently frozen!"); event.setCancelled(true); } else if (player.hasPermission("sfreeze.bypass")) { event.setCancelled(false); } } else if (!(Freeze.isFrozen)) { event.setCancelled(false); } } public void onPlayerMove (PlayerMoveEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } Player player = event.getPlayer(); if (Freeze.isFrozen) { if (!(player.hasPermission("sfreeze.bypass"))){ player.sendMessage(ChatColor.RED + "The server is currently frozen!"); event.setCancelled(true); } else if (player.hasPermission("sfreeze.bypass")) { event.setCancelled(false); } } else if (!(Freeze.isFrozen)) { event.setCancelled(false); } } public void onPlayerDropItem (PlayerDropItemEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } Player player = event.getPlayer(); if (Freeze.isFrozen) { if (!(player.hasPermission("sfreeze.bypass"))) { player.sendMessage(ChatColor.RED + "The server is currently frozen!"); event.setCancelled(true); } else if (player.hasPermission("sfreeze.bypass")) { event.setCancelled(false); } } else if (!(Freeze.isFrozen)) { event.setCancelled(false); } } public void onPlayerBlockBreak (BlockBreakEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } Player player = event.getPlayer(); if (Freeze.isFrozen) { if (!(player.hasPermission("sfreeze.bypass"))){ player.sendMessage(ChatColor.RED + "The server is currently frozen!"); event.setCancelled(true); } else if (player.hasPermission("sfreeze.bypass")) { event.setCancelled(false); } } else if (!(Freeze.isFrozen)) { event.setCancelled(false); } } public void onPlayerInteract (PlayerInteractEvent event) { if (!(event.getPlayer() instanceof Player)) { return; } Player player = event.getPlayer(); if (Freeze.isFrozen) { if (!(player.hasPermission("sfreeze.bypass"))){ player.sendMessage(ChatColor.RED + "The server is currently frozen!"); event.setCancelled(true); } else if (player.hasPermission("sfreeze.bypass")) { event.setCancelled(false); } } else if (!(Freeze.isFrozen)) { event.setCancelled(false); } } }
true
e7e5ae353c8a88134dc9dd61cb7be310e4a2b3dd
Java
arthmalbeck/console_text_rpg
/src/view/TelaBatalha.java
ISO-8859-1
16,319
2.515625
3
[]
no_license
package view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.text.ParseException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import controller.Batalha; //import controller.BatalhaController; //import controller.CriaJogadorController; import personagem.Inimigo; import personagem.Jogador; import personagem.Sexo; import sistema.MontanhaSagrada; public class TelaBatalha extends JFrame { public static final Dimension TAMANHO = UIUtil.getFullScreenSize(); // private Jogador jogador; // private Inimigo inimigo; private JPanel painelPrincipal; private JPanel painelJogador; private JPanel painelInimigo; private JPanel painelAcoes; private JButton btnAtacar; private JButton btnDefender; private JButton btnCurar; private JLabel lblIcone; private JLabel lblImgJogador; private JLabel lblImgVidaJogador; private JLabel lblVidaJogador; private JLabel lblImgDefesaJogador; private JLabel lblDefesaJogador; private JLabel lblImgAtaqueJogador; private JLabel lblAtaqueJogador; private JLabel lblImgJogadorDefendendo; private JLabel lblJogadorDefendendo; private JLabel lblImgInimigo; private JLabel lblImgVidaInimigo; private JLabel lblVidaInimigo; private JLabel lblImgDefesaInimigo; private JLabel lblDefesaInimigo; private JLabel lblImgAtaqueInimigo; private JLabel lblAtaqueInimigo; private JLabel lblImgInimigoDefendendo; private JLabel lblInimigoDefendendo; private JLabel lblJogador; private JLabel lblInimigo; private JLabel lblAcoes; private Batalha controller; public TelaBatalha(TelaPrincipal telaPrincipal,int numInimigo) throws ParseException { Inimigo inimigo = Batalha.geraOponente(numInimigo); controller = new Batalha(this, telaPrincipal, numInimigo); // Mudando o icone da aplicacao ImageIcon imgLogin = new ImageIcon("assets\\icone2.png"); setIconImage(imgLogin.getImage()); lblIcone = new JLabel(imgLogin); setTitle("A Montanha Sagrada"); setSize(TAMANHO); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); painelPrincipal = new JPanel(); setContentPane(painelPrincipal); painelPrincipal.setBackground(Color.decode("#BAAC87")); painelPrincipal.setLayout(new BorderLayout()); // Inicio Jogador painelJogador = new JPanel(); painelJogador.setLayout(null); painelJogador.setSize(680, 460); painelJogador.setLocation(0, 0); painelJogador.setBorder(javax.swing.BorderFactory.createEtchedBorder()); painelJogador.setBackground(null); painelPrincipal.add(painelJogador); lblJogador = new JLabel(MontanhaSagrada.jogador.getNome() + " (" + MontanhaSagrada.jogador.getClasse() + ")"); lblJogador.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblJogador.setSize(200, 20); lblJogador.setLocation(300, 30); painelJogador.add(lblJogador); // Inicio Img Jogador lblImgJogador = new JLabel(); lblImgJogador.setSize(200, 300); lblImgJogador.setLocation(40, 100); if (MontanhaSagrada.jogador.getSexo().equals(Sexo.FEMININO) == true) { ImageIcon imgJogador = new ImageIcon("assets\\jogador.png"); imgJogador.setImage( imgJogador.getImage().getScaledInstance(lblImgJogador.getWidth(), lblImgJogador.getHeight(), 1)); lblImgJogador.setIcon(imgJogador); painelJogador.add(lblImgJogador); } else { ImageIcon imgJogador = new ImageIcon("assets\\inimigo.png"); imgJogador.setImage( imgJogador.getImage().getScaledInstance(lblImgJogador.getWidth(), lblImgJogador.getHeight(), 1)); lblImgJogador.setIcon(imgJogador); painelJogador.add(lblImgJogador); } // Fim Img Jogador // Inicio Vida Jogador lblImgVidaJogador = new JLabel(); lblImgVidaJogador.setSize(50, 50); lblImgVidaJogador.setLocation(320, 120); ImageIcon imgHeart = new ImageIcon("assets\\heart.png"); imgHeart.setImage( imgHeart.getImage().getScaledInstance(lblImgVidaJogador.getWidth(), lblImgVidaJogador.getHeight(), 1)); lblImgVidaJogador.setIcon(imgHeart); painelJogador.add(lblImgVidaJogador); lblVidaJogador = new JLabel(Integer.toString(MontanhaSagrada.jogador.getHp())); lblVidaJogador.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblVidaJogador.setSize(200, 20); lblVidaJogador.setLocation(385, 135); painelJogador.add(lblVidaJogador); // Fim Vida Jogador // Inicio Defesa Jogador lblImgDefesaJogador = new JLabel(); lblImgDefesaJogador.setSize(50, 50); lblImgDefesaJogador.setLocation(320, 200); ImageIcon imgEscudo = new ImageIcon("assets\\escudo.png"); imgEscudo.setImage(imgEscudo.getImage().getScaledInstance(lblImgDefesaJogador.getWidth(), lblImgDefesaJogador.getHeight(), 1)); lblImgDefesaJogador.setIcon(imgEscudo); painelJogador.add(lblImgDefesaJogador); lblDefesaJogador = new JLabel(Integer.toString(MontanhaSagrada.jogador.getDef())); lblDefesaJogador.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblDefesaJogador.setSize(200, 20); lblDefesaJogador.setLocation(385, 215); painelJogador.add(lblDefesaJogador); // Fim Defesa Jogador // Inicio Ataque Jogador lblImgAtaqueJogador = new JLabel(); lblImgAtaqueJogador.setSize(50, 50); lblImgAtaqueJogador.setLocation(320, 280); ImageIcon imgAtaque = new ImageIcon("assets\\ataque2.png"); imgAtaque.setImage(imgAtaque.getImage().getScaledInstance(lblImgAtaqueJogador.getWidth(), lblImgAtaqueJogador.getHeight(), 1)); lblImgAtaqueJogador.setIcon(imgAtaque); painelJogador.add(lblImgAtaqueJogador); lblAtaqueJogador = new JLabel(Integer.toString(MontanhaSagrada.jogador.getAtk())); lblAtaqueJogador.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblAtaqueJogador.setSize(200, 20); lblAtaqueJogador.setLocation(385, 295); painelJogador.add(lblAtaqueJogador); // Fim Ataque Jogador // Inicio Defendendo Jogador lblImgJogadorDefendendo = new JLabel(); lblImgJogadorDefendendo.setSize(50, 50); lblImgJogadorDefendendo.setLocation(320, 360); // Fim Jogador // Inicio Inimigo painelInimigo = new JPanel(); painelInimigo.setLayout(null); painelInimigo.setSize(785, 460); painelInimigo.setLocation(681, 0); painelInimigo.setBorder(javax.swing.BorderFactory.createEtchedBorder()); painelInimigo.setBackground(null); painelPrincipal.add(painelInimigo); lblInimigo = new JLabel(inimigo.getNome()); lblInimigo.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblInimigo.setSize(300, 20); lblInimigo.setLocation(315, 30); painelInimigo.add(lblInimigo); // Inicio Img Inimigo lblImgInimigo = new JLabel(); lblImgInimigo.setSize(200, 300); lblImgInimigo.setLocation(40, 100); ImageIcon imgInimigo = new ImageIcon(inimigo.getPathImagem()); imgInimigo.setImage( imgInimigo.getImage().getScaledInstance(lblImgInimigo.getWidth(), lblImgInimigo.getHeight(), 1)); lblImgInimigo.setIcon(imgInimigo); painelInimigo.add(lblImgInimigo); // Fim Img Inimigo // Inicio Vida Inimigo lblImgVidaInimigo = new JLabel(); lblImgVidaInimigo.setSize(50, 50); lblImgVidaInimigo.setLocation(320, 120); imgHeart.setImage( imgHeart.getImage().getScaledInstance(lblImgVidaInimigo.getWidth(), lblImgVidaInimigo.getHeight(), 1)); lblImgVidaInimigo.setIcon(imgHeart); painelInimigo.add(lblImgVidaInimigo); lblVidaInimigo = new JLabel(Integer.toString(inimigo.getHp())); lblVidaInimigo.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblVidaInimigo.setSize(200, 20); lblVidaInimigo.setLocation(385, 135); painelInimigo.add(lblVidaInimigo); // Fim Vida Inimigo // Inicio Defesa Inimigo lblImgDefesaInimigo = new JLabel(); lblImgDefesaInimigo.setSize(50, 50); lblImgDefesaInimigo.setLocation(320, 200); imgEscudo.setImage(imgEscudo.getImage().getScaledInstance(lblImgDefesaInimigo.getWidth(), lblImgDefesaInimigo.getHeight(), 1)); lblImgDefesaInimigo.setIcon(imgEscudo); painelInimigo.add(lblImgDefesaInimigo); lblDefesaInimigo = new JLabel(Integer.toString(inimigo.getDef())); lblDefesaInimigo.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblDefesaInimigo.setSize(200, 20); lblDefesaInimigo.setLocation(385, 215); painelInimigo.add(lblDefesaInimigo); // Fim Defesa Inimigo // Inicio Defendendo Inimigo lblImgAtaqueInimigo = new JLabel(); lblImgAtaqueInimigo.setSize(50, 50); lblImgAtaqueInimigo.setLocation(320, 280); // ImageIcon imgAtaque = new ImageIcon("assets\\ataque.png"); imgAtaque.setImage(imgAtaque.getImage().getScaledInstance(lblImgAtaqueInimigo.getWidth(), lblImgAtaqueInimigo.getHeight(), 1)); lblImgAtaqueInimigo.setIcon(imgAtaque); painelInimigo.add(lblImgAtaqueInimigo); lblAtaqueInimigo = new JLabel(Integer.toString(inimigo.getAtk())); lblAtaqueInimigo.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblAtaqueInimigo.setSize(200, 20); lblAtaqueInimigo.setLocation(385, 295); painelInimigo.add(lblAtaqueInimigo); // Fim Defendendo Inimigo // Inicio Defendendo Inimigo lblImgInimigoDefendendo = new JLabel(); lblImgInimigoDefendendo.setSize(50, 50); lblImgInimigoDefendendo.setLocation(320, 360); // Fim Inimigo // Inicio Acoes painelAcoes = new JPanel(); painelAcoes.setLayout(null); painelAcoes.setSize(50, 50); painelAcoes.setLocation(0, 250); painelAcoes.setBackground(null); painelAcoes.setBorder(javax.swing.BorderFactory.createEtchedBorder()); painelPrincipal.add(painelAcoes); lblAcoes = new JLabel("AES"); lblAcoes.setFont(new Font("Tahoma", Font.PLAIN, 22)); lblAcoes.setSize(200, 20); lblAcoes.setLocation(645, 495); painelAcoes.add(lblAcoes); // ActionListener atk = new BatalhaController(this, jogador); btnAtacar = new JButton("Atacar"); btnAtacar.setName("btnAtacar"); btnAtacar.addActionListener(controller); btnAtacar.setSize(100, 50); btnAtacar.setLocation(500, 570); painelAcoes.add(btnAtacar); // ActionListener curar = new BatalhaController(this, jogador); btnCurar = new JButton("Inventario"); btnCurar.setName("btnCurar"); btnCurar.addActionListener(controller); btnCurar.setSize(100, 50); btnCurar.setLocation(750, 570); painelAcoes.add(btnCurar); // Fim Acoes JLabel lblUniversidade = new JLabel("Engenharia de Software - UNIPAMPA"); JPanel jp = new JPanel(); jp.setLayout(new FlowLayout()); jp.add(lblUniversidade); jp.setBackground(null); jp.setBorder(javax.swing.BorderFactory.createEtchedBorder()); painelPrincipal.add(jp, BorderLayout.SOUTH); } public void notifyIniciativa(int iniciativaJogador, int iniciativaInimigo, String iniciativa) { JOptionPane.showMessageDialog(this, "Sorteando um valor de iniciativa para ver quem comea a batalha\n" + "Iniciativa do Jogador: " + iniciativaJogador + "\nIniciativa do Inimigo: " + iniciativaInimigo + "\n" + iniciativa, "Sorteio de Iniciativa", JOptionPane.INFORMATION_MESSAGE, null); } public void bindJogador() throws ParseException { } public void bindInimigo() throws ParseException { } public JPanel getPainelPrincipal() { return painelPrincipal; } public void setPainelPrincipal(JPanel painelPrincipal) { this.painelPrincipal = painelPrincipal; } public JPanel getPainelJogador() { return painelJogador; } public void setPainelJogador(JPanel painelJogador) { this.painelJogador = painelJogador; } public JPanel getPainelInimigo() { return painelInimigo; } public void setPainelInimigo(JPanel painelInimigo) { this.painelInimigo = painelInimigo; } public JPanel getPainelAcoes() { return painelAcoes; } public void setPainelAcoes(JPanel painelAcoes) { this.painelAcoes = painelAcoes; } public JButton getBtnAtacar() { return btnAtacar; } public void setBtnAtacar(JButton btnAtacar) { this.btnAtacar = btnAtacar; } public JButton getBtnDefender() { return btnDefender; } public void setBtnDefender(JButton btnDefender) { this.btnDefender = btnDefender; } public JButton getBtnCurar() { return btnCurar; } public void setBtnCurar(JButton btnCurar) { this.btnCurar = btnCurar; } public JLabel getLblIcone() { return lblIcone; } public void setLblIcone(JLabel lblIcone) { this.lblIcone = lblIcone; } public JLabel getLblImgJogador() { return lblImgJogador; } public void setLblImgJogador(JLabel lblImgJogador) { this.lblImgJogador = lblImgJogador; } public JLabel getLblImgVidaJogador() { return lblImgVidaJogador; } public void setLblImgVidaJogador(JLabel lblImgVidaJogador) { this.lblImgVidaJogador = lblImgVidaJogador; } public JLabel getLblVidaJogador() { return lblVidaJogador; } public void setLblVidaJogador(JLabel lblVidaJogador) { this.lblVidaJogador = lblVidaJogador; } public JLabel getLblImgDefesaJogador() { return lblImgDefesaJogador; } public void setLblImgDefesaJogador(JLabel lblImgDefesaJogador) { this.lblImgDefesaJogador = lblImgDefesaJogador; } public JLabel getLblDefesaJogador() { return lblDefesaJogador; } public void setLblDefesaJogador(JLabel lblDefesaJogador) { this.lblDefesaJogador = lblDefesaJogador; } public JLabel getLblImgAtaqueJogador() { return lblImgAtaqueJogador; } public void setLblImgAtaqueJogador(JLabel lblImgAtaqueJogador) { this.lblImgAtaqueJogador = lblImgAtaqueJogador; } public JLabel getLblAtaqueJogador() { return lblAtaqueJogador; } public void setLblAtaqueJogador(JLabel lblAtaqueJogador) { this.lblAtaqueJogador = lblAtaqueJogador; } public JLabel getLblImgJogadorDefendendo() { return lblImgJogadorDefendendo; } public void setLblImgJogadorDefendendo(JLabel lblImgJogadorDefendendo) { this.lblImgJogadorDefendendo = lblImgJogadorDefendendo; } public JLabel getLblJogadorDefendendo() { return lblJogadorDefendendo; } public void setLblJogadorDefendendo(JLabel lblJogadorDefendendo) { this.lblJogadorDefendendo = lblJogadorDefendendo; } public JLabel getLblImgInimigo() { return lblImgInimigo; } public void setLblImgInimigo(JLabel lblImgInimigo) { this.lblImgInimigo = lblImgInimigo; } public JLabel getLblImgVidaInimigo() { return lblImgVidaInimigo; } public void setLblImgVidaInimigo(JLabel lblImgVidaInimigo) { this.lblImgVidaInimigo = lblImgVidaInimigo; } public JLabel getLblVidaInimigo() { return lblVidaInimigo; } public void setLblVidaInimigo(JLabel lblVidaInimigo) { this.lblVidaInimigo = lblVidaInimigo; } public JLabel getLblImgDefesaInimigo() { return lblImgDefesaInimigo; } public void setLblImgDefesaInimigo(JLabel lblImgDefesaInimigo) { this.lblImgDefesaInimigo = lblImgDefesaInimigo; } public JLabel getLblDefesaInimigo() { return lblDefesaInimigo; } public void setLblDefesaInimigo(JLabel lblDefesaInimigo) { this.lblDefesaInimigo = lblDefesaInimigo; } public JLabel getLblImgAtaqueInimigo() { return lblImgAtaqueInimigo; } public void setLblImgAtaqueInimigo(JLabel lblImgAtaqueInimigo) { this.lblImgAtaqueInimigo = lblImgAtaqueInimigo; } public JLabel getLblAtaqueInimigo() { return lblAtaqueInimigo; } public void setLblAtaqueInimigo(JLabel lblAtaqueInimigo) { this.lblAtaqueInimigo = lblAtaqueInimigo; } public JLabel getLblImgInimigoDefendendo() { return lblImgInimigoDefendendo; } public void setLblImgInimigoDefendendo(JLabel lblImgInimigoDefendendo) { this.lblImgInimigoDefendendo = lblImgInimigoDefendendo; } public JLabel getLblInimigoDefendendo() { return lblInimigoDefendendo; } public void setLblInimigoDefendendo(JLabel lblInimigoDefendendo) { this.lblInimigoDefendendo = lblInimigoDefendendo; } public JLabel getLblJogador() { return lblJogador; } public void setLblJogador(JLabel lblJogador) { this.lblJogador = lblJogador; } public JLabel getLblInimigo() { return lblInimigo; } public void setLblInimigo(JLabel lblInimigo) { this.lblInimigo = lblInimigo; } public JLabel getLblAcoes() { return lblAcoes; } public void setLblAcoes(JLabel lblAcoes) { this.lblAcoes = lblAcoes; } public Batalha getController() { return controller; } public void setController(Batalha controller) { this.controller = controller; } public static Dimension getTamanho() { return TAMANHO; } public void notifyAtaque(String string) { JOptionPane.showMessageDialog(this, string, "Ataque", JOptionPane.INFORMATION_MESSAGE, null); } }
true
6a97f44cefd8c48029b718658bf06e442b52b9bc
Java
asroboy/android_ls
/app/src/main/java/com/lapaksembako/app/SyaratDanKetentuanActivity.java
UTF-8
1,924
1.851563
2
[]
no_license
package com.lapaksembako.app; import android.content.Intent; import android.os.Build; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.lapaksembako.app.action.Core; import com.lapaksembako.app.model.OtherPage; public class SyaratDanKetentuanActivity extends AppCompatActivity { Core core; TextView textViewContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_syarat_dan_ketentuan); ActionBar ab = getSupportActionBar(); ab.setDisplayHomeAsUpEnabled(true); ab.setHomeAsUpIndicator(R.drawable.ic_back_white); core = new Core(); textViewContent = findViewById(R.id.textViewContent); core.getKebijakanPrivasi(new Core.OnCallCompleteListener() { @Override public void onSuccess(Intent data) { OtherPage op = data.getBundleExtra("bundle").getParcelable("page"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (op.getContent() != null) textViewContent.setText(Html.fromHtml(op.getContent(), Html.FROM_HTML_MODE_COMPACT)); } else { if (op.getContent() != null) textViewContent.setText(Html.fromHtml(op.getContent())); } } @Override public void onFailed(Intent data) { } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } }
true
68c36386db0a66f01d35c2be83c31988a279ddf5
Java
Tirtan/semestre3
/projet_tut/eclipse/Projet_S3/src/algopars/Controleur.java
UTF-8
2,698
3.28125
3
[]
no_license
package algopars; import java.util.Set; import algopars.ihm.*; import algopars.metier.*; /** * Classe controleur faisant la passerelle enre la partie métier et l'ihm * @author hugo labbé * @version 1.0, 2018-12-18 * */ public class Controleur { /** * Instance d'une IHMCui * */ private IHMCui ihm; /** * Insantance de Code * */ private Code code; /** * Instance de Interpreteur * */ private Interpreteur inter; /** * Constructeur du controleur passerel avec l'ihm * @param code instance de Code * */ public Controleur( Code code ) { if(System.getProperty("os.name").equalsIgnoreCase("Windows")) this.ihm = new IHMCuiWindows(this); else this.ihm = new IHMCuiUnix(this); this.code = code ; this.inter = new Interpreteur(code, this); } public void lancer(){ ihm.normal(); afficher(code.afficherPseudoCode()); this.inter.lireCode(); choixTracageVariables(); afficher(code.afficherDonnees()); // mode pas a pas /*while(inter.getIndex() < code.getNbLig()){ code.setNumLig(inter.getIndex()); System.out.println("INDEX: " +inter.getIndex()); inter.faireLigne(); //afficher(code.afficherPseudoCode()); afficher(code.afficherDonnees()); lireClavier(); inter.incIndex(); ihm.nettoyer(); //System.out.println(code.getIligUtil()); }*/ ihm.normal(); } /** * Lance la possibilité a l'utilisateur de choisir les variables * à tracer * */ private void choixTracageVariables() { afficher("Quelles variables souhaitez vous tracer ?"); Set<String> vars = code.variables.keySet(); boolean saisie = false; for(String nomVar: vars){ ihm.print(nomVar +": " ); saisie = ihm.lireBoolean(); code.variables.get(nomVar).setTracage(saisie); } } /** * Envoie sur l'ihm console une chaine de caractère à afficher * avec retour ligne * */ public void afficher(String str){ ihm.println(str); } /** * Retourne la saisie au clavier depuis l'ihm * @return un String * */ public String lireClavier(){ return ihm.lireClavier(); } /** * Incrémente le numéro de ligne en cours dans l'instance de Code * */ public void incNumLig(){ code.incNumLig(); } /** * Défini le numéro de ligne courante dans l'instance de Code * */ public void setNumLig(int numLig){ code.setNumLig(numLig); } /** * Retourne la valeur de la ligne utile à l'indice i dans la liste * de numéros de lignes utiles * @param index indice dans la liste entier * @return entier numéro de ligne utile à l'indice i * */ public int getNumLigUtilAt(int index){ return code.getNumLigUtilAt(index); } }
true
edece5363781c71e54dc0e15c36263653f62160d
Java
PaaS-TA/PAAS-TA-PORTAL-API
/src/main/java/org/openpaas/paasta/portal/api/controller/FlagControllerV3.java
UTF-8
1,032
1.578125
2
[ "Apache-2.0" ]
permissive
package org.openpaas.paasta.portal.api.controller; import org.openpaas.paasta.portal.api.common.Common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RestController; /** * Created by cheolhan on 2019-04-24. */ @RestController public class FlagControllerV3 extends Common { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////// * CLOUD FOUNDRY CLIENT API VERSION 3 ////// ////// Document : https://http://v3-apidocs.cloudfoundry.org/version/3.69.0/#feature-flags ////// ////// Not-implemented ////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private static final Logger LOGGER = LoggerFactory.getLogger(FlagControllerV3.class); }
true
d5683b9946aa65723d6f8714295531290c4c9e99
Java
jekey/jboot
/src/main/java/io/jboot/db/model/ModelCopier.java
UTF-8
3,527
2.328125
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2015-2017, Michael Yang 杨福海 (fuhai999@gmail.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jboot.db.model; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.Page; import io.jboot.utils.ClassNewer; import java.util.ArrayList; import java.util.List; /** * VoModel的拷贝器 */ public class ModelCopier { public static final String MODEL_FROM_COPIER = "__from_copier__"; public static <M extends JbootVoModel> Page<M> convertToVo(Page<? extends JbootModel> page, Class<M> clazz) { if (page == null) { return null; } List<M> list = new ArrayList<>(); for (JbootModel model : page.getList()) { list.add(convertToVo(model, clazz)); } return new Page<M>(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow()); } public static <M extends JbootVoModel> List<M> convertToVo(List<? extends JbootModel> modelList, Class<M> clazz) { if (modelList == null) { return null; } List<M> datas = new ArrayList<>(); for (JbootModel model : modelList) { datas.add(convertToVo(model, clazz)); } return datas; } public static <M extends JbootVoModel> M convertToVo(JbootModel model, Class<M> clazz) { return (M) copyToVo(model, ClassNewer.newInstance(clazz,false)); } public static JbootVoModel copyToVo(JbootModel model, JbootVoModel toObject) { if (model == null) return toObject; toObject.putAll(model._getAttrsAsMap()); toObject.remove(MODEL_FROM_COPIER); return toObject; } ////////以下是JbootModel 转化到 JbootVoModel//////// public static <M extends Model> Page<M> convertToModel(Page<? extends JbootVoModel> page, Class<M> clazz) { if (page == null) { return null; } List<M> list = new ArrayList<>(); for (JbootVoModel voModel : page.getList()) { list.add(convertToModel(voModel, clazz)); } return new Page<M>(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow()); } public static <M extends JbootModel> List<M> convertToModel(List<? extends JbootVoModel> modelList, Class<M> clazz) { if (modelList == null) { return null; } List<M> datas = new ArrayList<>(); for (JbootVoModel voModel : modelList) { datas.add(convertToModel(voModel, clazz)); } return datas; } public static <M extends Model> M convertToModel(JbootVoModel voModel, Class<M> clazz) { return (M) copyToModel(voModel, ClassNewer.newInstance(clazz,false)); } public static Model copyToModel(JbootVoModel voModel, Model toModel) { if (voModel == null) return toModel; toModel.put(voModel); toModel.put(MODEL_FROM_COPIER, true); return toModel; } }
true
428d24d141336e0d4193bd905dc4026fb6af2cc8
Java
juhS/finalpjtsjh
/src/main/java/com/kh/batterflow/user/myinfo/controller/MyInfomationController.java
UTF-8
3,245
1.96875
2
[]
no_license
package com.kh.batterflow.user.myinfo.controller; import java.util.List; import javax.servlet.http.HttpSession; 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.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.kh.batterflow.user.myinfo.service.MyInfoService; import com.kh.batterflow.vo.UserClient_vo; import com.kh.batterflow.vo.VacationInfo_vo; import com.kh.batterflow.vo.VacationType_vo; @Controller @RequestMapping("/myinfo") //나의정보 public class MyInfomationController { @Autowired MyInfoService myInfoService; //나의인사정보 @GetMapping("/personinfo") public String myPersonnelInfo() { return "user/myInfo/myPersonnelInfo"; } //나의휴가정보 @GetMapping("/vacationinfo") public String myVacationInfo(Model model, @ModelAttribute VacationType_vo vacationType_vo, @ModelAttribute VacationInfo_vo vacationInfo_vo, HttpSession session) throws Exception{ //public String myVacationInfo(Model model,@RequestParam("user_id" ) int user_id, @ModelAttribute VacationType_vo vacationType_vo,@ModelAttribute VacationInfo_vo vacationInfo_vo,@ModelAttribute VacationKind_vo vacationKind_vo) throws Exception { UserClient_vo login = (UserClient_vo) session.getAttribute("login"); //login.getUser_id(); int user_id = login.getUser_id(); //휴가내역 : 휴가종류 불러오기(selectBox) List<VacationType_vo> vacationTypeList = myInfoService.selectList(vacationType_vo); model.addAttribute("vacationTypeList", vacationTypeList); //휴가내역 : 휴가일수부여내역 list조회 //System.out.println("컨트롤러 유저아이디 확인ㅇ: " + user_id); List<VacationInfo_vo> vacationInfoList = myInfoService.apprList(user_id); //System.out.println("wpdklfjalkejw" +vacationInfoList); model.addAttribute("apprList", vacationInfoList); //휴가내역 : 휴가일수차감(사용_내역 list조회 List<VacationInfo_vo> vacationInfoMList = myInfoService.apprMList(user_id); //System.out.println("apprMList" +vacationInfoMList); //System.out.println("컨트롤러 vacationInfoMList 확인ㅇ: " + vacationInfoMList); model.addAttribute("apprMList", vacationInfoMList); // VacationInfo_vo aa = VacationInfo_vo.builder().user_id(user_id).build(); // for(int i=0; i<vacationInfoList.size(); i++) { // VacationInfo_vo aa = VacationInfo_vo.builder().user_id(vacationInfoList.get(i).getUser_id()).vaca_info_id(vacationInfoList.get(i).getVaca_info_id()).vaca_appr_reason(vacationInfoList.get(i).getVaca_appr_reason()).vaca_appr_day(vacationInfoList.get(i).getVaca_appr_day()).vaca_appr_date(vacationInfoList.get(i).getVaca_appr_date()).build(); // // // System.out.println("나오라아ㅣ러ㅣㅓ :" + aa); // } // System.out.println("컨트롤러2"); //model.addAttribute("apprList", myInfoService.apprList(user_id)); return "user/myInfo/myVacationInfo"; } //나의휴가조 }
true
a7b91bfef4ae78d3e2a72d012c1e5a552059f062
Java
RDYW81/PI_Ueb18_A1
/Quadrat.java
UTF-8
184
2.140625
2
[]
no_license
/** * Tragen Sie hier eine Beschreibung des Interface Quadrat ein. * * @author Roland Daidone, Michael Linn * @version 1.0 */ public interface Quadrat { public void berechneQuadrat(); }
true
2ebde2b0956954acd4f06ddf81c4f3e83fbdf7a3
Java
utcuong3010/guru
/common/src/main/java/com/bubanking/common/configuration/RabbitConfiguration.java
UTF-8
2,073
2.21875
2
[]
no_license
package com.bubanking.common.configuration; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.amqp.rabbit.annotation.EnableRabbit; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableRabbit public class RabbitConfiguration { @Autowired RabbitProperties rabbitProperties; @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory( rabbitProperties.getHost(), rabbitProperties.getPort()); connectionFactory.setUsername(rabbitProperties.getUsername()); connectionFactory.setPassword(rabbitProperties.getPassword()); connectionFactory.setVirtualHost(rabbitProperties.getVirtualHost()); return connectionFactory; } @Bean public TopicExchange exchange() { return new TopicExchange(rabbitProperties.getExchangeName()); } @Bean public MessageConverter messageConverter() { return new Jackson2JsonMessageConverter(); } @Bean public RabbitTemplate rabbitTemplate() { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory()); rabbitTemplate.setMessageConverter(messageConverter()); return rabbitTemplate; } @Bean public Queue queue() { return new Queue(rabbitProperties.getQueueName()); } @Bean public Binding queueBinding(TopicExchange exchange, Queue queue) { return BindingBuilder.bind(queue).to(exchange).with(rabbitProperties.getQueueName()); } }
true
389482fafc6fa79bdfa3caf73b4aa0647c95b369
Java
EezoME/AstroProjects
/AstroMet/src/main/java/org/astro/met/MainMetering.java
UTF-8
15,701
2.5
2
[]
no_license
package org.astro.met; import org.astro.met.model.abstracts.PlanetarySystem; import org.astro.met.model.abstracts.PlanetarySystemObject; import org.astro.met.model.planetary_system.SolarSystem; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; /** * This class contains main form and realization of computing. * Created by Eezo on 16.08.2016. */ public class MainMetering extends JFrame { private JPanel rootPanel; private JComboBox comboBoxGalaxies; private JComboBox comboBoxPlanetarySystems; private JComboBox comboBoxPointOfDeparture; private JComboBox comboBoxArrivalPoint; private JComboBox comboBoxSpeed; private JComboBox comboBoxUnits; private JLabel labelDistance; private JLabel labelFlightTime; private JButton buttonDoCalculations; private JComboBox comboBoxPSO; private JComboBox comboBoxSatellites; private JLabel labelDataType; private JLabel labelDataPericenter; private JLabel labelDataApocenter; private JLabel labelDataSemiMajorAxis; private JLabel labelDataOrbitalEccentricity; private JLabel labelDataAverageOrbitalPeriod; private JLabel labelDataAverageOrbitalSpeed; private JLabel labelDataRotationPeriod; private JLabel labelDataASatelliteOf; private JLabel labelDataEquatorialRadius; private JLabel labelDataPolarRadius; private JLabel labelDataMeanRadius; private JLabel labelDataSurfaceArea; private JLabel labelObjectImage; private JButton buttonRefreshInfo; private JLabel labelSatellites; private JLabel labelType; private JLabel labelPericenter; private JLabel labelApocenter; private JLabel labelSemiMajorAxis; private JLabel labelOrbitalEccentricity; private JLabel labelAverageOrbitalPeriod; private JLabel labelAverageOrbitalSpeed; private JLabel labelRotationPeriod; private JLabel labelASatelliteOf; private JLabel labelEquatorialRadius; private JLabel labelPolarRadius; private JLabel labelMeanRadius; private JLabel labelSurfaceArea; private JButton buttonGetSatelliteInfo; private JLabel[][] labels; private java.util.List<PlanetarySystem> planetarySystems; static double defaultUnit; public MainMetering() { super("AstroMet v2.1.1"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setContentPane(rootPanel); createMenuBar(); setBounds(400, 215, 905, 530); setVisible(true); initialize(); buttonDoCalculations.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { computing(); } }); comboBoxPSO.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getInfo(comboBoxPSO); } }); buttonRefreshInfo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getInfo(comboBoxPSO); } }); buttonGetSatelliteInfo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getInfo(comboBoxSatellites); } }); comboBoxSatellites.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //getInfo(comboBoxSatellites); } }); labelObjectImage.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (labelObjectImage.getIcon().toString().equals(planetarySystems.get(0).getPath())) { System.out.println(labelObjectImage.getMousePosition()); PlanetarySystemObject pso = getPointRange(labelObjectImage.getMousePosition()); comboBoxPSO.setSelectedItem(pso); if (pso != null && comboBoxPSO.getSelectedIndex() == -1){ getInfo(pso); } } } }); } /** * This method computes data for AstroMet. */ private void computing() { // distance c = |a-b|, where a - dstn between Sun and SSO1, b - dstn between Sun and SSO2 //long a = PSO.getDistanceForComputing(); long a = ((PlanetarySystemObject) comboBoxPointOfDeparture.getSelectedItem()).getDistanceForComputing(); //long b = PSO.getDistanceForComputing(); long b = ((PlanetarySystemObject) comboBoxArrivalPoint.getSelectedItem()).getDistanceForComputing(); long c = Math.abs(a - b); // s - number of seconds of flight time, sp - current speed double sp = DataClass.SPEEDS[comboBoxSpeed.getSelectedIndex()]; long s = (long) (c / sp); labelDistance.setText(DataClass.formatDistance(c, comboBoxUnits.getSelectedIndex())); labelFlightTime.setText(DataClass.formatTime(s)); } /** * Checks combobox for planetary system objects. */ private void getInfo(JComboBox comboBox) { if (comboBox.getSelectedIndex() < 0) { return; } if (comboBox.getSelectedItem() instanceof PlanetarySystemObject) { getInfo((PlanetarySystemObject) comboBox.getSelectedItem()); } else { //JOptionPane.showMessageDialog(this, "Выберите объект планетарной системы из списка."); labelObjectImage.setIcon(new ImageIcon(DataClass.PATH_TO_IMAGES_FOLDER + "\\solar_system.png")); } } /** * This method computes and formats data for AstroInfo. */ private void getInfo(PlanetarySystemObject selectedObject) { clearLabels(); Iterator<String> iterator = selectedObject.getObjectInfoMap().keySet().iterator(); int ind = 0; while (iterator.hasNext()) { labels[ind][0].setText(iterator.next()); labels[ind][1].setText(selectedObject.getObjectInfoMap().get(labels[ind][0].getText())); ind++; } labelObjectImage.setIcon(new ImageIcon(selectedObject.getPath())); comboBoxSatellites.removeAllItems(); try { labelSatellites.setVisible(true); if (selectedObject.getSatellites() == null) { comboBoxSatellites.setVisible(false); labelSatellites.setText("Спутников не имеет"); } else { comboBoxSatellites.setVisible(true); labelSatellites.setText("Спутники: "); for (int i = 0; i < selectedObject.getSatellites().size(); i++) { comboBoxSatellites.addItem(selectedObject.getSatellites().get(i)); } } } catch (UnsupportedOperationException e) { comboBoxSatellites.setVisible(false); labelSatellites.setVisible(false); labelSatellites.setVisible(false); } } /** * Custom method for preparing form for viewing. */ @SuppressWarnings("unckecked") private void initialize() { defaultUnit = DataClass.KM_COEFF; // labels labels = new JLabel[][]{{labelType, labelDataType}, {labelPericenter, labelDataPericenter}, {labelApocenter, labelDataApocenter}, {labelSemiMajorAxis, labelDataSemiMajorAxis}, {labelOrbitalEccentricity, labelDataOrbitalEccentricity}, {labelAverageOrbitalPeriod, labelDataAverageOrbitalPeriod}, {labelAverageOrbitalSpeed, labelDataAverageOrbitalSpeed}, {labelRotationPeriod, labelDataRotationPeriod}, {labelASatelliteOf, labelDataASatelliteOf}, {labelEquatorialRadius, labelDataEquatorialRadius}, {labelPolarRadius, labelDataPolarRadius}, {labelMeanRadius, labelDataMeanRadius}, {labelSurfaceArea, labelDataSurfaceArea}}; labelSatellites.setVisible(false); clearLabels(); planetarySystems = new ArrayList<>(); planetarySystems.add(new SolarSystem()); comboBoxGalaxies.addItem(DataClass.GALAXIES[0]); comboBoxGalaxies.setSelectedIndex(0); for (int i = 0; i < planetarySystems.size(); i++) { comboBoxPlanetarySystems.addItem(planetarySystems.get(i)); } comboBoxPlanetarySystems.setSelectedIndex(0); //Planetary System Objects List<PlanetarySystemObject> psos = planetarySystems.get(comboBoxPlanetarySystems.getSelectedIndex()).getPSOs(); comboBoxPSO.addItem(" - не выбрано - "); for (int i = 0; i < psos.size(); i++) { comboBoxPointOfDeparture.addItem(psos.get(i)); comboBoxArrivalPoint.addItem(psos.get(i)); comboBoxPSO.addItem(psos.get(i)); } comboBoxPointOfDeparture.setSelectedIndex(3); comboBoxArrivalPoint.setSelectedIndex(4); // speeds for (int i = 0; i < DataClass.SPEEDS_DESCRIPTION.length; i++) { comboBoxSpeed.addItem(DataClass.SPEEDS_DESCRIPTION[i]); } comboBoxSpeed.setSelectedIndex(0); // units for (int i = 0; i < DataClass.UNITS_DESCRIPTION.length; i++) { comboBoxUnits.addItem(DataClass.UNITS_DESCRIPTION[i]); } comboBoxUnits.setSelectedIndex(0); } /** * Check current point allocatable for some of PSOs. * @param point mouse current point * @return an object of planetary system or null if no matches was found */ private PlanetarySystemObject getPointRange(Point point) { if (point == null) { return null; } // Sun if ((point.x >= 0 && point.x <= 25) && (point.y >= 139 && point.y <= 262)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.SUN); } // Mercury if ((point.x >= 35 && point.x <= 40) && (point.y >= 160 && point.y <= 195)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.MERCURY); } // Venus if ((point.x >= 45 && point.x <= 54) && (point.y >= 152 && point.y <= 184)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.VENUS); } // Earth if ((point.x >= 57 && point.x <= 69) && (point.y >= 145 && point.y <= 176)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.EARTH); } // Moon if ((point.x >= 59 && point.x <= 65) && (point.y >= 131 && point.y <= 143)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.MOON); } // Mars if ((point.x >= 72 && point.x <= 81) && (point.y >= 140 && point.y <= 170)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.MARS); } // Asteroid Belt if ((point.x >= 55 && point.x <= 94) && (point.y >= 87 && point.y <= 134) || (point.x >= 95 && point.x <= 104) && (point.y >= 105 && point.y <= 176) || (point.x >= 103 && point.x <= 117) && (point.y >= 148 && point.y <= 214) || (point.x >= 95 && point.x <= 114) && (point.y >= 238 && point.y <= 263)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.ASTEROID_BELT); } // Ceres if ((point.x >= 89 && point.x <= 110) && (point.y >= 223 && point.y <= 259)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.CERES); } // Jupiter if ((point.x >= 122 && point.x <= 162) && (point.y >= 168 && point.y <= 217) || (point.x >= 138 && point.x <= 149) && (point.y >= 144 && point.y <= 167)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.JUPITER); } // Saturn if ((point.x >= 180 && point.x <= 217) && (point.y >= 149 && point.y <= 181) || (point.x >= 195 && point.x <= 206) && (point.y >= 128 && point.y <= 146)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.SARUTN); } // Uranus if ((point.x >= 243 && point.x <= 260) && (point.y >= 137 && point.y <= 153) || (point.x >= 274 && point.x <= 282) && (point.y >= 100 && point.y <= 122)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.URANUS); } // Neptune if ((point.x >= 269 && point.x <= 286) && (point.y >= 98 && point.y <= 141)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.NEPTUNE); } // Pluto if ((point.x >= 290 && point.x <= 315) && (point.y >= 164 && point.y <= 172) || (point.x >= 296 && point.x <= 300) && (point.y >= 159 && point.y <= 163)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.PLUTO); } // Charon if ((point.x >= 302 && point.x <= 304) && (point.y >= 160 && point.y <= 163)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.CHARON); } // Makemake if ((point.x >= 292 && point.x <= 325) && (point.y >= 200 && point.y <= 207)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.MAKEMAKE); } // Kuiper Belt if ((point.x >= 304 && point.x <= 321) && (point.y >= 84 && point.y <= 105) || (point.x >= 317 && point.x <= 321) && (point.y >= 105 && point.y <= 136) || (point.x >= 317 && point.x <= 334) && (point.y >= 137 && point.y <= 193) || (point.x >= 328 && point.x <= 334) && (point.y >= 197 && point.y <= 208) || (point.x >= 318 && point.x <= 334) && (point.y >= 216 && point.y <= 253)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.KUIPER_BELT); } // Eris if ((point.x >= 324 && point.x <= 338) && (point.y >= 93 && point.y <= 105)) { return planetarySystems.get(0).getPSOByCode(null, DataClass.ERIS); } return null; } /** * Custom method to make a menu bar. */ private void createMenuBar() { JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("Файл"); menuBar.add(fileMenu); JMenuItem optionsItem = new JMenuItem("Настройки..."); JMenuItem exitItem = new JMenuItem("Выход"); fileMenu.add(optionsItem); fileMenu.addSeparator(); fileMenu.add(exitItem); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); optionsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OptionsWindow.main(null); } }); } /** * Custom method prepares labels for new info items. */ private void clearLabels() { for (int i = 0; i < labels.length; i++) { labels[i][0].setText(""); labels[i][1].setText(""); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainMetering(); } }); } }
true
2db91276b37f87c962f16cc3ce901c6e8e9ec5aa
Java
Nanxi-Huang/ip
/src/main/java/InvalidEventException.java
UTF-8
529
2.859375
3
[]
no_license
class InvalidEventException extends DukeException{ protected String description; public InvalidEventException(String description) { this.description = description; } @Override public String toString() { String[] seg = description.split(" "); if (description.length() <= 6) { return "\u2639 OOPS!!! The description of an event cannot be empty..."; } else { return "\u2639 OOPS!! format for event: event (task) /at yyyy-MM-ddTHH:mm"; } } }
true
2cbf1737360d1c7642f08978fbcf31d827078b1a
Java
karpomkarpipom/interviewpanel-ms-user-service
/src/main/java/com/interviewpanel/user/controller/UserController.java
UTF-8
2,186
2.296875
2
[]
no_license
package com.interviewpanel.user.controller; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.interviewpanel.user.bean.Role; import com.interviewpanel.user.bean.User; import com.interviewpanel.user.kafka.Sender; import com.interviewpanel.user.exception.CustomException; import com.interviewpanel.user.service.ISignupService; @RestController public class UserController { // @Value("${spring.kafka.topic.userCreated}") @Value("${spring.cloud.stream.bindings.output.destination}") private String USER_CREATED_TOPIC; @Autowired private Sender sender; @Autowired private ISignupService iSignupService; @CrossOrigin("*") @PostMapping("v1/signup") @ResponseBody public ResponseEntity<Map<String, String>> signup(@RequestBody User user) { Map<String, String> responseSuccessMap=new HashMap<String,String>(); //revisit this code feature------ Set<Role> roleSet=new HashSet<Role>(); roleSet.add(new Role(1,"USER")); user.setRole(roleSet); //------------ User createdUser=iSignupService.saveUser(user); //After successful signup send notification to the user successfully signedup using Kafka sender.send(USER_CREATED_TOPIC, createdUser); if(createdUser!=null) { responseSuccessMap.put("status","User "+createdUser.getFirstName() +" signedup Successfully!" ); }else { throw new CustomException("Signup unsuccessful!",HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<Map<String, String>>(responseSuccessMap, HttpStatus.CREATED); } }
true
1d31ac8cf3a283df0ba8387d76fbf86d01466120
Java
ShelRoman/OldJava
/src/week4/lesson8/MyClass.java
UTF-8
1,157
3.25
3
[]
no_license
package week4.lesson8; // public class MyClass { // static int sStatic; // int sNonStatic; // public static class NestedExmple{ // public void f1(){ // } // } // public class InnerExmple{ // public void f2(){ // } // // // // public class MainNestedInner { // public static void main(String[] args) { // MyClass.NestedExmple obj1 = // new MyClass.NestedExmple(); // // MyClass.InnerExmple obj2 = // new MyClass().new InnerExmple(); // obj1.f1(); // obj2.f2(); // } // } // // public static void main(String[] args){ // final String name1 = "Name1"; // String name2 = "Name2"; // //��������� �����-������ � ����� ������������ ������(� ������ static � non-static) � � // //��������� ���������� ������������ ������ ������������ final // class InnerLocal{ // public void func(){ // // System.out.println(name1 +" "+ nameStatic); // //System.out.println(name2);//error // } // } // } // } //} //} }
true
397f2aedbd52c7eb9a1ab9e1d1d72156e1900fce
Java
Shikhar7dec/Goods24MAIN
/app/src/main/java/in/goods24/common/RegisterActivity.java
UTF-8
6,058
2.046875
2
[]
no_license
package in.goods24.common; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Toast; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; import in.goods24.R; import in.goods24.common.LoginActivity; import in.goods24.common.MainActivity; import in.goods24.util.ConstantsUtil; import in.goods24.util.HttpUtils; import in.goods24.util.ValidationUtil; public class RegisterActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); } public void onFinalRegister(View view){ EditText fname = (EditText)findViewById(R.id.regFName); EditText lname = (EditText)findViewById(R.id.regLName); EditText email = (EditText)findViewById(R.id.regEmail); EditText phone = (EditText)findViewById(R.id.regPhone); EditText pass = (EditText)findViewById(R.id.regPass); EditText rePass= (EditText)findViewById(R.id.regPassRe); Boolean areAllFieldsEmpty = ValidationUtil.isEmptyTextField(fname) ||ValidationUtil.isEmptyTextField(lname) ||ValidationUtil.isEmptyTextField(email) ||ValidationUtil.isEmptyTextField(phone) ||ValidationUtil.isEmptyTextField(pass) ||ValidationUtil.isEmptyTextField(rePass); if(!areAllFieldsEmpty){ if(ValidationUtil.isValidEmail(email)){ if(ValidationUtil.isValidPhoneNumber(phone)){ if(ValidationUtil.passwordMatcher(pass,rePass)){ SharedPreferences sharedpreferences = getSharedPreferences(ConstantsUtil.MyPREFERENCES, Context.MODE_PRIVATE); String utype = sharedpreferences.getString("selectedUserTypeID",""); RequestParams rp = new RequestParams(); rp.add("appId","g24API1"); rp.add("pwd","API1g24"); rp.add("utype",utype); rp.add("fname",fname.getText().toString()); rp.add("lname",lname.getText().toString()); rp.add("email",email.getText().toString()); rp.add("mobile",phone.getText().toString()); rp.add("password",pass.getText().toString()); String phpName = "createUser.php"; Log.d("REQ","Request from app>>>>>"+rp); RelativeLayout relLayoutProgress = (RelativeLayout) findViewById(R.id.progressBarLayout); relLayoutProgress.setVisibility(View.VISIBLE); makeRegRestCall(view,rp,phpName); } else showValidationMsg("Password doesn't match with Confirm Password"); } else showValidationMsg("Please enter valid phone number"); } else showValidationMsg("Please enter valid e-mail"); } else showValidationMsg("Please enter all fields"); } private void showValidationMsg(String message) { Toast.makeText(getApplicationContext(),message, Toast.LENGTH_LONG) .show(); } private void makeRegRestCall( final View view, RequestParams rp, String phpName) { HttpUtils.post(phpName,rp, new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject res) { Log.d("res","---------------response from host>>> "+res+"Status is"+statusCode); try{ String respMsg = (String)res.get("res"); int errCode= (Integer)res.getInt("error_code"); showRegResp(view,respMsg,errCode); } catch (Exception e){ e.printStackTrace(); showValidationMsg("Please check your internet and try again"); RelativeLayout relLayoutProgress = (RelativeLayout) findViewById(R.id.progressBarLayout); relLayoutProgress.setVisibility(View.GONE); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { Log.d("log","Status code is>>"+statusCode+"Response code>>>"+responseString); showValidationMsg("Some Error occurred please try again"); RelativeLayout relLayoutProgress = (RelativeLayout) findViewById(R.id.progressBarLayout); relLayoutProgress.setVisibility(View.GONE); } }); } private void showRegResp(View view,String respMessage, int errCode) { RelativeLayout relLayoutProgress = (RelativeLayout) findViewById(R.id.progressBarLayout); relLayoutProgress.setVisibility(View.GONE); if(0==errCode){ showValidationMsg(respMessage); Intent intent = new Intent(getApplicationContext(),LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else{ showValidationMsg(respMessage); } } @Override public void onBackPressed() { Intent intent = new Intent(this,LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }
true
d72eb0457d6556a0f57df1d47ef781bb72014771
Java
Ivana-Spiridonovska/web-pages
/Seminarska/SOURCE/NitkaVtora.java
UTF-8
791
3
3
[]
no_license
public class NitkaVtora implements Runnable { private int frekvencija = 1000; boolean animacija = false; ApletNitka a; private String poraka = "Втора нитка се извршува\n"; NitkaVtora(ApletNitka a) { this.a=a; } public void run() { while(true) { try { Thread.sleep(frekvencija); synchronized(this) { while (!animacija) wait(); } } catch (InterruptedException e) { } a.setThreadText(poraka); } } public synchronized void setLooping(boolean b) { animacija = b; if (animacija) notify(); } }
true
dcff189fac84e4ea0bcba1edaf7d64eac29001ed
Java
RajenderSingh/SpringMVC
/executorservice-example/src/main/java/com/demo/Executor.java
UTF-8
2,522
2.9375
3
[]
no_license
package com.demo; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Executor { public int execute(List<String> toBeProcessedList, int THREAD_SIZE, int BATCH_SIZE) { int dataCount = toBeProcessedList.size(); int subListFromIdx = 0, subListToIdx = BATCH_SIZE; int bundleCount = dataCount/BATCH_SIZE; int remainderData = dataCount % BATCH_SIZE; if(remainderData != 0) { bundleCount++; } if(bundleCount == 1 && remainderData != 0) { subListToIdx = remainderData; } int firstLoop = 0, secondLoop = 0; firstLoop = bundleCount/THREAD_SIZE; int remainderRec = bundleCount % THREAD_SIZE; if(remainderRec != 0) { firstLoop++; } try { for (int i = 0; i < firstLoop; i++) { List<Future<Boolean>> futLst = new ArrayList<Future<Boolean>>(); ExecutorService executor; if((i == (firstLoop-1)) && (remainderRec != 0)) { executor = Executors.newFixedThreadPool(remainderRec); secondLoop = remainderRec; } else { executor = Executors.newFixedThreadPool(THREAD_SIZE); secondLoop = THREAD_SIZE; } for (int j = 0; j < secondLoop; j++) { List<String> partialList = toBeProcessedList.subList(subListFromIdx, subListToIdx); Callable<Boolean> worker = new ExecutorRunner(partialList); Future<Boolean> result = executor.submit(worker); futLst.add(result); subListFromIdx = subListToIdx; if((i == (firstLoop-1)) && (j==(secondLoop-2))) { subListToIdx = subListToIdx + remainderData; } else { subListToIdx = subListToIdx + BATCH_SIZE; } } for (Future<Boolean> future : futLst) { try { System.out.println(future.get().booleanValue()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } executor.shutdown(); while (!executor.isTerminated()) { System.out.println("Waiting for all threads from a bundle to finish"); } System.out.println("Finished one bundle threads"); } System.out.println("Finished executing all bundles of threads"); } catch(Exception e) { e.printStackTrace(); } return dataCount; } }
true
856af1e22118a7c29eedef764b971ce78d2f889b
Java
narik41/blog
/src/main/java/com/treeleaf/blog/post/PostView.java
UTF-8
697
2.09375
2
[]
no_license
package com.treeleaf.blog.post; import com.treeleaf.blog.comment.CommentView; import com.treeleaf.blog.user.User; import org.springframework.beans.factory.annotation.Value; import java.util.List; import java.util.Set; public interface PostView { Long getId(); String getTitle(); String getDescription(); List<CommentView> getComments(); UserView getUser(); Set<ImageView> getImages(); interface ImageView{ Long getId(); @Value("#{target.getUrl()}") String getUrl(); } interface UserView { Long getId(); @Value("#{target.profile.firstName+' '+target.profile.lastName}") String getFullName(); } }
true
088dfd6bc8def31115c549b57c2abfa544bcbef3
Java
SaralaBhadraiah/ashok
/CoreExamples/src/com/app/java8/optional/OptionalDemo.java
UTF-8
560
3.734375
4
[]
no_license
package com.app.java8.optional; import java.util.Optional; public class OptionalDemo { public static void main(String[] args) { /*Program wtihout optional class String str[] = new String[10]; String str1 = str[5].toLowerCase(); System.out.println(str1);*/ /*Program with optional class*/ String str2[] = new String[20]; Optional<String> checkNull = Optional.ofNullable(str2[10]); if(checkNull.isPresent()) { String s = str2[10].toLowerCase(); System.out.println(s); } else { System.out.println("s is null"); } } }
true
d1aef06551a1cc06617d52c431376bdc7fe9f5fe
Java
WisamAlhroub/Observer-Pattern-Asssignment
/src/BlogPost.java
UTF-8
897
2.578125
3
[]
no_license
import java.util.Date; public class BlogPost { private String name; private String title; private String body; private Date postDate; public BlogPost(String name, String title, String body, Date postDate) { this.name = name; this.title = title; this.body = body; this.postDate = postDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Date getPostDate() { return postDate; } public void setPostDate(Date postDate) { this.postDate = postDate; } }
true
cac1c1a889aef885d5aab8894021549d429fc4c9
Java
pugagithub/DSAlgoSamplesRepo
/src/jan2019/MyLinkedList.java
UTF-8
1,822
3.796875
4
[]
no_license
package jan2019; public class MyLinkedList { LinkNode firstNode; public static void main(String[] args) { MyLinkedList ll = new MyLinkedList(); add(ll , new LinkNode(1, null)); add(ll , new LinkNode(2, null)); add(ll , new LinkNode(3, null)); add(ll , new LinkNode(4, null)); add(ll , new LinkNode(5, null)); traverse(ll); delete(ll,2 , new LinkNode(10, null)); System.out.println(); traverse(ll); } public static void add(MyLinkedList ll , LinkNode node){ if(ll.firstNode == null) ll.firstNode = node; else{ LinkNode currentNode = ll.firstNode; while(currentNode.next != null){ // While Loop to move past the data currentNode = currentNode.next; // Change the condition inside the while loop so the condition may fail later. } currentNode.next = node; } } public static void traverse(MyLinkedList ll){ LinkNode currentNode = ll.firstNode; while(currentNode.next!=null){ System.out.print(currentNode.data+" | "); currentNode = currentNode.next; } } public static void delete(MyLinkedList ll , int dataTobeDeleted , LinkNode newNode){ LinkNode currentNode = ll.firstNode; LinkNode parentNode = null; while(currentNode.next!=null){ if(currentNode.data == dataTobeDeleted){ parentNode.next = newNode; newNode.next = currentNode.next; return; } parentNode = currentNode; currentNode = currentNode.next; } } }// Class End class LinkNode { int data; LinkNode next; LinkNode(int data , LinkNode next){ this.data = data; this.next = next; } } //Traverse Data in Linked List //Delete Data in Linked List
true