hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923e77dc3c90986441f00e5dfd75f1de7e489a67
21,912
java
Java
src/main/java/com/sb/elsinore/BrewServer.java
DougEdey/SB_Elsinore_Server
8c67a88f46921df58e1580f78c3caeb42ce76209
[ "MIT" ]
70
2015-01-28T21:02:40.000Z
2022-01-18T15:51:27.000Z
src/main/java/com/sb/elsinore/BrewServer.java
DougEdey/SB_Elsinore_Server
8c67a88f46921df58e1580f78c3caeb42ce76209
[ "MIT" ]
28
2015-02-04T02:24:58.000Z
2016-10-14T14:36:12.000Z
src/main/java/com/sb/elsinore/BrewServer.java
DougEdey/SB_Elsinore_Server
8c67a88f46921df58e1580f78c3caeb42ce76209
[ "MIT" ]
30
2015-01-02T16:29:46.000Z
2022-01-26T08:19:34.000Z
38.442105
143
0.475539
1,000,770
package com.sb.elsinore; import ca.strangebrew.recipe.Recipe; import com.sb.elsinore.NanoHTTPD.Response.Status; import com.sb.elsinore.annotations.Parameter; import com.sb.elsinore.annotations.UrlEndpoint; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; /** * A custom HTTP server for Elsinore. * Designed to be very simple and lightweight. * * @author Doug Edey * */ @SuppressWarnings("ResultOfMethodCallIgnored") public class BrewServer extends NanoHTTPD { public static String SHA = ""; public static String SHA_DATE = ""; private static Recipe currentRecipe; private final TreeMap<String, java.lang.reflect.Method> m_endpoints = new TreeMap<>(); /** * The Root Directory of the files to be served. */ public File rootDir; /** * The Logger object. */ public static final Logger LOG = Logger.getLogger("com.sb.manager.Server"); /** * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE. */ public static final Map<String, String> MIME_TYPES = new HashMap<String, String>() { /** * The Serial UID. */ public static final long serialVersionUID = 1L; { put("css", "text/css"); put("htm", "text/html"); put("html", "text/html"); put("xml", "text/xml"); put("log", "text/plain"); put("txt", "text/plain"); put("asc", "text/plain"); put("gif", "image/gif"); put("jpg", "image/jpeg"); put("jpeg", "image/jpeg"); put("png", "image/png"); put("mp3", "audio/mpeg"); put("m3u", "audio/mpeg-url"); put("mp4", "video/mp4"); put("ogv", "video/ogg"); put("flv", "video/x-flv"); put("mov", "video/quicktime"); put("swf", "application/x-shockwave-flash"); put("js", "application/javascript"); put("pdf", "application/pdf"); put("doc", "application/msword"); put("ogg", "application/x-ogg"); put("zip", "application/octet-stream"); put("exe", "application/octet-stream"); put("class", "application/octet-stream"); put("json", "application/json"); } }; private static ArrayList<String> recipeList; /** * Constructor to create the HTTP Server. * * @param port * The port to run on * @throws IOException * If there's an issue starting up */ public BrewServer(final int port) throws IOException { super(port); // default level, this can be changed initializeLogger(BrewServer.LOG); Level logLevel = Level.WARNING; String newLevel = System.getProperty("debug") != null ? System.getProperty("debug"): System.getenv("ELSINORE_DEBUG"); if ("INFO".equalsIgnoreCase(newLevel)) { logLevel = Level.INFO; } BrewServer.LOG.info("Launching on port " + port); BrewServer.LOG.info("Enabled logging at level:" + logLevel.toString()); BrewServer.LOG.setLevel(logLevel); this.rootDir = new File(BrewServer.class.getProtectionDomain() .getCodeSource().getLocation().getPath()).getParentFile(); if (System.getProperty("root_override") != null) { this.rootDir = new File(System.getProperty("root_override")); LOG.info("Overriding Root Directory from System Property: " + rootDir.getAbsolutePath()); } LOG.info("Root Directory is: " + rootDir.toString()); if (rootDir.exists() && rootDir.isDirectory()) { LOG.info("Root directory: " + rootDir.toString()); } // Load the ANnotations for (java.lang.reflect.Method m : UrlEndpoints.class.getDeclaredMethods()) { UrlEndpoint urlMethod = m.getAnnotation(UrlEndpoint.class); if (urlMethod != null) { m_endpoints.put(urlMethod.url().toLowerCase(), m); } } } public static void setRecipeList(ArrayList<String> recipeList) { BrewServer.recipeList = recipeList; } public static ArrayList<String> getRecipeList() { return recipeList; } public static void setCurrentRecipe(Recipe recipe) { BrewServer.currentRecipe = recipe; } public static Recipe getCurrentRecipe() { return BrewServer.currentRecipe; } @SuppressWarnings("unchecked") public static JSONObject getVersionStatus() { JSONObject verStatus = new JSONObject(); verStatus.put("sha", BrewServer.SHA); verStatus.put("date", BrewServer.SHA_DATE); return verStatus; } /** * Initialize the logger. Look at the current logger and its parents to see * if it already has a handler setup. If not, it adds one. * * @param logger * The logger to initialize */ private void initializeLogger(final Logger logger) { if (logger.getHandlers().length == 0) { if (logger.getParent() != null && logger.getUseParentHandlers()) { initializeLogger(LOG.getParent()); } else { Handler newHandler = new ConsoleHandler(); logger.addHandler(newHandler); } } } /** * The main method that checks the data coming into the server. * * @param session The HTTP Session object. * @return A NanoHTTPD Response Object */ @SuppressWarnings("unchecked") public final Response serve(IHTTPSession session) { String uri = session.getUri(); Method method = session.getMethod(); Map<String, String> header = session.getHeaders(); Map<String, String> parms = session.getParms(); Map<String, String> files = new HashMap<>(); if (Method.PUT.equals(method) || Method.POST.equals(method)) { try { session.parseBody(files); } catch (IOException ioe) { return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } catch (ResponseException re) { return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); } } BrewServer.LOG.info("URL : " + uri + " method: " + method); if (uri.equalsIgnoreCase("/favicon.ico")) { // Has the favicon been overridden? // Check to see if there's a theme set. if (LaunchControl.theme != null && !LaunchControl.theme.equals("")) { if (new File(rootDir, "/logos/" + LaunchControl.theme + ".ico").exists()) { return serveFile("/logos/" + LaunchControl.theme + ".ico", header, rootDir); } } if (new File(rootDir, uri).exists()) { return serveFile(uri, header, rootDir); } } // NLS Support if (uri.startsWith("/nls/")) { return serveFile(uri.replace("/nls/", "/src/main/java/com/sb/elsinore/nls/"), header, rootDir); } if (uri.equalsIgnoreCase("/stop")) { System.exit(128); } if (uri.equals("/help")) { JSONObject helpJSON = new JSONObject(); for (Map.Entry<String, java.lang.reflect.Method> entry: m_endpoints.entrySet()) { UrlEndpoint urlEndpoint = entry.getValue().getAnnotation(UrlEndpoint.class); helpJSON.put(urlEndpoint.url(), urlEndpoint.help()); } return new Response(Status.OK, MIME_TYPES.get("json"), helpJSON.toJSONString()); } String endpointName = uri; boolean help = false; if (uri.endsWith("/help")) { endpointName = uri.substring(0, uri.indexOf("/help")); help = true; } java.lang.reflect.Method urlMethod = m_endpoints.get(endpointName.toLowerCase()); if (urlMethod != null) { if (!help) { try { UrlEndpoints urlEndpoints = new UrlEndpoints(); urlEndpoints.parameters = parms; urlEndpoints.files = files; urlEndpoints.header = header; urlEndpoints.rootDir = rootDir; return (Response) urlMethod.invoke(urlEndpoints); } catch (Exception e) { LOG.warning("Couldn't access URL: " + uri); e.printStackTrace(); } } UrlEndpoint urlEndpoint= urlMethod.getAnnotation(UrlEndpoint.class); JSONObject helpJSON = new JSONObject(); helpJSON.put(urlEndpoint.url(), urlEndpoint.help()); JSONArray paramsJSON = new JSONArray(); for (Parameter parameter: urlEndpoint.parameters()) { JSONObject paramObj = new JSONObject(); paramObj.put(parameter.name(), parameter.value()); paramsJSON.add(paramObj); } Collections.sort(paramsJSON, new Comparator() { @Override public int compare(Object o, Object t1) { return o.toString().compareTo(t1.toString()); } }); helpJSON.put("parameters", paramsJSON); return new Response(Status.BAD_REQUEST, MIME_TYPES.get("json"), helpJSON.toJSONString()); } if (uri.equals("/")) { return serveFile("html/index.html", header, rootDir); } if (!uri.equals("") && new File(rootDir, uri).exists()) { return serveFile(uri, header, rootDir); } BrewServer.LOG.warning("Failed to find URI: " + uri); BrewServer.LOG.info("Unidentified URL: " + uri); JSONObject usage = new JSONObject(); usage.put("controller", "Get the main controller page"); usage.put("getstatus", "Get the current status as a JSON object"); usage.put("timers", "Get the current timer status"); usage.put("addswitch", "Add a new switch"); usage.put("addtimer", "Add a new timer"); usage.put("addvolpoint", "Add a new volume point"); usage.put("toggleaux", "toggle an aux output"); usage.put("mashprofile", "Set a mash profile for the output"); usage.put("editdevice", "Edit the settings on a device"); usage.put("updatepid", "Update the PID Settings"); usage.put("updateday", "Update the brewday information"); usage.put("updateswitch", "Change the switch status off/on"); BrewServer.LOG.info("Invalid URI: " + uri); return new NanoHTTPD.Response(Status.NOT_FOUND, MIME_TYPES.get("json"), usage.toJSONString()); } /** * Serves file from homeDir and its' subdirectories (only). Uses only URI, * ignores all headers and HTTP parameters. * * @param incomingUri * The URI requested * @param header * The headers coming in * @param homeDir * The root directory. * @return A NanoHTTPD Response for the file */ public static Response serveFile(final String incomingUri, final Map<String, String> header, final File homeDir) { Response res = null; String uri = incomingUri; // Make sure we won't die of an exception later if (!homeDir.isDirectory()) { res = new Response(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "INTERNAL ERRROR: serveFile(): " + "given homeDir is not a directory."); } if (res == null) { // Remove URL arguments uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) { uri = uri.substring(0, uri.indexOf('?')); } // Prohibit getting out of current directory if (uri.startsWith("src/main") || uri.endsWith("src/main") || uri.contains("../")) { res = new Response(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons."); } } File f = new File(homeDir, uri); if (res == null && !f.exists()) { res = new Response(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found."); } // List the directory, if necessary if (res == null && f.isDirectory()) { // Browsers get confused without '/' after the // directory, send a redirect. if (!uri.endsWith("/")) { uri += "/"; res = new Response(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>"); res.addHeader("Location", uri); } if (res == null) { // First try index.html and index.htm if (new File(f, "index.html").exists()) { f = new File(homeDir, uri + "/index.html"); } else if (new File(f, "index.htm").exists()) { f = new File(homeDir, uri + "/index.htm"); // No index file, list the directory if it is readable } else if (f.canRead()) { String[] files = f.list(); String msg = "<html><body><h1>Directory " + uri + "</h1><br/>"; if (uri.length() > 1) { String u = uri.substring(0, uri.length() - 1); int slash = u.lastIndexOf('/'); if (slash >= 0 && slash < u.length()) { msg += "<b><a href=\"" + uri.substring(0, slash + 1) + "\">..</a></b><br/>"; } } if (files != null) { for (int i = 0; i < files.length; ++i) { File curFile = new File(f, files[i]); boolean dir = curFile.isDirectory(); if (dir) { msg += "<b>"; files[i] += "/"; } msg += "<a href=\"" + encodeUri(uri + files[i]) + "\">" + files[i] + "</a>"; // Show file size if (curFile.isFile()) { long len = curFile.length(); msg += " &nbsp;<font size=2>("; if (len < 1024) { msg += len + " bytes"; } else if (len < 1024 * 1024) { msg += len / 1024 + "." + (len % 1024 / 10 % 100) + " KB"; } else { msg += len / (1024 * 1024) + "." + len % (1024 * 1024) / 10 % 100 + " MB"; } msg += ")</font>"; } msg += "<br/>"; if (dir) { msg += "</b>"; } } } msg += "</body></html>"; res = new Response(msg); } else { res = new Response(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: No directory listing."); } } } try { if (res == null) { // Get MIME type from file name extension, if possible String mime = null; int dot = f.getCanonicalPath().lastIndexOf('.'); if (dot >= 0) { mime = MIME_TYPES.get(f.getCanonicalPath() .substring(dot + 1).toLowerCase()); } if (mime == null) { mime = NanoHTTPD.MIME_HTML; } // Calculate etag String etag = Integer.toHexString((f.getAbsolutePath() + f.lastModified() + "" + f.length()).hashCode()); // Support (simple) skipping: long startFrom = 0; long endAt = -1; String range = header.get("range"); if (range != null) { if (range.startsWith("bytes=")) { range = range.substring("bytes=".length()); int minus = range.indexOf('-'); try { if (minus > 0) { startFrom = Long.parseLong(range.substring(0, minus)); endAt = Long.parseLong(range .substring(minus + 1)); } } catch (NumberFormatException ignored) { BrewServer.LOG.info(ignored.getMessage()); } } } // Change return code and add Content-Range header // when skipping is requested long fileLen = f.length(); if (range != null && startFrom >= 0) { if (startFrom >= fileLen) { res = new Response( Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, ""); res.addHeader("Content-Range", "bytes 0-0/" + fileLen); res.addHeader("ETag", etag); } else { if (endAt < 0) { endAt = fileLen - 1; } long newLen = endAt - startFrom + 1; if (newLen < 0) { newLen = 0; } final long dataLen = newLen; FileInputStream fis = new FileInputStream(f) { @Override public int available() throws IOException { return (int) dataLen; } }; fis.skip(startFrom); res = new Response(Response.Status.PARTIAL_CONTENT, mime, fis); res.addHeader("Content-Length", "" + dataLen); res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); res.addHeader("ETag", etag); } } else { if (etag.equals(header.get("if-none-match"))) { res = new Response(Response.Status.NOT_MODIFIED, mime, ""); } else { res = new Response(Response.Status.OK, mime, new FileInputStream(f)); res.addHeader("Content-Length", "" + fileLen); res.addHeader("ETag", etag); } } } } catch (IOException ioe) { res = new Response(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: Reading file failed."); } res.addHeader("Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes return res; } /** * URL-encodes everything between "/"-characters. Encodes spaces as '%20' * instead of '+'. * @param uri * The URI to be encoded * @return The Encoded URI */ public static String encodeUri(final String uri) { String newUri = ""; StringTokenizer st = new StringTokenizer(uri, "/ ", true); while (st.hasMoreTokens()) { String tok = st.nextToken(); if (tok.equals("/")) { newUri += "/"; } else if (tok.equals(" ")) { newUri += "%20"; } else { try { newUri += URLEncoder.encode(tok, "UTF-8"); } catch (UnsupportedEncodingException ignored) { BrewServer.LOG.info(ignored.getMessage()); } } } return newUri; } }
923e7921db23e45cb730fe9827d8980c422eb600
5,123
java
Java
PCS/Infrastructure/inf-jar/ca-manager/src/main/java/com/idealunited/poss/systemmanager/service/impl/UserServiceImpl.java
IdealUnited/JAVA-2017
75cbc068ea399ff0e9c7690419fdb0b5e215e337
[ "Apache-2.0" ]
2
2017-09-11T06:08:03.000Z
2018-08-08T03:27:40.000Z
PCS/Infrastructure/inf-jar/ca-manager/src/main/java/com/idealunited/poss/systemmanager/service/impl/UserServiceImpl.java
IdealUnited/JAVA-2017
75cbc068ea399ff0e9c7690419fdb0b5e215e337
[ "Apache-2.0" ]
16
2020-04-27T03:21:18.000Z
2022-02-01T00:57:31.000Z
PCS/Infrastructure/inf-jar/ca-manager/src/main/java/com/idealunited/poss/systemmanager/service/impl/UserServiceImpl.java
IdealUnited/JAVA-2017
75cbc068ea399ff0e9c7690419fdb0b5e215e337
[ "Apache-2.0" ]
1
2021-01-10T10:39:46.000Z
2021-01-10T10:39:46.000Z
28.943503
77
0.721062
1,000,771
package com.idealunited.poss.systemmanager.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.Authentication; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.encoding.Md5PasswordEncoder; import com.idealunited.inf.dao.Page; import com.idealunited.poss.security.model.SessionUserHolder; import com.idealunited.poss.systemmanager.dao.IUserDao; import com.idealunited.poss.systemmanager.formbean.UserFormBean; import com.idealunited.poss.systemmanager.model.Duty; import com.idealunited.poss.systemmanager.model.Org; import com.idealunited.poss.systemmanager.model.Users; import com.idealunited.poss.systemmanager.service.IUserService; /** * 用户管理Service * * @author wucan * @descript * @data 2010-7-22 下午05:58:47 */ public class UserServiceImpl implements IUserService { private Map DutyAndOrgmap = new HashMap(); private final Log logger = LogFactory.getLog(getClass()); private IUserDao userDAO; // 注入DAO public void setUserDAO(IUserDao userDAO) { this.userDAO = userDAO; } @Override public boolean deleteUser(String id) { Users user = new Users(); user.setStatus(0); user.setUserKy(new Long(id)); return userDAO.deleteUser(user); } @Override public Users findUserById(String id) { return (Users) userDAO.findById(new Long(id)); } @Override public List<Users> findAllUsers() { return userDAO.findAllUsers(); } @Override public void saveUser(UserFormBean userFormBean) throws Exception { try { // 新增用户 Users user = new Users(); setFormBeanToUser(userFormBean, user); userDAO.create(user); logger.info("新增用户" + user.getLoginId() + "--" + user.getUserName()); } catch (Exception ex) { logger.error("新增用户关联自然人、员工、岗位"); ex.printStackTrace(); throw new Exception("新增用户关联自然人、员工、岗位"); } } @Override public boolean updateUser(UserFormBean userFormBean) throws Exception { try { // 新增用户 Users user = (Users) userDAO.findById(new Long(userFormBean .getUserKy())); setFormBeanToUser(userFormBean, user); userDAO.update(user); } catch (Exception ex) { logger.error(ex); logger.error("修改用户关联自然人、员工、岗位", ex); throw new Exception("修改用户关联自然人、员工、岗位"); } return true; } @Override public List<UserFormBean> queryAll(Map<String, String> map) { return userDAO.queryByMap(map); } // 条件查询分页 public Page<UserFormBean> search(Page<UserFormBean> page, Map<String, String> map) { return userDAO.search(page, map); } @Override public Map queryAllDutyAndOrg() { if (!DutyAndOrgmap.containsKey("dutys")) { List<Duty> dutyList = userDAO.queryAllDuty(); DutyAndOrgmap.put("dutys", dutyList); } if (!DutyAndOrgmap.containsKey("org")) { List<Org> orgList = userDAO.queryAllOrg(); DutyAndOrgmap.put("orgs", orgList); } return DutyAndOrgmap; } @Override public UserFormBean queryUserByKy(String id) { Users user = new Users(); user.setUserKy(new Long(id)); return userDAO.queryUserByKy(user); } public boolean changePassword(String currentPassword, String newPassword) { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); SessionUserHolder sessionUserHolder = (SessionUserHolder) authentication .getPrincipal(); Md5PasswordEncoder md5 = new Md5PasswordEncoder(); String currentPwd = sessionUserHolder.getPassword(); currentPassword = md5.encodePassword(currentPassword, null); if (currentPassword.equals(currentPwd)) { Users user = new Users(); user.setUserKy(new Long(sessionUserHolder.getUserKy())); newPassword = md5.encodePassword(newPassword, null); user.setPassword(newPassword); return userDAO.updatePassword(user); } else { return false; } } public Users findUserByLoginId(String loginId) { return userDAO.findByLoginId(loginId); } /** * 将userFormBean的值设置到user里 * * @param userFormBean * @param user * @date 2011-1-5 */ private void setFormBeanToUser(UserFormBean userFormBean, Users user) { user.setLoginId(userFormBean.getUserCode()); if (StringUtils.isNotEmpty(userFormBean.getUserPassword())) { Md5PasswordEncoder md5 = new Md5PasswordEncoder(); String password = md5.encodePassword( userFormBean.getUserPassword(), null); user.setPassword(password); } user.setStatus(userFormBean.getUserStatus()); user.setUserEmail(userFormBean.getUserEmail()); user.setUserName(userFormBean.getUserName()); user.setUserMobile(userFormBean.getUserMobile()); user.setUserPhone(userFormBean.getUserPhone()); user.setUserRTX(userFormBean.getUserRTX()); user.setDutyCode(userFormBean.getUserDutyCode()); user.setOrgCode(userFormBean.getUserOrgCode()); user.setRepositoryId(userFormBean.getRepositoryId()); } }
923e792f44f9b1ec73d2b81843104493a7d6f76c
1,984
java
Java
src/main/org/jamocha/rete/functions/messaging/PrintContentHandlersFunction.java
DaveWoodman/morendo
d0db2fb7386cb09a5f8411c6a5fffe8841987677
[ "Apache-2.0" ]
null
null
null
src/main/org/jamocha/rete/functions/messaging/PrintContentHandlersFunction.java
DaveWoodman/morendo
d0db2fb7386cb09a5f8411c6a5fffe8841987677
[ "Apache-2.0" ]
3
2021-05-29T13:13:39.000Z
2021-06-25T12:37:06.000Z
src/main/org/jamocha/rete/functions/messaging/PrintContentHandlersFunction.java
woolfel/morendo
6245aff5c4fbb4514c7d6bb1b783077af1fa53eb
[ "Apache-2.0" ]
null
null
null
28.753623
92
0.753528
1,000,772
/* * Copyright 2002-2010 Jamocha * * 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://ruleml-dev.sourceforge.net/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jamocha.rete.functions.messaging; import java.util.Iterator; import org.jamocha.messaging.ContentHandler; import org.jamocha.messaging.ContentHandlerRegistry; import org.jamocha.rete.Constants; import org.jamocha.rete.DefaultReturnVector; import org.jamocha.rete.Function; import org.jamocha.rete.Parameter; import org.jamocha.rete.Rete; import org.jamocha.rete.ReturnVector; public class PrintContentHandlersFunction implements Function { /** * */ private static final long serialVersionUID = 1L; public static final String PRINT_CONTENT_HANDLERS = "print-content-handlers"; public PrintContentHandlersFunction() { } public ReturnVector executeFunction(Rete engine, Parameter[] params) { Iterator<?> iterator = ContentHandlerRegistry.keyIterator(); while (iterator.hasNext()) { String key = (String)iterator.next(); ContentHandler handler = ContentHandlerRegistry.findHandler(key); engine.writeMessage(key + ":" + handler.getClass().getName() + Constants.LINEBREAK, "t"); } DefaultReturnVector ret = new DefaultReturnVector(); return ret; } public String getName() { return PRINT_CONTENT_HANDLERS; } public Class<?>[] getParameter() { return new Class[0]; } public int getReturnType() { return Constants.RETURN_VOID_TYPE; } public String toPPString(Parameter[] params, int indents) { return "(print-content-handlers)"; } }
923e7974360621f71bf448e35d01d3ad9c7cb5cb
1,924
java
Java
hedera-node/src/main/java/com/hedera/services/ledger/properties/ChangeSummaryManager.java
Cryptourios/hedera-services
564c5cbaf18b033e667f52aa94850e4bce2168c5
[ "Apache-2.0" ]
164
2020-08-06T17:02:44.000Z
2022-03-30T15:56:55.000Z
hedera-node/src/main/java/com/hedera/services/ledger/properties/ChangeSummaryManager.java
Cryptourios/hedera-services
564c5cbaf18b033e667f52aa94850e4bce2168c5
[ "Apache-2.0" ]
2,439
2020-08-06T17:06:15.000Z
2022-03-31T23:38:38.000Z
hedera-node/src/main/java/com/hedera/services/ledger/properties/ChangeSummaryManager.java
Cryptourios/hedera-services
564c5cbaf18b033e667f52aa94850e4bce2168c5
[ "Apache-2.0" ]
51
2020-08-06T18:53:48.000Z
2022-02-03T13:12:37.000Z
30.539683
89
0.70738
1,000,773
package com.hedera.services.ledger.properties; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import java.util.Map; /** * Minimal implementation of a helper that manages summary changesets. * An extension point for possible future performance optimizations. * * @param <A> * the type of account being changed. * @param <P> * the property family whose changesets are to be summarized. */ public final class ChangeSummaryManager<A, P extends Enum<P> & BeanProperty<A>> { /** * Updates the changeset summary for the given property to the given value. * * @param changes * the total changeset summary so far. * @param property * the property in the family whose changeset should be updated. * @param value * the new value that summarizes the changeset. */ public void update(final Map<P, Object> changes, final P property, final Object value) { changes.put(property, value); } /** * Flush a changeset summary to a given object. * * @param changes * the summary of changes made to the relevant property family. * @param account * the account to receive the net changes. */ public void persist(final Map<P, Object> changes, final A account) { changes.entrySet().forEach(entry -> entry.getKey().setter().accept(account, entry.getValue()) ); } }
923e79e61ae17f5097f7b18cb6823a153966e24d
14,333
java
Java
APIJSON-Android/APIJSONTest/app/src/main/java/apijson/demo/ui/UIAutoListActivity.java
dacker-soul/APIJSON
a5d604e26ac666dcedbf759782f461c6f03d6b44
[ "Apache-2.0" ]
2
2021-02-10T10:05:43.000Z
2021-05-18T03:20:03.000Z
APIJSON-Android/APIJSONTest/app/src/main/java/apijson/demo/ui/UIAutoListActivity.java
dacker-soul/APIJSON
a5d604e26ac666dcedbf759782f461c6f03d6b44
[ "Apache-2.0" ]
null
null
null
APIJSON-Android/APIJSONTest/app/src/main/java/apijson/demo/ui/UIAutoListActivity.java
dacker-soul/APIJSON
a5d604e26ac666dcedbf759782f461c6f03d6b44
[ "Apache-2.0" ]
null
null
null
37.817942
232
0.534919
1,000,774
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon) 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 apijson.demo.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import apijson.demo.HttpManager; import apijson.demo.R; import apijson.demo.StringUtil; import apijson.demo.InputUtil; import zuo.biao.apijson.JSON; import zuo.biao.apijson.JSONRequest; import zuo.biao.apijson.JSONResponse; /** 操作流程 Flow /操作步骤 Touch 列表 * https://github.com/TommyLemon/UIAuto * @author Lemon */ public class UIAutoListActivity extends Activity implements HttpManager.OnHttpResponseListener { public static final String TAG = "UIAutoListActivity"; public static final String INTENT_IS_LOCAL = "INTENT_IS_LOCAL"; public static final String INTENT_FLOW_ID = "INTENT_FLOW_ID"; public static final String INTENT_TOUCH_LIST = "INTENT_TOUCH_LIST"; public static final String RESULT_LIST = "RESULT_LIST"; /** * @param context * @return */ public static Intent createIntent(Context context, boolean isLocal) { return new Intent(context, UIAutoListActivity.class).putExtra(INTENT_IS_LOCAL, isLocal); } /** * @param context * @return */ public static Intent createIntent(Context context, long flowId) { return new Intent(context, UIAutoListActivity.class).putExtra(INTENT_FLOW_ID, flowId); } /** * @param context * @return */ public static Intent createIntent(Context context, String touchList) { return createIntent(context, true).putExtra(INTENT_TOUCH_LIST, touchList); } public static final String CACHE_FLOW = "CACHE_FLOW"; public static final String CACHE_TOUCH = "KEY_TOUCH"; private Activity context; private long flowId = 0; private boolean isTouch = false; private boolean isLocal = false; private boolean hasTempTouchList = false; private JSONArray touchList = null; private EditText etUIAutoListName; private ListView lvUIAutoList; private View llUIAutoListBar; private View btnUIAutoListRecover; private ProgressBar pbUIAutoList; private EditText etUIAutoListUrl; private Button btnUIAutoListGet; SharedPreferences cache; String cacheKey; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ui_auto_list_activity); context = this; isLocal = getIntent().getBooleanExtra(INTENT_IS_LOCAL, isLocal); flowId = getIntent().getLongExtra(INTENT_FLOW_ID, flowId); touchList = JSON.parseArray(getIntent().getStringExtra(INTENT_TOUCH_LIST)); hasTempTouchList = touchList != null && touchList.isEmpty() == false; isTouch = flowId > 0 || hasTempTouchList; cache = getSharedPreferences(TAG, Context.MODE_PRIVATE); cacheKey = isTouch ? CACHE_TOUCH : CACHE_FLOW; if (isLocal) { JSONArray allList = JSON.parseArray(cache.getString(cacheKey, null)); if (hasTempTouchList) { if (allList == null || allList.isEmpty()) { allList = touchList; } else { allList.addAll(touchList); } cache.edit().remove(cacheKey).putString(cacheKey, JSON.toJSONString(allList)).apply(); } else { hasTempTouchList = true; if (flowId == 0) { touchList = allList; } else { touchList = new JSONArray(); if (allList != null) { for (int i = 0; i < allList.size(); i++) { JSONObject obj = allList.getJSONObject(i); if (obj != null && obj.getLongValue("flowId") == flowId) { touchList.add(obj); } } } } } } etUIAutoListName = findViewById(R.id.etUIAutoListName); lvUIAutoList = findViewById(R.id.lvUIAutoList); llUIAutoListBar = findViewById(R.id.llUIAutoListBar); btnUIAutoListRecover = findViewById(R.id.btnUIAutoListRecover); pbUIAutoList = findViewById(R.id.pbUIAutoList); etUIAutoListUrl = findViewById(R.id.etUIAutoListUrl); btnUIAutoListGet = findViewById(R.id.btnUIAutoListGet); btnUIAutoListRecover.setVisibility(isTouch ? View.VISIBLE : View.GONE); etUIAutoListName.setVisibility(isTouch ? View.VISIBLE : View.GONE); etUIAutoListName.setEnabled(isLocal || hasTempTouchList); // llUIAutoListBar.setVisibility(isLocal ? View.GONE : View.VISIBLE); btnUIAutoListGet.setText(isLocal ? R.string.post : R.string.get); lvUIAutoList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (array != null) { JSONObject obj = array.getJSONObject(position); if (isTouch) { // setResult(RESULT_OK, new Intent().putExtra(RESULT_LIST, JSON.toJSONString(obj))); // finish(); } else { startActivityForResult(UIAutoListActivity.createIntent(context, obj == null ? 0 : obj.getLongValue("id")), REQUEST_TOUCH_LIST); } } } }); if (hasTempTouchList) { showList(touchList); } else { send(btnUIAutoListGet); } } private ArrayAdapter<String> adapter; /** 示例方法 :显示列表内容 * @param list */ private void setList(List<String> list) { runOnUiThread(new Runnable() { @Override public void run() { pbUIAutoList.setVisibility(View.GONE); adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list); lvUIAutoList.setAdapter(adapter); } }); } private void showList(JSONArray array) { this.array = array; new Thread(new Runnable() { @Override public void run() { List<String> list = new ArrayList<>(); if (array != null) { for (int i = 0; i < array.size(); i++) { JSONObject obj = array.getJSONObject(i); if (obj == null) { obj = new JSONObject(); } String state = statueList.get(obj); if (StringUtil.isEmpty(state, true)) { state = "Local"; } if (isTouch) { if (obj.getIntValue("type") == 1) { list.add("[" + state + "] " + new Date(obj.getLongValue("time")).toLocaleString() + " " + InputUtil.getActionName(obj.getIntValue("action")) + "\nkeyCode: " + InputUtil.getKeyCodeName(obj.getIntValue("keyCode")) + ", scanCode: " + InputUtil.getScanCodeName(obj.getIntValue("scanCode")) + ", dividerY: " + obj.getString("dividerY") + "\nrepeatCount: " + obj.getString("repeatCount") + " " + InputUtil.getOrientationName(obj.getIntValue("orientation")) ); } else { list.add("[" + state + "] " + new Date(obj.getLongValue("time")).toLocaleString() + " " + InputUtil.getActionName(obj.getIntValue("action")) + "\nx: " + obj.getString("x") + ", y: " + obj.getString("y") + ", dividerY: " + obj.getString("dividerY") + "\npointerCount: " + obj.getString("pointerCount") + " " + InputUtil.getOrientationName(obj.getIntValue("orientation")) ); } } else { list.add("[" + state + "]" + " name: " + obj.getString("name") + ", time: " + new Date(obj.getLongValue("time")).toLocaleString()); } } } setList(list); } }).start(); } private Map<JSONObject, String> statueList = new HashMap<JSONObject, String>(); public void send(View v) { final String fullUrl = StringUtil.getTrimedString(etUIAutoListUrl) + StringUtil.getString((TextView) v).toLowerCase(); pbUIAutoList.setVisibility(View.VISIBLE); if (hasTempTouchList == false) { hasTempTouchList = true; cache.edit().remove(cacheKey).putString(cacheKey, JSON.toJSONString(touchList)).apply(); } if (isLocal) { statueList = new HashMap<>(); if (touchList != null) { for (int i = 0; i < touchList.size(); i++) { JSONObject touch = touchList.getJSONObject(i); String state = statueList.get(touch); if ("Remote".equals(state) || "Uploading".equals(state)) { return; } statueList.put(touch, "Uploading"); JSONRequest request = new JSONRequest(); { // Touch <<<<<<<<<<<<<<<<<<<<<<<<<<<<< request.put("Touch", touch); } // Touch >>>>>>>>>>>>>>>>>>>>>>>>>>>>> request.setTag("Touch"); pbUIAutoList.setVisibility(View.VISIBLE); HttpManager.getInstance().post(fullUrl, request.toString(), new HttpManager.OnHttpResponseListener() { @Override public void onHttpResponse(int requestCode, String resultJson, Exception e) { JSONResponse response = new JSONResponse(resultJson); if (response.isSuccess()) { statueList.put(touch, "Remote"); } else { statueList.put(touch, "Local"); } showList(array); } }); } } } else { JSONRequest request = new JSONRequest(); if (isTouch) { { // Touch[] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< JSONRequest touchItem = new JSONRequest(); { // Touch <<<<<<<<<<<<<<<<<<<<<<<<<<<<< JSONRequest touch = new JSONRequest(); touch.put("flowId", flowId); touchItem.put("Touch", touch); } // Touch >>>>>>>>>>>>>>>>>>>>>>>>>>>>> request.putAll(touchItem.toArray(0, 0, "Touch")); } // Touch[] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> } else { { // Flow[] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< JSONRequest flowItem = new JSONRequest(); { // Flow <<<<<<<<<<<<<<<<<<<<<<<<<<<<< JSONRequest flow = new JSONRequest(); flowItem.put("Flow", flow); } // Flow >>>>>>>>>>>>>>>>>>>>>>>>>>>>> request.putAll(flowItem.toArray(0, 0, "Flow")); } // Flow[] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> } HttpManager.getInstance().post(fullUrl, request.toString(), this); } } public void recover(View v) { setResult(RESULT_OK, new Intent().putExtra(RESULT_LIST, JSON.toJSONString(array))); finish(); } private JSONArray array; @Override public void onHttpResponse(int requestCode, String resultJson, Exception e) { Log.d(TAG, "onHttpResponse resultJson = " + resultJson); if (e != null) { Log.e(TAG, "onHttpResponse e = " + e.getMessage()); } JSONResponse response = new JSONResponse(resultJson); array = response.getJSONArray(isTouch ? "Touch[]" : "Flow[]"); if (array == null) { array = new JSONArray(); } statueList = new HashMap<>(); for (int i = 0; i < array.size(); i++) { statueList.put(array.getJSONObject(i), "Remote"); } showList(array); } private static final int REQUEST_TOUCH_LIST = 1; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { return; } if (requestCode == REQUEST_TOUCH_LIST) { setResult(RESULT_OK, data); finish(); } } }
923e7a06b0e7ad5b79d598fdb69bf4cc06b7bf44
874
java
Java
Algorithms/Implementation/Circular_Array_Rotation.java
jaswal72/hacker-rank
95aaa71b4636928664341dc9c6f75d69af5f26ac
[ "MIT" ]
1
2017-03-27T18:21:38.000Z
2017-03-27T18:21:38.000Z
Algorithms/Implementation/Circular_Array_Rotation.java
jaswal72/hacker-rank
95aaa71b4636928664341dc9c6f75d69af5f26ac
[ "MIT" ]
null
null
null
Algorithms/Implementation/Circular_Array_Rotation.java
jaswal72/hacker-rank
95aaa71b4636928664341dc9c6f75d69af5f26ac
[ "MIT" ]
null
null
null
23.621622
76
0.616705
1,000,775
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; class Solution { public static void main(String ... ags)throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tk = new StringTokenizer(in.readLine()); int n = Integer.parseInt(tk.nextToken()); int k = Integer.parseInt(tk.nextToken()); int q = Integer.parseInt(tk.nextToken()); int [] arr = new int[n]; tk = new StringTokenizer(in.readLine()); if(k>=n) { k = k - (k/n)*n ; } for(int i=0;i<n;i++) { int val = i + k ; if(val>=n) { val -= n ; } arr[val] = Integer.parseInt(tk.nextToken()); } for(int i=0;i<q;i++) { int val = Integer.parseInt(in.readLine()); System.out.println(arr[val]); } } }
923e7b25ac51e9501262851d5828dd2be1e59418
307
java
Java
SpringBoot/learn_01/s_2/src/main/java/com/rzhylj/S2Application.java
qvtu/spring
72ba5050411ecba759461021b8d5d4df4dc715ac
[ "MIT" ]
null
null
null
SpringBoot/learn_01/s_2/src/main/java/com/rzhylj/S2Application.java
qvtu/spring
72ba5050411ecba759461021b8d5d4df4dc715ac
[ "MIT" ]
null
null
null
SpringBoot/learn_01/s_2/src/main/java/com/rzhylj/S2Application.java
qvtu/spring
72ba5050411ecba759461021b8d5d4df4dc715ac
[ "MIT" ]
null
null
null
21.928571
68
0.781759
1,000,776
package com.rzhylj; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class S2Application { public static void main(String[] args) { SpringApplication.run(S2Application.class, args); } }
923e7bb1a33eac2ccb4e665f6b73bb0fc7c82a61
2,178
java
Java
protomed-web/src/main/java/ch/bfh/bti7081/s2020/green/protomed/view/ClientViewImplementation.java
moera1/ch.bfh.bti7081.s2020.green
760d7830b64121f580d5d97fedcf95a701ad5023
[ "Unlicense" ]
null
null
null
protomed-web/src/main/java/ch/bfh/bti7081/s2020/green/protomed/view/ClientViewImplementation.java
moera1/ch.bfh.bti7081.s2020.green
760d7830b64121f580d5d97fedcf95a701ad5023
[ "Unlicense" ]
4
2021-03-10T17:16:39.000Z
2021-08-30T16:27:37.000Z
protomed-web/src/main/java/ch/bfh/bti7081/s2020/green/protomed/view/ClientViewImplementation.java
moera1/ch.bfh.bti7081.s2020.green
760d7830b64121f580d5d97fedcf95a701ad5023
[ "Unlicense" ]
1
2020-03-28T21:14:37.000Z
2020-03-28T21:14:37.000Z
32.507463
85
0.666667
1,000,777
package ch.bfh.bti7081.s2020.green.protomed.view; import ch.bfh.bti7081.s2020.green.protomed.component.ClientListItem; import ch.bfh.bti7081.s2020.green.protomed.model.HealthClient; import com.github.appreciated.card.ClickableCard; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import java.util.ArrayList; import java.util.List; import java.util.Set; public class ClientViewImplementation extends VerticalLayout implements ClientView { private List<ClientViewListener> listeners = new ArrayList<ClientViewListener>(); private VerticalLayout healthClientList; public ClientViewImplementation() { add(new H2("Alle Klienten")); TextField search = new TextField(); search.setPlaceholder("Suche Klient"); search.setAutoselect(true); search.addValueChangeListener(e -> { for (ClientViewListener listener : listeners) listener.setSearchValue(e.getValue().toString()); }); search.setWidthFull(); add(search); healthClientList = new VerticalLayout(); healthClientList.setWidthFull(); healthClientList.setMargin(false); healthClientList.setPadding(false); add(healthClientList); } public void updateHealthClientList(Set<HealthClient> clients) { healthClientList.removeAll(); for (HealthClient client : clients) { ClickableCard clientCard = new ClickableCard( onClick -> { for (ClientViewListener listener : listeners) listener.selectClient(client); }, new ClientListItem(client) ); clientCard.setWidthFull(); healthClientList.add(clientCard); } } public void navigateToClientProfile(int id) { UI.getCurrent().navigate("client/" + Integer.toString(id)); } @Override public void addListener(ClientViewListener listener) { listeners.add(listener); } }
923e7bd6c8aa4e6448f1a37d23f8af05c25114ba
105
java
Java
summer-db/src/main/java/cn/cerc/db/editor/SetTextEvent.java
cn-cerc/summer-model
1c3dc54093d19ea1f061a1f5564eb4203bd4aeb9
[ "Apache-2.0" ]
null
null
null
summer-db/src/main/java/cn/cerc/db/editor/SetTextEvent.java
cn-cerc/summer-model
1c3dc54093d19ea1f061a1f5564eb4203bd4aeb9
[ "Apache-2.0" ]
null
null
null
summer-db/src/main/java/cn/cerc/db/editor/SetTextEvent.java
cn-cerc/summer-model
1c3dc54093d19ea1f061a1f5564eb4203bd4aeb9
[ "Apache-2.0" ]
null
null
null
13.125
32
0.67619
1,000,778
package cn.cerc.db.editor; public interface SetTextEvent { Object setText(String text); }
923e7bf5529b172642a726dc8138b50ab704a6c0
572
java
Java
org-code-javabuilder/lib/src/main/java/org/code/javabuilder/FileNameUtils.java
code-dot-org/javabuilder
28bda6d12582eb746ce4f718f008c9e972f56cf6
[ "Apache-2.0" ]
2
2021-06-16T20:08:43.000Z
2021-09-09T21:45:53.000Z
org-code-javabuilder/lib/src/main/java/org/code/javabuilder/FileNameUtils.java
code-dot-org/javabuilder
28bda6d12582eb746ce4f718f008c9e972f56cf6
[ "Apache-2.0" ]
42
2021-05-12T17:14:58.000Z
2022-03-23T20:35:45.000Z
org-code-javabuilder/lib/src/main/java/org/code/javabuilder/FileNameUtils.java
code-dot-org/javabuilder
28bda6d12582eb746ce4f718f008c9e972f56cf6
[ "Apache-2.0" ]
2
2021-12-14T19:56:54.000Z
2022-03-21T22:10:52.000Z
31.777778
99
0.718531
1,000,779
package org.code.javabuilder; /** Convenience methods for handling file names */ public class FileNameUtils { public static final String JAVA_EXTENSION = ".java"; /** * Whether the given file name is a valid Java file name. Must end with ".java" and have at least * one character before the extension. * * @param fileName file name to check * @return whether the file name is a valid Java file name */ public static boolean isJavaFile(String fileName) { return fileName.endsWith(JAVA_EXTENSION) && fileName.indexOf(JAVA_EXTENSION) > 0; } }
923e7ceca940690ec581ec5f7c1ff37a43b671fa
6,704
java
Java
geoportal/src/com/esri/gpt/catalog/discovery/PropertyClause.java
tomkralidis/geoportal-server
9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee
[ "Apache-2.0" ]
6
2015-03-23T16:56:41.000Z
2020-01-21T09:34:14.000Z
geoportal/src/com/esri/gpt/catalog/discovery/PropertyClause.java
tomkralidis/geoportal-server
9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee
[ "Apache-2.0" ]
9
2015-06-04T19:16:03.000Z
2015-08-03T17:01:30.000Z
geoportal/src/com/esri/gpt/catalog/discovery/PropertyClause.java
tomkralidis/geoportal-server
9844d7caa1f0b9fdf2b76b336ca7aa213fbd59ee
[ "Apache-2.0" ]
5
2015-03-18T20:37:09.000Z
2018-11-15T11:59:59.000Z
33.688442
82
0.634099
1,000,780
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.gpt.catalog.discovery; /** * A clause that compares a stored property to a supplied literal. */ public class PropertyClause extends DiscoveryClause { /** instance variables ====================================================== */ private String literal; private Discoverable target; /** constructors ============================================================ */ /** Default constructor. */ private PropertyClause() {} /** properties ============================================================== */ /** * Gets the literal value that constrains the clause. * @return the literal value */ public String getLiteral() { return literal; } /** * Sets the literal value that constrains the clause. * @param literal the literal value */ public void setLiteral(String literal) { this.literal = literal; } /** * Gets the discoverable property targeted by the clause. * @return the target */ public Discoverable getTarget() { return target; } /** * Sets the discoverable property targeted by the clause. * @param target the target */ public void setTarget(Discoverable target) { this.target = target; } /** methods ================================================================= */ /** * Appends property information for the component to a buffer. * @param sb the buffer to use when appending information * @param depth the depth of the clause */ @Override public void echo(StringBuffer sb, int depth) { StringBuffer sbDepth = new StringBuffer(); for (int i=0;i<2*depth;i++) sbDepth.append(" "); sb.append(sbDepth).append(getClass().getSimpleName()).append(":"); if (this instanceof PropertyIsBetween) { PropertyIsBetween between = (PropertyIsBetween)this; sb.append("\n").append(sbDepth); sb.append(" lowerBoundary=\"").append( between.getLowerBoundary()).append("\""); sb.append("\n").append(sbDepth); sb.append(" upperBoundary=\"").append( between.getUpperBoundary()).append("\""); } else { sb.append("\n").append(sbDepth); sb.append(" literal=\"").append(getLiteral()).append("\""); if (this instanceof PropertyIsLike) { PropertyIsLike like = (PropertyIsLike)this; sb.append("\n").append(sbDepth).append(" "); sb.append(" escapeChar=\"").append(like.getEscapeChar()).append("\""); sb.append(" singleChar=\"").append(like.getSingleChar()).append("\""); sb.append(" wildCard=\"").append(like.getWildCard()).append("\""); } } getTarget().echo(sb.append("\n"),depth+1); } /** inner classes =========================================================== */ /** A property comparison between two literals. */ public static class PropertyIsBetween extends PropertyClause { /* instance variables */ private String lowerBoundary; private String upperBoundary; /** Default constructor. */ public PropertyIsBetween() {super();} /** Gets the lower boundary. */ public String getLowerBoundary() {return lowerBoundary;} /** Sets the lower boundary. */ public void setLowerBoundary(String value) {lowerBoundary = value;} /** Gets the upper boundary. */ public String getUpperBoundary() {return upperBoundary;} /** Sets the upper boundary. */ public void setUpperBoundary(String value) {upperBoundary = value;} } /** A property is equal to a literal comparison. */ public static class PropertyIsEqualTo extends PropertyClause { public PropertyIsEqualTo() {super();} } /** A property is greater than a literal comparison. */ public static class PropertyIsGreaterThan extends PropertyClause { public PropertyIsGreaterThan() {super();} } /** A property is greater than or equal to a literal comparison. */ public static class PropertyIsGreaterThanOrEqualTo extends PropertyClause { public PropertyIsGreaterThanOrEqualTo() {super();} } /** A property is less than a literal comparison. */ public static class PropertyIsLessThan extends PropertyClause { public PropertyIsLessThan() {super();} } /** A property is less than or equal to a literal comparison. */ public static class PropertyIsLessThanOrEqualTo extends PropertyClause { public PropertyIsLessThanOrEqualTo() {super();} } /** A property is like a literal comparison. */ public static class PropertyIsLike extends PropertyClause { /* instance variables */ private String escapeChar = ""; private String singleChar = ""; private String wildCard = ""; /** Default constructor. */ public PropertyIsLike() {super();} /** Gets the escape character.*/ public String getEscapeChar() {return escapeChar;} /** Sets the escape character. */ public void setEscapeChar(String escapeChar) { this.escapeChar = escapeChar; if (this.escapeChar.length() > 1) this.escapeChar = ""; } /** Gets the single pattern match character. */ public String getSingleChar() {return singleChar;} /** Sets the single pattern match character. */ public void setSingleChar(String singleChar) { this.singleChar = singleChar; if (this.singleChar.length() > 1) this.singleChar = ""; } /** Gets the wild card character. */ public String getWildCard() {return wildCard;} /** Sets the wild card character. */ public void setWildCard(String wildCard) { this.wildCard = wildCard; if (this.wildCard.length() > 1) this.wildCard = ""; } } /** A property is not equal to a literal comparison. */ public static class PropertyIsNotEqualTo extends PropertyClause { public PropertyIsNotEqualTo() {super();} } /** A property is null comparison */ public static class PropertyIsNull extends PropertyClause { public PropertyIsNull() {super();} } }
923e7da97e4d6f0ea702926ea976d5d7a71b0b62
1,091
java
Java
spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/SubjectNamingStrategy.java
zhouzhou19950825/spring-cloud-stream
0075d094fcbea57661d3121bfab3772dcebfa182
[ "Apache-2.0" ]
1
2020-04-07T08:34:04.000Z
2020-04-07T08:34:04.000Z
spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/SubjectNamingStrategy.java
zhouzhou19950825/spring-cloud-stream
0075d094fcbea57661d3121bfab3772dcebfa182
[ "Apache-2.0" ]
1
2022-01-21T23:49:54.000Z
2022-01-21T23:49:54.000Z
spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/SubjectNamingStrategy.java
zhouzhou19950825/spring-cloud-stream
0075d094fcbea57661d3121bfab3772dcebfa182
[ "Apache-2.0" ]
null
null
null
29.486486
84
0.741522
1,000,781
/* * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.stream.schema.avro; import org.apache.avro.Schema; /** * Provides function towards naming schema registry subjects for Avro files. * * @author David Kalosi */ public interface SubjectNamingStrategy { /** * Takes the Avro schema on input and returns the generated subject under which the * schema should be registered. * @param schema schema to register * @return subject name */ String toSubject(Schema schema); }
923e7e9418ea1f0b2850cf41ba61e74090c7e604
55
java
Java
baseline/src/main/java/cmaps/io/Format.java
UKPLab/emnlp2017-cmapsum-corpus
ea746fb3784941a389cb29a7cc312a109f4619b6
[ "MIT" ]
13
2017-08-16T19:09:19.000Z
2021-07-01T09:49:24.000Z
baseline/src/main/java/cmaps/io/Format.java
UKPLab/emnlp2017-cmapsum-corpus
ea746fb3784941a389cb29a7cc312a109f4619b6
[ "MIT" ]
1
2017-09-27T09:16:46.000Z
2017-09-27T09:19:40.000Z
baseline/src/main/java/cmaps/io/Format.java
UKPLab/emnlp2017-cmapsum-corpus
ea746fb3784941a389cb29a7cc312a109f4619b6
[ "MIT" ]
3
2017-07-14T09:10:52.000Z
2017-08-23T07:56:54.000Z
11
21
0.654545
1,000,782
package cmaps.io; public enum Format { TSV, CXL }
923e7e965c0646671e1fe50b55cfeee672683b8a
508
java
Java
src/main/java/de/karimbkb/wishlistgraphqlapi/exception/WishlistNotFoundException.java
karimbkb/wishlist-graphql-api
d91ebd2bab796d75c19dc515584543a62e6ae400
[ "Apache-2.0" ]
1
2022-01-28T13:21:48.000Z
2022-01-28T13:21:48.000Z
src/main/java/de/karimbkb/wishlistgraphqlapi/exception/WishlistNotFoundException.java
karimbkb/wishlist-graphql-api
d91ebd2bab796d75c19dc515584543a62e6ae400
[ "Apache-2.0" ]
null
null
null
src/main/java/de/karimbkb/wishlistgraphqlapi/exception/WishlistNotFoundException.java
karimbkb/wishlist-graphql-api
d91ebd2bab796d75c19dc515584543a62e6ae400
[ "Apache-2.0" ]
null
null
null
31.75
97
0.787402
1,000,783
package de.karimbkb.wishlistgraphqlapi.exception; import de.karimbkb.wishlistgraphqlapi.dto.Customer; import javax.validation.Valid; public class WishlistNotFoundException extends RuntimeException { public WishlistNotFoundException(String message) { super(message); } public static WishlistNotFoundException withCustomer(@Valid Customer customer) { return new WishlistNotFoundException( String.format("Wishlist for customer with id %s could not be found.", customer.getId())); } }
923e7ede16e31549cbc33eb5da467165e810f126
1,031
java
Java
src/net/arx.java
josesilveiraa/novoline
9146c4add3aa518d9aa40560158e50be1b076cf0
[ "Unlicense" ]
5
2022-02-04T12:57:17.000Z
2022-03-26T16:12:16.000Z
src/net/arx.java
josesilveiraa/novoline
9146c4add3aa518d9aa40560158e50be1b076cf0
[ "Unlicense" ]
2
2022-02-25T20:10:14.000Z
2022-03-03T14:25:03.000Z
src/net/arx.java
josesilveiraa/novoline
9146c4add3aa518d9aa40560158e50be1b076cf0
[ "Unlicense" ]
1
2021-11-28T09:59:55.000Z
2021-11-28T09:59:55.000Z
21.93617
90
0.672163
1,000,784
package net; import net.acE; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.Achievement; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatFileWriter; public class arx { private static acE[] b; public static int a(StatFileWriter var0, StatBase var1) { return var0.readStat(var1); } public static void a(StatFileWriter var0, EntityPlayer var1, StatBase var2, int var3) { var0.unlockAchievement(var1, var2, var3); } public static boolean c(StatFileWriter var0, Achievement var1) { return var0.hasAchievementUnlocked(var1); } public static boolean a(StatFileWriter var0, Achievement var1) { return var0.canUnlockAchievement(var1); } public static int b(StatFileWriter var0, Achievement var1) { return var0.func_150874_c(var1); } public static void b(acE[] var0) { b = var0; } public static acE[] b() { return b; } static { if(b() == null) { b(new acE[1]); } } }
923e80b0deeb3e0d310d7b068827591ac2fda2a3
1,976
java
Java
clever-security-embed/src/main/java/org/clever/security/event/HttpSessionDestroyedListener.java
Lzw2016/clever-security
a0f92b63b5a4488db1d115360eece97b7e73fa3f
[ "MIT" ]
16
2018-10-23T08:32:02.000Z
2021-12-09T05:26:23.000Z
clever-security-embed/src/main/java/org/clever/security/event/HttpSessionDestroyedListener.java
Lzw2016/clever-security
a0f92b63b5a4488db1d115360eece97b7e73fa3f
[ "MIT" ]
1
2020-11-28T09:12:10.000Z
2020-11-28T09:12:10.000Z
clever-security-embed/src/main/java/org/clever/security/event/HttpSessionDestroyedListener.java
Lzw2016/clever-security
a0f92b63b5a4488db1d115360eece97b7e73fa3f
[ "MIT" ]
2
2018-10-23T08:57:48.000Z
2021-05-27T16:44:17.000Z
38
97
0.680668
1,000,785
package org.clever.security.event; import lombok.extern.slf4j.Slf4j; import org.clever.security.LoginModel; import org.clever.security.client.UserLoginLogClient; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.request.UserLoginLogUpdateReq; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.UserLoginLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.security.core.session.SessionDestroyedEvent; import org.springframework.stereotype.Component; /** * 作者: lzw<br/> * 创建时间:2018-09-23 19:33 <br/> */ @Component @Slf4j public class HttpSessionDestroyedListener implements ApplicationListener<SessionDestroyedEvent> { @Autowired private SecurityConfig securityConfig; @Autowired private UserLoginLogClient userLoginLogClient; @SuppressWarnings("NullableProblems") @Override public void onApplicationEvent(SessionDestroyedEvent event) { // org.springframework.session.events.SessionDestroyedEvent; if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { log.error("### 注销Session [{}] -> 不应该创建HttpSession", event.getId()); } else { try { log.info("### 注销Session [{}]", event.getId()); UserLoginLog userLoginLog = userLoginLogClient.getUserLoginLog(event.getId()); if (userLoginLog == null) { log.warn("### 注销Session未能找到对应的登录日志 [{}]", event.getId()); return; } // 设置登录过期 UserLoginLogUpdateReq req = new UserLoginLogUpdateReq(); req.setLoginState(EnumConstant.UserLoginLog_LoginState_2); userLoginLogClient.updateUserLoginLog(event.getId(), req); } catch (Exception e) { log.error("更新Session注销信息失败", e); } } } }
923e82321efb689898d74e5e35f6fcbc8527cdb9
2,870
java
Java
tool/src/main/java/org/imzdong/tool/ticket/core/GetJsCookie.java
imzdong/study
a789f7534637a95949c3a0a202b8c04dbdfb7916
[ "Apache-2.0" ]
null
null
null
tool/src/main/java/org/imzdong/tool/ticket/core/GetJsCookie.java
imzdong/study
a789f7534637a95949c3a0a202b8c04dbdfb7916
[ "Apache-2.0" ]
2
2020-01-18T12:48:47.000Z
2020-01-18T12:49:22.000Z
tool/src/main/java/org/imzdong/tool/ticket/core/GetJsCookie.java
imzdong/study
a789f7534637a95949c3a0a202b8c04dbdfb7916
[ "Apache-2.0" ]
null
null
null
38.266667
114
0.580836
1,000,786
package org.imzdong.tool.ticket.core; import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.util.WebConnectionWrapper; import org.apache.commons.lang3.StringUtils; import org.imzdong.tool.ticket.util.HttpUtil; import org.imzdong.tool.ticket.util.UrlConf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * @description: * @author: Winter * @time: 2020/1/5 */ public class GetJsCookie { private Logger logger = LoggerFactory.getLogger(GetJsCookie.class); private String cookieUrl = null; public String getCookieUrl(String ip, String port) { WebClient wc = null; logger.info("登录初始化:1.1、初始化/otn/HttpZF/logdevice请求地址"); try { if (StringUtils.isNotBlank(ip)) { wc = new WebClient(BrowserVersion.CHROME, ip, Integer.parseInt(port)); } else { wc = new WebClient(); } wc.getOptions().setTimeout(15000); wc.getOptions().setUseInsecureSSL(true); wc.getOptions().setJavaScriptEnabled(true); wc.getOptions().setCssEnabled(false); //当JS执行出错的时候是否抛出异常, 这里选择不需要 wc.getOptions().setThrowExceptionOnScriptError(true); //当HTTP的状态非200时是否抛出异常 wc.getOptions().setThrowExceptionOnFailingStatusCode(true); //很重要,设置支持AJAX wc.setAjaxController(new AjaxController() { private static final long serialVersionUID = -7255795662011210223L; @Override public boolean processSynchron(HtmlPage page, WebRequest settings, boolean async) { // logger.info("AjaxController " + settings.getUrl().toString()); return super.processSynchron(page, settings, async); } }); wc.setWebConnection( new WebConnectionWrapper(wc) { @Override public WebResponse getResponse(WebRequest request) throws IOException { WebResponse response = super.getResponse(request); if (request.getUrl().toExternalForm().contains(UrlConf.LOG_DEVICE.getRequestPath())) { cookieUrl = request.getUrl().toExternalForm(); } return response; } } ); wc.getPage(HttpUtil.REQUEST_HOST+UrlConf.OTN_INIT.getRequestPath()); wc.waitForBackgroundJavaScript(3 * 1000); } catch (Exception e) { logger.error("获取失败cookie url", e); } finally { if (wc!=null) { wc.close(); } } return cookieUrl; } }
923e82945383eb53b8df8cdba8c9b643bc447bac
2,785
java
Java
rosandroid-example-app/src/main/java/org/ollide/rosandroid/BottomSheet.java
abdelrahman-osama/SDC-Dashboard-ROS
7e427013f7629e2aec4a342c79d68d4821b7a27d
[ "Apache-2.0" ]
null
null
null
rosandroid-example-app/src/main/java/org/ollide/rosandroid/BottomSheet.java
abdelrahman-osama/SDC-Dashboard-ROS
7e427013f7629e2aec4a342c79d68d4821b7a27d
[ "Apache-2.0" ]
null
null
null
rosandroid-example-app/src/main/java/org/ollide/rosandroid/BottomSheet.java
abdelrahman-osama/SDC-Dashboard-ROS
7e427013f7629e2aec4a342c79d68d4821b7a27d
[ "Apache-2.0" ]
null
null
null
30.944444
123
0.755835
1,000,787
/*package com.example.hadwa.myapplication; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.BottomSheetDialog; import android.support.design.widget.BottomSheetDialogFragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; public class BottomSheet extends BottomSheetDialogFragment { private BottomSheetBehavior mBehavior; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState); View view = View.inflate(getContext(), R.layout.bottom_sheet_layout, null); //view.findViewById(R.id.fakeShadow).setVisibility(View.GONE); //RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); //recyclerView.setHasFixedSize(true); //recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // ItemAdapter itemAdapter = new ItemAdapter(createItems(), this); //recyclerView.setAdapter(itemAdapter); dialog.setContentView(view); mBehavior = BottomSheetBehavior.from((View) view.getParent()); return dialog; } @Override public void onStart() { super.onStart(); mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } }*/ /* import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.BottomSheetDialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; public class BottomSheet extends BottomSheetBehavior { private BottomSheetBehavior BottomSheetBehavior; private View bottomsheetFragment ; private TextView Marker; public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v =inflater.inflate(R.layout.bottom_sheet_layout,container,false); bottomsheetFragment=v.findViewById(R.id.bottomsheet); BottomSheetBehavior=BottomSheetBehavior.from(bottomsheetFragment); Marker=v.findViewById(R.id.WhichStop); return v; } public void expand(com.google.android.gms.maps.model.Marker marker){ BottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); Marker.setText(marker.getTitle()); } } */
923e82ccbc5a1fe2c1d04f455248b8df1aa69569
2,053
java
Java
jxen-math-expression/src/main/java/com/github/jxen/math/expression/MathOperator.java
jxen/jxen-math
a2b4724dc1e68b314f7e8a41bc7f1d00cbf8df8c
[ "Apache-2.0" ]
null
null
null
jxen-math-expression/src/main/java/com/github/jxen/math/expression/MathOperator.java
jxen/jxen-math
a2b4724dc1e68b314f7e8a41bc7f1d00cbf8df8c
[ "Apache-2.0" ]
null
null
null
jxen-math-expression/src/main/java/com/github/jxen/math/expression/MathOperator.java
jxen/jxen-math
a2b4724dc1e68b314f7e8a41bc7f1d00cbf8df8c
[ "Apache-2.0" ]
null
null
null
21.164948
116
0.654652
1,000,788
package com.github.jxen.math.expression; import java.util.function.DoubleBinaryOperator; /** * {@code MathOperator} class represents mathematical operator. * * @author Denis Murashev * @since Math Expression Parser 0.1 */ public final class MathOperator { /** * To be moved. */ static final int LOW_PRIORITY = 1; /** * To be moved. */ static final int MEDIUM_PRIORITY = 2; /** * To be moved. */ static final int HIGH_PRIORITY = 3; private final String symbol; private final int priority; private final boolean emptyLeftOperandAllowed; private final DoubleBinaryOperator operator; /** * Initializes with given values. * * @param symbol symbol * @param priority priority * @param emptyLeftOperandAllowed flag * @param operator operator */ public MathOperator(String symbol, int priority, boolean emptyLeftOperandAllowed, DoubleBinaryOperator operator) { this.symbol = symbol; this.priority = priority; this.emptyLeftOperandAllowed = emptyLeftOperandAllowed; this.operator = operator; } /** * Initializes with given values. * * @param symbol symbol * @param priority priority * @param operator operator */ public MathOperator(String symbol, int priority, DoubleBinaryOperator operator) { this(symbol, priority, false, operator); } /** * Provides symbol. * * @return operator symbol */ String getSymbol() { return symbol; } /** * Provides priority. * * @return operator priority */ int getPriority() { return priority; } /** * Checks if left operand is allowed. * * @return {@code true} if left operand is allowed */ boolean isEmptyLeftOperandAllowed() { return emptyLeftOperandAllowed; } /** * Evaluates operation. * * @param left left operand * @param right right operand * @return result */ double evaluate(double left, double right) { return operator.applyAsDouble(left, right); } }
923e83fb653e63aef034c9246b019062d4dc1b73
9,438
java
Java
src/main/java/com/yiting/toeflvoc/services/VocabularyBeanService.java
shenyiting2018/toefl-vocabulary-helper
8583dc67dee7b7130037fe2b333b865073c4e74a
[ "MIT" ]
1
2019-11-22T06:47:09.000Z
2019-11-22T06:47:09.000Z
src/main/java/com/yiting/toeflvoc/services/VocabularyBeanService.java
shenyiting2018/toefl-vocabulary-helper
8583dc67dee7b7130037fe2b333b865073c4e74a
[ "MIT" ]
null
null
null
src/main/java/com/yiting/toeflvoc/services/VocabularyBeanService.java
shenyiting2018/toefl-vocabulary-helper
8583dc67dee7b7130037fe2b333b865073c4e74a
[ "MIT" ]
null
null
null
35.885932
153
0.710108
1,000,789
package com.yiting.toeflvoc.services; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.yiting.toeflvoc.beans.AliasBean; import com.yiting.toeflvoc.beans.AnalyzeResultBean; import com.yiting.toeflvoc.beans.RootBean; import com.yiting.toeflvoc.beans.UserWordBean; import com.yiting.toeflvoc.beans.WordBean; import com.yiting.toeflvoc.models.Category; import com.yiting.toeflvoc.models.RootAliasMap; import com.yiting.toeflvoc.models.Word; import com.yiting.toeflvoc.models.WordCategoryMap; import com.yiting.toeflvoc.models.WordRootMap; import com.yiting.toeflvoc.utils.ResourceNotFoundException; @Service public class VocabularyBeanService { @Autowired private VocabularyModelService modelService; private final Logger logger = LoggerFactory.getLogger(VocabularyBeanService.class); private Map<Integer, AliasBean> aliasBeansCache = new HashMap<>(); private Map<Integer, RootBean> rootBeansCache = new HashMap<>(); private Map<Integer, WordBean> wordBeansCache = new HashMap<>(); private Map<Integer, AliasBean> getAliasBeansCache() { if (this.aliasBeansCache.isEmpty()) { long t1 = System.currentTimeMillis(); List<RootAliasMap> maps = this.modelService.getAllRootAliasMaps(); for (RootAliasMap map : maps) { this.aliasBeansCache.putIfAbsent(map.getAlias().getId(), new AliasBean(map.getAlias(), new ArrayList<>())); this.aliasBeansCache.get(map.getAlias().getId()).getRootAliasMaps().add(map); } logger.info(String.format("alisBeanCache reinited in %d milliseconds.", System.currentTimeMillis() - t1)); } return this.aliasBeansCache; } private Map<Integer, RootBean> getRootBeansCache() { if (this.rootBeansCache.isEmpty()) { long t1 = System.currentTimeMillis(); List<WordRootMap> wordRootMaps = this.modelService.getAllWordRootMaps(); List<RootAliasMap> rootAliasMaps = this.modelService.getAllRootAliasMaps(); for (WordRootMap map : wordRootMaps) { this.rootBeansCache.putIfAbsent(map.getRoot().getId(), new RootBean(map.getRoot(), new ArrayList<>(), new ArrayList<>())); this.rootBeansCache.get(map.getRoot().getId()).getWordRootMaps().add(map); } for (RootAliasMap map : rootAliasMaps) { this.rootBeansCache.putIfAbsent(map.getRoot().getId(), new RootBean(map.getRoot(), new ArrayList<>(), new ArrayList<>())); this.rootBeansCache.get(map.getRoot().getId()).getRootAliasMaps().add(map); } logger.info(String.format("rootBeansCache reinited in %d milliseconds.", System.currentTimeMillis() - t1)); } return this.rootBeansCache; } public void invalideCache() { this.aliasBeansCache.clear(); this.rootBeansCache.clear(); this.wordBeansCache.clear(); //logger.info("All cache cleared"); } @Transactional(readOnly=true) private Map<Integer, WordBean> getWordBeansCache() { if (this.wordBeansCache.isEmpty()) { long t1 = System.currentTimeMillis(); List<Word> allWords = this.modelService.getAllWords(); for (int i = 0; i < allWords.size(); i++) { Word word = allWords.get(i); List<WordRootMap> wordRootMaps = this.modelService.getWordRootMapsByWord(word.getId()); //List<WordCategoryMap> wordCategoryMap = this.modelService.getWordCategoryMapByWord(word.getId()); this.wordBeansCache.putIfAbsent(word.getId(), new WordBean(word, wordRootMaps, null)); } logger.info(String.format("wordBeansCache reinited in %d milliseconds.", System.currentTimeMillis() - t1)); } return this.wordBeansCache; } public List<AliasBean> getAllAliasBeans() { return new ArrayList<>(this.getAliasBeansCache().values()); } public List<RootBean> getAllRootBeans() { return new ArrayList<>(this.getRootBeansCache().values()); } public RootBean getRootBean(Integer rootId) throws ResourceNotFoundException { RootBean rootBean = this.getRootBeansCache().get(rootId); if (rootBean == null) { String msg = String.format("Cache invalidated for some reason, received rootID: %s, but not in rootBeansCache, reinitiating rootBeansCache", rootId); logger.info(msg); throw new ResourceNotFoundException(msg); } return rootBean; } public List<WordBean> getAllWordBeans() { return new ArrayList<>(this.getWordBeansCache().values()); } public WordBean getWordBean(Integer wordId) throws ResourceNotFoundException { //WordBean wordBean = this.getWordBeansCache().get(wordId); Word word = this.modelService.getWord(wordId); if (word == null) { return null; } else { List<WordRootMap> wordRootMaps = this.modelService.getWordRootMapsByWord(word.getId()); List<WordCategoryMap> wordCategoryMaps = this.modelService.getWordCategoryMapByWord(word.getId()); return new WordBean(word, wordRootMaps, wordCategoryMaps); } } @Transactional public List<AnalyzeResultBean> analyzeRootForWord(final String wordString) throws ResourceNotFoundException { Set<Integer> rootIdSet = new HashSet<>(); List<AnalyzeResultBean> res = new ArrayList<>(); Word word = this.modelService.getWordByWordString(wordString); if (word != null) { //If word already in DB, retrieve its current validated roots first. WordBean bean = this.getWordBean(word.getId()); for (WordRootMap map : bean.getWordRootMaps()) { rootIdSet.add(map.getRoot().getId()); res.add(new AnalyzeResultBean( map.getRoot().getId(), map.getRoot().getRootString(), map.getRoot().getRootString(), map.getRoot().getMeanings(), map.getDescription(), true) ); } } List<AnalyzeResultBean> analysis = new ArrayList<>(); for (AliasBean bean : this.getAllAliasBeans()) { for (RootAliasMap map : bean.getRootAliasMaps()) { if (!rootIdSet.contains(map.getRoot().getId()) && this.match(wordString, map.getAlias().getAliasString())) { analysis.add(new AnalyzeResultBean( map.getRoot().getId(), map.getAlias().getAliasString(), map.getRoot().getRootString(), map.getRoot().getMeanings(), "", false) ); } } } analysis.sort((a, b) -> { return a.getRootString().compareTo(b.getRootString()); }); res.addAll(analysis); return res; } private boolean match(String a, String b) { return a.contains(b); } /*@Transactional public List<WordBean> getCategoryWordBeans(String categoryName) { List<WordBean> wordBeans = new ArrayList<>(); Category category = this.modelService.getCategoryByCategoryName(categoryName); List<Word> words = new ArrayList<>(); if (category != null) { List<WordCategoryMap> maps = this.modelService.getWordCategoryMapByCategory(category.getId()); words = maps.stream() .map(map -> map.getWord()) .sorted((a, b) -> { return a.getWordString().compareTo(b.getWordString()); }) .collect(Collectors.toList()); for (Word word : words) { List<WordRootMap> wordRootMaps = this.modelService.getWordRootMapsByWord(word.getId()); wordBeans.add(new WordBean(word, wordRootMaps, null)); } } return wordBeans; }*/ public List<UserWordBean> getCategoryWordBeans(String categoryName, Integer userId) { List<UserWordBean> userWords = new ArrayList<>(); Category category = this.modelService.getCategoryByCategoryNameAndUser(categoryName, userId); if (category != null) { List<WordCategoryMap> maps = this.modelService.getWordCategoryMapByCategory(category.getId()); userWords = maps.stream() .map(map -> new UserWordBean(map.getWord(), map.getCategory(), map.getProficiency(), map.getListNumber())) .sorted((a, b) -> { return a.getWordString().compareTo(b.getWordString()); }) .collect(Collectors.toList()); } return userWords; } public List<UserWordBean> getGREAdditionalWordBeans(Integer userId) { List<UserWordBean> userWords = new ArrayList<>(); List<Category> categories = new ArrayList<>(); Category greBlanksCategory = this.modelService.getCategoryByCategoryNameAndUser("gre-blanks", userId); if (greBlanksCategory != null) categories.add(greBlanksCategory); Category greReadingsCategory = this.modelService.getCategoryByCategoryNameAndUser("gre-readings", userId); if (greReadingsCategory != null) categories.add(greReadingsCategory); Category greRootExpansaionCategory = this.modelService.getCategoryByCategoryNameAndUser("root-expansion", userId); if (greRootExpansaionCategory != null) categories.add(greRootExpansaionCategory); for (Category category : categories) { List<WordCategoryMap> maps = this.modelService.getWordCategoryMapByCategory(category.getId()); userWords.addAll(maps.stream() .map(map -> new UserWordBean(map.getWord(), map.getCategory(), map.getProficiency(), map.getListNumber())) .sorted((a, b) -> { return a.getWordString().compareTo(b.getWordString()); }) .collect(Collectors.toList())); } return userWords; } }
923e8504a072186db7401b2e739d3534924d7913
5,044
java
Java
MonitoringLayer/src/eu/qualimaster/monitoring/tracing/ReflectiveFileTrace.java
QualiMaster/Infrastructure
258557752070f4a2c4a18491fec110361e8fa0ee
[ "Apache-2.0" ]
2
2016-10-21T09:35:47.000Z
2017-01-24T21:49:23.000Z
MonitoringLayer/src/eu/qualimaster/monitoring/tracing/ReflectiveFileTrace.java
QualiMaster/Infrastructure
258557752070f4a2c4a18491fec110361e8fa0ee
[ "Apache-2.0" ]
23
2016-02-24T14:18:02.000Z
2017-01-18T13:34:50.000Z
MonitoringLayer/src/eu/qualimaster/monitoring/tracing/ReflectiveFileTrace.java
QualiMaster/Infrastructure
258557752070f4a2c4a18491fec110361e8fa0ee
[ "Apache-2.0" ]
3
2016-07-29T07:30:14.000Z
2016-09-24T12:29:39.000Z
33.403974
110
0.585448
1,000,790
package eu.qualimaster.monitoring.tracing; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import eu.qualimaster.monitoring.parts.PartType; import eu.qualimaster.monitoring.systemState.PipelineNodeSystemPart; import eu.qualimaster.monitoring.systemState.PipelineSystemPart; import eu.qualimaster.monitoring.systemState.PlatformSystemPart; import eu.qualimaster.monitoring.systemState.SystemState; /** * Represents a trace storing the information required for reflective adaptation. * * @author Andrea Ceroni */ public class ReflectiveFileTrace extends AbstractFileTrace { /** * Creates a new trace. * * @param name the name of the trace (for {link {@link #toString()}}, shall be the file name * @param out the output stream to trace to */ public ReflectiveFileTrace(String name, PrintStream out) { super(name, out); } /** * Traces the platform. * * @param state the system state */ private void tracePlatform(SystemState state) { PlatformSystemPart platform = state.getPlatform(); print("platform:"); printSeparator(); print(platform.getName()); printSeparator(); trace(platform, PlatformSystemPart.class, null, null, null); } /** * Traces a pipeline. * * @param state the system state * @param info the trace information * @param parameters the parameters */ private void tracePipeline(SystemState state, PipelineTraceInfo info, IParameterProvider parameters) { PipelineSystemPart pipeline = state.getPipeline(info.name); if (null != pipeline) { // unsure how this shall look for the reflective trace, pls check TracingTest print("pipeline:"); printSeparator(); print(pipeline.getName()); printSeparator(); trace(pipeline, PipelineSystemPart.class, null, null, null); Set<String> done = new HashSet<String>(); for (String nodeName : info.nodes) { PipelineNodeSystemPart node = pipeline.getNode(nodeName); tracePipelineNode(node); done.add(nodeName); } for (PipelineNodeSystemPart node : pipeline.getNodes()) { String name = node.getName(); if (!done.contains(name)) { tracePipelineNode(node); info.nodes.add(name); } } } //print("pipeline/"); } /** * Traces a single pipeline node. * * @param node the node to be traced */ private void tracePipelineNode(PipelineNodeSystemPart node) { if (null != node) { print("node:"); printSeparator(); print(node.getName()); printSeparator(); trace(node, PipelineNodeSystemPart.class, null, null, null); } } @Override public void traceInfrastructure(SystemState state, IParameterProvider parameters) { SystemState copy = new SystemState(state); if (!isInitialized() && null == pipelines) { pipelines = new ArrayList<PipelineTraceInfo>(); super.headers = new HashMap<String, ArrayList<String>>(); printFormat(PlatformSystemPart.class, PartType.PLATFORM, "platform format:\t"); printFormat(PipelineSystemPart.class, PartType.PIPELINE, "pipeline format:\t"); printFormat(PipelineNodeSystemPart.class, PartType.PIPELINE_NODE, "pipeline node format:\t"); println(); initialized = true; } super.latestMonitoring = ""; print(copy.getTimestamp()); printSeparator(); tracePlatform(copy); Set<String> pipelineDone = new HashSet<String>(); for (PipelineTraceInfo info : pipelines) { tracePipeline(copy, info, parameters); pipelineDone.add(info.name); } Collection<PipelineSystemPart> pipelines = copy.getPipelines(); for (PipelineSystemPart pipeline : pipelines) { String pName = pipeline.getName(); if (!pipelineDone.contains(pName)) { tracePipeline(copy, getTraceInfo(pName), parameters); } } println(); } /** * Returns the latest monitoring. * * @return the latest monitoring */ public String getLatestMonitoring() { return super.latestMonitoring; } /** * Returns the headers. * * @return the headers */ public Map<String, ArrayList<String>> getHeaders() { return super.headers; } }
923e854050f727ca9111d1dea274518cf800877d
1,141
java
Java
CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/events/handling/MCEntityLivingHurtEvent.java
justinrusso/CraftTweaker
bfb6289d9ed15ff8b062358d648f839ab2ed9a13
[ "MIT" ]
null
null
null
CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/events/handling/MCEntityLivingHurtEvent.java
justinrusso/CraftTweaker
bfb6289d9ed15ff8b062358d648f839ab2ed9a13
[ "MIT" ]
null
null
null
CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/events/handling/MCEntityLivingHurtEvent.java
justinrusso/CraftTweaker
bfb6289d9ed15ff8b062358d648f839ab2ed9a13
[ "MIT" ]
null
null
null
27.166667
77
0.687117
1,000,791
package crafttweaker.mc1120.events.handling; import crafttweaker.api.damage.IDamageSource; import crafttweaker.api.entity.IEntityLivingBase; import crafttweaker.api.event.EntityLivingHurtEvent; import crafttweaker.api.minecraft.CraftTweakerMC; import net.minecraftforge.event.entity.living.*; public class MCEntityLivingHurtEvent implements EntityLivingHurtEvent { private final LivingHurtEvent event; public MCEntityLivingHurtEvent(LivingHurtEvent event) { this.event = event; } @Override public IDamageSource getDamageSource() { return CraftTweakerMC.getIDamageSource(event.getSource()); } @Override public float getAmount() { return event.getAmount(); } @Override public boolean isCanceled() { return event.isCanceled(); } @Override public void setCanceled(boolean canceled) { event.setCanceled(canceled); } @Override public IEntityLivingBase getEntityLivingBase() { return CraftTweakerMC.getIEntityLivingBase(event.getEntityLiving()); } }
923e85c630280fddc471bae55ae392c9e79554cd
18,379
java
Java
tddl-optimizer/src/main/java/com/taobao/tddl/optimizer/core/ast/query/JoinNode.java
hejianzxl/TDDL-1
33ab99c37ae8b927f1cd3294d1ec8aa31b71c84b
[ "Apache-2.0" ]
35
2015-09-08T12:46:12.000Z
2021-09-10T02:17:31.000Z
tddl-optimizer/src/main/java/com/taobao/tddl/optimizer/core/ast/query/JoinNode.java
hejianzxl/TDDL-1
33ab99c37ae8b927f1cd3294d1ec8aa31b71c84b
[ "Apache-2.0" ]
null
null
null
tddl-optimizer/src/main/java/com/taobao/tddl/optimizer/core/ast/query/JoinNode.java
hejianzxl/TDDL-1
33ab99c37ae8b927f1cd3294d1ec8aa31b71c84b
[ "Apache-2.0" ]
63
2015-07-24T08:27:19.000Z
2022-01-17T07:16:25.000Z
37.054435
125
0.643996
1,000,792
package com.taobao.tddl.optimizer.core.ast.query; import static com.taobao.tddl.optimizer.utils.OptimizerToString.appendField; import static com.taobao.tddl.optimizer.utils.OptimizerToString.appendln; import static com.taobao.tddl.optimizer.utils.OptimizerToString.printFilterString; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.taobao.tddl.common.utils.GeneralUtil; import com.taobao.tddl.optimizer.core.ASTNodeFactory; import com.taobao.tddl.optimizer.core.ast.ASTNode; import com.taobao.tddl.optimizer.core.ast.QueryTreeNode; import com.taobao.tddl.optimizer.core.ast.build.JoinNodeBuilder; import com.taobao.tddl.optimizer.core.ast.build.QueryTreeNodeBuilder; import com.taobao.tddl.optimizer.core.expression.IBooleanFilter; import com.taobao.tddl.optimizer.core.expression.IOrderBy; import com.taobao.tddl.optimizer.core.expression.ISelectable; import com.taobao.tddl.optimizer.core.plan.query.IJoin; import com.taobao.tddl.optimizer.core.plan.query.IJoin.JoinStrategy; import com.taobao.tddl.optimizer.exceptions.QueryException; import com.taobao.tddl.optimizer.utils.FilterUtils; import com.taobao.tddl.optimizer.utils.OptimizerUtils; public class JoinNode extends QueryTreeNode { private JoinNodeBuilder builder; /** * join 策略 */ private JoinStrategy joinStrategy = JoinStrategy.NEST_LOOP_JOIN; /** * <pre> * leftOuterJoin: * leftOuter=true && rightOuter=false * rightOuterJoin: * leftOuter=false && rightOuter=true * innerJoin: * leftOuter=false && rightOuter=false * outerJoin: * leftOuter=true && rightOuter=true * </pre> */ private boolean leftOuter = false; private boolean rightOuter = false; private boolean isCrossJoin = false; private boolean usedForIndexJoinPK = false; private List<IBooleanFilter> joinFilter = new ArrayList(); private boolean needOptimizeJoinOrder = true; public JoinNode(){ builder = new JoinNodeBuilder(this); } public List<ISelectable> getLeftKeys() { List<ISelectable> leftKeys = new ArrayList<ISelectable>(this.getJoinFilter().size()); for (IBooleanFilter f : this.getJoinFilter()) { leftKeys.add((ISelectable) f.getColumn()); } return leftKeys; } public List<ISelectable> getRightKeys() { List<ISelectable> rightKeys = new ArrayList<ISelectable>(this.getJoinFilter().size()); for (IBooleanFilter f : this.getJoinFilter()) { rightKeys.add((ISelectable) f.getValue()); } return rightKeys; } public JoinNode addJoinKeys(ISelectable leftKey, ISelectable rightKey) { this.joinFilter.add(FilterUtils.equal(leftKey, rightKey)); setNeedBuild(true); return this; } public JoinNode addJoinKeys(String leftKey, String rightKey) { return this.addJoinKeys(OptimizerUtils.createColumnFromString(leftKey), OptimizerUtils.createColumnFromString(rightKey)); } public void addJoinFilter(IBooleanFilter filter) { this.joinFilter.add(filter); setNeedBuild(true); } public QueryTreeNode getLeftNode() { if (this.getChildren() == null || this.getChildren().isEmpty()) { return null; } return (QueryTreeNode) this.getChildren().get(0); } public QueryTreeNode getRightNode() { if (this.getChildren() == null || this.getChildren().size() < 2) { return null; } return (QueryTreeNode) this.getChildren().get(1); } public void setLeftNode(QueryTreeNode left) { if (this.getChildren().isEmpty()) { this.getChildren().add(left); } else { this.getChildren().set(0, left); } setNeedBuild(true); } public void setRightNode(QueryTreeNode right) { if (this.getChildren().isEmpty()) { this.getChildren().add(null); } if (this.getChildren().size() == 1) { this.getChildren().add(right); } else { this.getChildren().set(1, right); } setNeedBuild(true); } public List<ASTNode> getChildren() { List<ASTNode> childs = super.getChildren(); childs.remove(null);// 删除left为null的情况 return childs; } public List<IOrderBy> getImplicitOrderBys() { List<IOrderBy> orderByCombineWithGroupBy = getOrderByCombineWithGroupBy(); if (orderByCombineWithGroupBy != null) { return orderByCombineWithGroupBy; } List<IOrderBy> orders = new ArrayList(); // index nested loop以左表顺序为准 if (this.getJoinStrategy() == JoinStrategy.INDEX_NEST_LOOP || this.getJoinStrategy() == JoinStrategy.NEST_LOOP_JOIN) { orders = this.getLeftNode().getImplicitOrderBys(); } else if (this.getJoinStrategy() == JoinStrategy.SORT_MERGE_JOIN) { // sort merge的话,返回空值,由上层来判断 return orders; } List<IOrderBy> implicitOrdersCandidate = orders; List<IOrderBy> implicitOrders = new ArrayList(); for (int i = 0; i < implicitOrdersCandidate.size(); i++) { if (this.getColumnsSelected().contains(implicitOrdersCandidate.get(i).getColumn())) { implicitOrders.add(implicitOrdersCandidate.get(i)); } else { break; } } return implicitOrders; } public QueryTreeNodeBuilder getBuilder() { return builder; } public String getName() { return this.getAlias(); } public void build() { if (this.isNeedBuild()) { this.getLeftNode().build(); this.getRightNode().build(); this.builder.build(); } setNeedBuild(false); } /** * 交换左右节点 */ public void exchangeLeftAndRight() { setNeedBuild(true); QueryTreeNode tmp = this.getLeftNode(); this.setLeftNode(this.getRightNode()); this.setRightNode(tmp); boolean tmpouter = this.leftOuter; this.leftOuter = this.rightOuter; this.rightOuter = tmpouter; } public IJoin toDataNodeExecutor() throws QueryException { IJoin join = ASTNodeFactory.getInstance().createJoin(); join.setRightNode(this.getRightNode().toDataNodeExecutor()); join.setLeftNode(this.getLeftNode().toDataNodeExecutor()); join.setJoinStrategy(this.getJoinStrategy()); join.setLeftOuter(this.getLeftOuter()).setRightOuter(this.getRightOuter()); join.setJoinOnColumns((this.getLeftKeys()), (this.getRightKeys())); join.setOrderBys(this.getOrderBys()); join.setLimitFrom(this.getLimitFrom()).setLimitTo(this.getLimitTo()); join.executeOn(this.getDataNode()).setConsistent(true); join.setValueFilter(this.getResultFilter()); join.having(this.getHavingFilter()); join.setAlias(this.getAlias()); join.setGroupBys(this.getGroupBys()); join.setIsSubQuery(this.isSubQuery()); join.setOtherJoinOnFilter(this.getOtherJoinOnFilter()); if (this.isCrossJoin()) { join.setColumns(new ArrayList(0)); // 查询所有字段 } else { join.setColumns((this.getColumnsSelected())); } join.setWhereFilter(this.getAllWhereFilter()); return join; } public QueryTreeNode convertToJoinIfNeed() { super.convertToJoinIfNeed(); // 首先执行一次TableNode处理,生成join // 如果右边是子查询,join策略为block,不做调整 if (!(this.getJoinStrategy() == JoinStrategy.INDEX_NEST_LOOP)) { return this; } QueryTreeNode right = this.getRightNode(); // 如果右边是一个IQuery,就按正常的方法生成JoinNode即可 if (right instanceof TableNode || right instanceof QueryNode || right instanceof MergeNode) { return this; } assert (right instanceof JoinNode);// 右边也是一个join // 将原本 A join (B Join C) 调整为 (A join B) join C // 原本B join C可能是TableNode中走的索引信息不包含字段信息,需要做回表查询 QueryTreeNode left = (QueryTreeNode) this.getLeftNode(); if (right instanceof JoinNode) { QueryTreeNode rightIndexQuery = ((JoinNode) right).getLeftNode(); QueryTreeNode rightKeyQuery = ((JoinNode) right).getRightNode(); JoinNode leftJoinRightIndex = left.join(rightIndexQuery); leftJoinRightIndex.setJoinStrategy(JoinStrategy.INDEX_NEST_LOOP); // 复制join的右字段,修正一下表名 List<ISelectable> rightIndexJoinOnColumns = OptimizerUtils.copySelectables(this.getRightKeys(), rightIndexQuery.getName()); // 添加left join index的条件 for (int i = 0; i < this.getLeftKeys().size(); i++) { leftJoinRightIndex.addJoinKeys(this.getLeftKeys().get(i), rightIndexJoinOnColumns.get(i)); } leftJoinRightIndex.setLeftRightJoin(this.leftOuter, this.rightOuter); leftJoinRightIndex.executeOn(this.getDataNode()); List<ISelectable> leftJoinRightIndexColumns = new LinkedList(); // 复制left的查询 List<ISelectable> leftJoinColumns = OptimizerUtils.copySelectables(left.getColumnsSelected(), left.getName()); // 复制index的查询 List<ISelectable> rightIndexColumns = OptimizerUtils.copySelectables(rightIndexQuery.getColumnsSelected(), rightIndexQuery.getName()); leftJoinRightIndexColumns.addAll(leftJoinColumns); leftJoinRightIndexColumns.addAll(rightIndexColumns); // left + index的查询做为新的join查询字段 leftJoinRightIndex.select(leftJoinRightIndexColumns); // (left join index) join key构建 JoinNode leftJoinRightIndexJoinRightKey = leftJoinRightIndex.join(rightKeyQuery); leftJoinRightIndexJoinRightKey.setJoinStrategy(JoinStrategy.INDEX_NEST_LOOP); // 也是走index List<ISelectable> leftKeys = OptimizerUtils.copySelectables(((JoinNode) right).getLeftKeys(), rightIndexQuery.getName()); for (int i = 0; i < leftKeys.size(); i++) { leftJoinRightIndexJoinRightKey.addJoinKeys(leftKeys.get(i), ((JoinNode) right).getRightKeys().get(i)); } leftJoinRightIndexJoinRightKey.setLeftRightJoin(this.leftOuter, this.rightOuter); leftJoinRightIndexJoinRightKey.setOrderBys(this.getOrderBys()); leftJoinRightIndexJoinRightKey.setConsistent(true); leftJoinRightIndexJoinRightKey.setLimitFrom(this.getLimitFrom()); leftJoinRightIndexJoinRightKey.setLimitTo(this.getLimitTo()); leftJoinRightIndexJoinRightKey.setAlias(this.getAlias()); leftJoinRightIndexJoinRightKey.setSubAlias(this.getSubAlias()); leftJoinRightIndexJoinRightKey.executeOn(this.getDataNode()); if (this.isCrossJoin()) { leftJoinRightIndexJoinRightKey.select(new ArrayList(0));// 查全表所有字段,build的时候会补充 } else { leftJoinRightIndexJoinRightKey.setColumnsSelected(this.getColumnsSelected()); } leftJoinRightIndexJoinRightKey.setGroupBys(this.getGroupBys()); leftJoinRightIndexJoinRightKey.setResultFilter(this.getResultFilter()); leftJoinRightIndexJoinRightKey.setOtherJoinOnFilter(this.getOtherJoinOnFilter()); leftJoinRightIndexJoinRightKey.setSubQuery(this.isSubQuery()); leftJoinRightIndexJoinRightKey.setAllWhereFilter(this.getAllWhereFilter()); leftJoinRightIndexJoinRightKey.build(); return leftJoinRightIndexJoinRightKey; } return this; } // ===================== setter / getter ========================= public JoinStrategy getJoinStrategy() { return this.joinStrategy; } public JoinNode setJoinStrategy(JoinStrategy joinStrategy) { this.joinStrategy = joinStrategy; return this; } public List<IBooleanFilter> getJoinFilter() { return this.joinFilter; } public void setJoinFilter(List<IBooleanFilter> joinFilter) { this.joinFilter = joinFilter; } public JoinNode setCrossJoin() { this.isCrossJoin = true; return this; } public boolean isCrossJoin() { return isCrossJoin; } public JoinNode setLeftOuterJoin() { this.leftOuter = true; this.rightOuter = false; return this; } public JoinNode setRightOuterJoin() { this.rightOuter = true; this.leftOuter = false; return this; } public JoinNode setInnerJoin() { this.leftOuter = false; this.rightOuter = false; return this; } /** * 或者称为full join */ public JoinNode setOuterJoin() { this.leftOuter = true; this.rightOuter = true; return this; } public boolean getLeftOuter() { return this.leftOuter; } public boolean getRightOuter() { return this.rightOuter; } public boolean isLeftOuterJoin() { return (this.getLeftOuter()) && (!this.getRightOuter()); } public boolean isRightOuterJoin() { return (!this.getLeftOuter()) && (this.getRightOuter()); } public boolean isInnerJoin() { return (!this.getLeftOuter()) && (!this.getRightOuter()); } public boolean isOuterJoin() { return (this.getLeftOuter()) && (this.getRightOuter()); } public boolean isNeedOptimizeJoinOrder() { return this.needOptimizeJoinOrder; } public void setNeedOptimizeJoinOrder(boolean needOptimizeJoinOrder) { this.needOptimizeJoinOrder = needOptimizeJoinOrder; } public boolean isUedForIndexJoinPK() { return usedForIndexJoinPK; } public void setUsedForIndexJoinPK(boolean uedForIndexJoinPK) { this.usedForIndexJoinPK = uedForIndexJoinPK; } public JoinNode setLeftRightJoin(boolean leftOuter, boolean rightOuter) { this.leftOuter = leftOuter; this.rightOuter = rightOuter; return this; } public JoinNode copy() { JoinNode newJoinNode = new JoinNode(); this.copySelfTo(newJoinNode); newJoinNode.setJoinFilter(new ArrayList<IBooleanFilter>(this.getJoinFilter())); newJoinNode.setJoinStrategy(this.getJoinStrategy()); newJoinNode.setLeftNode((QueryTreeNode) this.getLeftNode().copy()); newJoinNode.setRightNode((QueryTreeNode) this.getRightNode().copy()); newJoinNode.setNeedOptimizeJoinOrder(this.isNeedOptimizeJoinOrder()); newJoinNode.isCrossJoin = this.isCrossJoin; newJoinNode.leftOuter = this.leftOuter; newJoinNode.rightOuter = this.rightOuter; newJoinNode.usedForIndexJoinPK = this.usedForIndexJoinPK; return newJoinNode; } public JoinNode deepCopy() { JoinNode newJoinNode = new JoinNode(); this.deepCopySelfTo(newJoinNode); newJoinNode.setJoinFilter(OptimizerUtils.copyFilter(this.getJoinFilter())); newJoinNode.setJoinStrategy(this.getJoinStrategy()); newJoinNode.setLeftNode((QueryTreeNode) this.getLeftNode().deepCopy()); newJoinNode.setRightNode((QueryTreeNode) this.getRightNode().deepCopy()); newJoinNode.setNeedOptimizeJoinOrder(this.isNeedOptimizeJoinOrder()); newJoinNode.isCrossJoin = this.isCrossJoin; newJoinNode.leftOuter = this.leftOuter; newJoinNode.rightOuter = this.rightOuter; newJoinNode.usedForIndexJoinPK = this.usedForIndexJoinPK; return newJoinNode; } public String toString(int inden) { String tabTittle = GeneralUtil.getTab(inden); String tabContent = GeneralUtil.getTab(inden + 1); StringBuilder sb = new StringBuilder(); if (this.getAlias() != null) { appendln(sb, tabTittle + "Join" + " as " + this.getAlias()); } else { appendln(sb, tabTittle + "Join"); } appendField(sb, "joinFilter:", this.getJoinFilter(), tabContent); appendField(sb, "otherJoinOnFilter:", this.getOtherJoinOnFilter(), tabContent); if (this.isInnerJoin()) { appendField(sb, "type", "inner join", tabContent); } if (this.isRightOuterJoin()) { appendField(sb, "type", "right outter join", tabContent); } if (this.isLeftOuterJoin()) { appendField(sb, "type", "left outter join", tabContent); } if (this.isOuterJoin()) { appendField(sb, "type", "outer join", tabContent); } appendField(sb, "resultFilter", printFilterString(this.getResultFilter(), inden + 2), tabContent); appendField(sb, "whereFilter", printFilterString(this.getWhereFilter(), inden + 2), tabContent); // appendField(sb, "allWhereFilter", // printFilterString(this.getAllWhereFilter()), tabContent); appendField(sb, "having", printFilterString(this.getHavingFilter(), inden + 2), tabContent); if (!(this.getLimitFrom() != null && this.getLimitFrom().equals(0L) && this.getLimitTo() != null && this.getLimitTo() .equals(0L))) { appendField(sb, "limitFrom", this.getLimitFrom(), tabContent); appendField(sb, "limitTo", this.getLimitTo(), tabContent); } if (this.isSubQuery()) { appendField(sb, "isSubQuery", this.isSubQuery(), tabContent); } appendField(sb, "orderBys", this.getOrderBys(), tabContent); appendField(sb, "queryConcurrency", this.getQueryConcurrency(), tabContent); appendField(sb, "columns", this.getColumnsSelected(), tabContent); appendField(sb, "groupBys", this.getGroupBys(), tabContent); appendField(sb, "strategy", this.getJoinStrategy(), tabContent); appendField(sb, "executeOn", this.getDataNode(), tabContent); appendln(sb, tabContent + "left:"); sb.append(this.getLeftNode().toString(inden + 2)); appendln(sb, tabContent + "right:"); sb.append(this.getRightNode().toString(inden + 2)); return sb.toString(); } }
923e85f4cdd34e635a58449aa24f2026e389d583
789
java
Java
src/test/java/org/codeforamerica/shiba/pages/LocalePreferenceSelectionTest.java
isabella232/shiba
0560361fb7e575a0288e4815024f8dfcdc6e9cfa
[ "BSD-3-Clause" ]
null
null
null
src/test/java/org/codeforamerica/shiba/pages/LocalePreferenceSelectionTest.java
isabella232/shiba
0560361fb7e575a0288e4815024f8dfcdc6e9cfa
[ "BSD-3-Clause" ]
1
2021-03-15T17:47:55.000Z
2021-03-15T17:47:55.000Z
src/test/java/org/codeforamerica/shiba/pages/LocalePreferenceSelectionTest.java
isabella232/shiba
0560361fb7e575a0288e4815024f8dfcdc6e9cfa
[ "BSD-3-Clause" ]
null
null
null
28.178571
102
0.73384
1,000,793
package org.codeforamerica.shiba.pages; import org.codeforamerica.shiba.AbstractBasePageTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class LocalePreferenceSelectionTest extends AbstractBasePageTest { @Override @BeforeEach protected void setUp() throws IOException { super.setUp(); driver.navigate().to(baseUrl); } @Test void userCanSeeTextInSpanishWhenSpanishIsLanguageSelected() { testPage.clickButton("Apply now"); testPage.enter("locales", "Español"); assertThat(driver.findElements(By.tagName("h1")).get(0).getText()).isEqualTo("Como funciona"); } }
923e8647661472bdc308bb452bbe723d49cda84d
8,281
java
Java
vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/providers/OpenIDConnectAuth.java
bfreuden/vertx-auth
61309456b63a9ef3e1d8f04a7a2be25ccfb92d2c
[ "Apache-2.0" ]
150
2015-05-21T09:23:22.000Z
2022-02-24T10:56:35.000Z
vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/providers/OpenIDConnectAuth.java
bfreuden/vertx-auth
61309456b63a9ef3e1d8f04a7a2be25ccfb92d2c
[ "Apache-2.0" ]
423
2015-05-19T13:55:01.000Z
2022-03-30T10:01:59.000Z
vertx-auth-oauth2/src/main/java/io/vertx/ext/auth/oauth2/providers/OpenIDConnectAuth.java
bfreuden/vertx-auth
61309456b63a9ef3e1d8f04a7a2be25ccfb92d2c
[ "Apache-2.0" ]
181
2015-05-22T16:12:10.000Z
2022-03-20T00:39:03.000Z
39.246445
128
0.656322
1,000,794
/* * Copyright 2015 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.auth.oauth2.providers; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.*; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.JWTOptions; import io.vertx.ext.auth.impl.http.SimpleHttpClient; import io.vertx.ext.auth.impl.http.SimpleHttpResponse; import io.vertx.ext.auth.oauth2.OAuth2Auth; import io.vertx.ext.auth.oauth2.OAuth2Options; /** * Simplified factory to create an {@link io.vertx.ext.auth.oauth2.OAuth2Auth} for OpenID Connect. * * @author <a href="mailto:kenaa@example.com">Paulo Lopes</a> */ @VertxGen public interface OpenIDConnectAuth { /** * Create a OAuth2Auth provider for OpenID Connect Discovery. The discovery will use the given site in the * configuration options and attempt to load the well known descriptor. * <p> * If the discovered config includes a json web key url, it will be also fetched and the JWKs will be loaded * into the OAuth provider so tokens can be decoded. * * @param vertx the vertx instance * @param config the initial config, it should contain a site url * @param handler the instantiated Oauth2 provider instance handler */ static void discover(final Vertx vertx, final OAuth2Options config, final Handler<AsyncResult<OAuth2Auth>> handler) { if (config.getSite() == null) { handler.handle(Future.failedFuture("issuer cannot be null")); return; } // compute paths with variables, at this moment it is only relevant that // the paths and site are properly computed config.replaceVariables(false); final String oidc_discovery_path = "/.well-known/openid-configuration"; // The site and issuer are used interchangeably here and can be confusing in some cases. A small replacement can // happen at this time to ensure that the config is correct. String issuer = config.getSite(); if (issuer.endsWith(oidc_discovery_path)) { issuer = issuer.substring(0, issuer.length() - oidc_discovery_path.length()); } final SimpleHttpClient httpClient = new SimpleHttpClient( vertx, config.getUserAgent(), config.getHttpClientOptions()); // the response follows the OpenID Connect provider metadata spec: // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata httpClient.fetch( HttpMethod.GET, issuer + oidc_discovery_path, new JsonObject() .put("Accept", "application/json"), null, fetch -> { if (fetch.failed()) { handler.handle(Future.failedFuture(fetch.cause())); return; } final SimpleHttpResponse response = fetch.result(); if (response.statusCode() != 200) { handler.handle(Future.failedFuture("Bad Response [" + response.statusCode() + "] " + response.body())); return; } if (!response.is("application/json")) { handler.handle(Future.failedFuture("Cannot handle Content-Type: " + response.headers().get("Content-Type"))); return; } final JsonObject json = response.jsonObject(); if (json == null) { handler.handle(Future.failedFuture("Cannot handle null JSON")); return; } // some providers return errors as JSON too if (json.containsKey("error")) { // attempt to handle the error as a string handler.handle(Future.failedFuture(json.getString("error_description", json.getString("error")))); return; } // issuer validation if (config.isValidateIssuer()) { String issuerEndpoint = json.getString("issuer"); if (issuerEndpoint != null) { // the provider is letting the user know the issuer endpoint, so we need to validate // as in vertx oauth the issuer (site config) is a url without the trailing slash we // will compare the received endpoint without the final slash is present if (issuerEndpoint.endsWith("/")) { issuerEndpoint = issuerEndpoint.substring(0, issuerEndpoint.length() - 1); } if (!config.getSite().equals(issuerEndpoint)) { handler.handle(Future.failedFuture("issuer validation failed: received [" + issuerEndpoint + "]")); return; } } } config.setAuthorizationPath(json.getString("authorization_endpoint")); config.setTokenPath(json.getString("token_endpoint")); config.setLogoutPath(json.getString("end_session_endpoint")); config.setRevocationPath(json.getString("revocation_endpoint")); config.setUserInfoPath(json.getString("userinfo_endpoint")); config.setJwkPath(json.getString("jwks_uri")); config.setIntrospectionPath(json.getString("introspection_endpoint")); if (json.containsKey("issuer")) { // the discovery document includes the issuer, this means we can and should assert that source of all tokens // when in JWT form JWTOptions jwtOptions = config.getJWTOptions(); if (jwtOptions == null) { jwtOptions = new JWTOptions(); config.setJWTOptions(jwtOptions); } // configure the issuer jwtOptions.setIssuer(json.getString("issuer")); } // reset config config.setSupportedGrantTypes(null); if (json.containsKey("grant_types_supported")) { // optional config JsonArray flows = json.getJsonArray("grant_types_supported"); flows.forEach(el -> config.addSupportedGrantType((String) el)); if (!flows.contains(config.getFlow().getGrantType())) { handler.handle(Future.failedFuture("unsupported flow: " + config.getFlow().getGrantType() + ", allowed: " + flows)); return; } } else { // https://datatracker.ietf.org/doc/html/rfc8414 // specifies that if omitted, assume the default: ["authorization_code", "implicit"] config .addSupportedGrantType("authorization_code") .addSupportedGrantType("implicit"); } try { // the constructor might fail if the configuration is incomplete final OAuth2Auth oidc = OAuth2Auth.create(vertx, config); if (config.getJwkPath() != null) { oidc.jWKSet(v -> { if (v.failed()) { handler.handle(Future.failedFuture(v.cause())); return; } handler.handle(Future.succeededFuture(oidc)); }); } else { handler.handle(Future.succeededFuture(oidc)); } } catch (IllegalArgumentException | IllegalStateException e) { handler.handle(Future.failedFuture(e)); } }); } /** * Create a OAuth2Auth provider for OpenID Connect Discovery. The discovery will use the given site in the * configuration options and attempt to load the well known descriptor. * <p> * If the discovered config includes a json web key url, it will be also fetched and the JWKs will be loaded * into the OAuth provider so tokens can be decoded. * * @param vertx the vertx instance * @param config the initial config, it should contain a site url * @return future with the instantiated Oauth2 provider instance handler * @see OpenIDConnectAuth#discover(Vertx, OAuth2Options, Handler) */ static Future<OAuth2Auth> discover(final Vertx vertx, final OAuth2Options config) { Promise<OAuth2Auth> promise = Promise.promise(); discover(vertx, config, promise); return promise.future(); } }
923e86774511605aa71e681df23c12999d04ada0
4,751
java
Java
cyfm-web/src/main/java/com/ppcxy/cyfm/desktop/web/DesktopController.java
ppcxy/cyfm
87131fc2fb7be12979e0a23326198212ee0df0ba
[ "Apache-2.0" ]
14
2016-06-28T15:10:36.000Z
2021-12-30T09:42:15.000Z
cyfm-web/src/main/java/com/ppcxy/cyfm/desktop/web/DesktopController.java
ppcxy/cyfm
87131fc2fb7be12979e0a23326198212ee0df0ba
[ "Apache-2.0" ]
15
2016-07-09T16:42:51.000Z
2022-01-27T16:21:31.000Z
cyfm-web/src/main/java/com/ppcxy/cyfm/desktop/web/DesktopController.java
ppcxy/cyfm
87131fc2fb7be12979e0a23326198212ee0df0ba
[ "Apache-2.0" ]
7
2016-07-11T10:28:32.000Z
2022-02-27T10:09:47.000Z
37.409449
134
0.629762
1,000,795
package com.ppcxy.cyfm.desktop.web; import com.ppcxy.common.exception.BaseException; import com.ppcxy.common.web.bind.annotation.CurrentUser; import com.ppcxy.cyfm.sys.entity.resource.dto.Menu; import com.ppcxy.cyfm.sys.entity.user.User; import com.ppcxy.cyfm.sys.service.UserSwitchService; import com.ppcxy.cyfm.sys.service.resource.ResourceService; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springside.modules.mapper.JsonMapper; import org.springside.modules.web.Servlets; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; /** * Created by weep on 2016-5-16. */ @Controller @RequestMapping(value = "/desktop") public class DesktopController { @Autowired private UserSwitchService userSwitchService; @Autowired private ResourceService resourceService; //TODO 默认前端首页实现. //@RequestMapping //public String index(HttpServletRequest request, HttpServletResponse response) { // Servlets.changeCookie("skin", "default", request, response); // return "index"; //} @RequestMapping public String main(@CurrentUser User user) { Long rootMenuId = user.getTeam().getRootMenuId(); if (rootMenuId == null || rootMenuId.intValue() == 0) { rootMenuId = 1L; } return String.format("redirect:/desktop/%d/", rootMenuId); } @RequestMapping(value = "{rootId}") public String main(@CurrentUser User user, @PathVariable(value = "rootId") Long rootId, HttpServletRequest request, Model model) { com.ppcxy.cyfm.sys.entity.resource.Resource rootResource = resourceService.findOne(rootId); //访问的菜单不存在,则跳转到首页 if (rootResource == null) { Long rootMenuId = user.getTeam().getRootMenuId(); if (rootMenuId == null) { throw new BaseException("访问地址不存在。"); } return String.format("redirect:/desktop/%d/", rootMenuId); } if (StringUtils.isNotBlank(rootResource.getIdentity())) { Subject subject = SecurityUtils.getSubject(); if (!subject.isPermitted(rootResource.getIdentity() + ":view") && !subject.hasRole("Admin")) { if (!Objects.equals(rootResource.getId(), user.getTeam().getRootMenuId())) { return String.format("redirect:/desktop/%d/", user.getTeam().getRootMenuId()); } subject.logout(); throw new BaseException("无系统访问权限,请联系管理员。"); } } String searchText = request.getParameter("searchText"); List<Menu> menus = resourceService.findMenus(user, rootId); JsonMapper jsonMapper = new JsonMapper(); menus = jsonMapper.fromJson(jsonMapper.toJson(menus), jsonMapper.contructCollectionType(ArrayList.class, Menu.class)); if (StringUtils.isNotBlank(searchText) && menus != null) { menufilter(menus, searchText); } model.addAttribute("rootId", rootId); model.addAttribute("roots", resourceService.findRoots(user)); model.addAttribute("root", rootResource); model.addAttribute("menus", menus); model.addAttribute("searchText", searchText); model.addAttribute("existPreUser", userSwitchService.existPreUser()); if (Servlets.getCookie("skin", request) != null && "mobile".equals(Servlets.getCookie("skin", request).getValue())) { return "desktop/mobile/main"; } return "desktop/main"; } public int menufilter(List<Menu> menus, String searchText) { Iterator<Menu> iterator = menus.iterator(); while (iterator.hasNext()) { Menu m = iterator.next(); if (m.isHasChildren()) { int cc = menufilter(m.getChildren(), searchText); if (cc == 0) { iterator.remove(); } } else { if (m.getName() != null && !m.getName().contains(searchText)) { iterator.remove(); } } } return menus.size(); } @RequestMapping(value = "/index") public String index() { return "desktop/index"; } }
923e86af34f18fedcfbcf2890ca5a02bcc734147
338
java
Java
exercise/src/typeinfo/ex10/Ex10.java
jhwsx/Think4JavaExamples
bf912a14def15c11a9a5eada308ddaae8e31ff8f
[ "Apache-2.0" ]
null
null
null
exercise/src/typeinfo/ex10/Ex10.java
jhwsx/Think4JavaExamples
bf912a14def15c11a9a5eada308ddaae8e31ff8f
[ "Apache-2.0" ]
null
null
null
exercise/src/typeinfo/ex10/Ex10.java
jhwsx/Think4JavaExamples
bf912a14def15c11a9a5eada308ddaae8e31ff8f
[ "Apache-2.0" ]
1
2022-01-30T00:49:54.000Z
2022-01-30T00:49:54.000Z
21.125
51
0.565089
1,000,796
package typeinfo.ex10; /** * @author wangzhichao * @date 2019/11/02 */ public class Ex10 { public static void main(String[] args) { char[] chars = new char[]{1, 'a'}; System.out.println(chars.getClass()); if (chars instanceof Object) { System.out.println("char[] is Object"); } } }
923e86d54e6f61f1bbbea9d3fbfa4771fc0e68da
962
java
Java
Multithreaded/Fact.java
Abhi-1U/SemaphoresInJava
16551ee4a4d63cd69ccb88ea26380b255c1e81a0
[ "MIT" ]
1
2020-10-02T14:28:02.000Z
2020-10-02T14:28:02.000Z
Multithreaded/Fact.java
Abhi-1U/SemaphoresInJava
16551ee4a4d63cd69ccb88ea26380b255c1e81a0
[ "MIT" ]
null
null
null
Multithreaded/Fact.java
Abhi-1U/SemaphoresInJava
16551ee4a4d63cd69ccb88ea26380b255c1e81a0
[ "MIT" ]
null
null
null
22.372093
99
0.56237
1,000,797
import java.math.BigInteger; class Factorial implements Runnable { private int number; public Factorial(int number) { this.number = number; } public Factorial() { super(); } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } private BigInteger calculateFactorial(int number) { BigInteger result = new BigInteger("1"); for (int i = 1; i <= number; i++) { result = result.multiply(new BigInteger("" + i)); } return result; } @Override public void run() { Thread th = Thread.currentThread(); th.setName("Thread No. " + number); System.out.println(th.getName() + ":" + "!" + number + " = " + calculateFactorial(number)); } } public class Fact{ public static void main(String[] args){ Factorial s=new Factorial(10); s.run(); } }
923e86ffb8841a663c8f0960e6324d13403ae3c1
6,002
java
Java
app/src/main/java/com/example/android/miwok/PhrasesFragment.java
Norphy/Miwok-Udacity
938975bb148891bfa571429ae184f326864dfe42
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/PhrasesFragment.java
Norphy/Miwok-Udacity
938975bb148891bfa571429ae184f326864dfe42
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/PhrasesFragment.java
Norphy/Miwok-Udacity
938975bb148891bfa571429ae184f326864dfe42
[ "Apache-2.0" ]
null
null
null
40.281879
154
0.651283
1,000,798
package com.example.android.miwok; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class PhrasesFragment extends Fragment { private MediaPlayer mMediaPlayer; private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { releaseMediaPlayer(); } }; /** Handles audio focus when playing a sound file */ private AudioManager mAudioManager; /** * This listener gets triggered whenever the audio focus changes * (i.e., we gain or lose audio focus because of another app or device). */ private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange){ if(focusChange == AudioManager.AUDIOFOCUS_GAIN){ mMediaPlayer.start(); } else if(focusChange == AudioManager.AUDIOFOCUS_LOSS) { mMediaPlayer.stop(); releaseMediaPlayer(); } else if(focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { mMediaPlayer.pause(); mMediaPlayer.seekTo(0); } } }; public PhrasesFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.word_list, container, false); // Create and setup the {@link AudioManager} to request audio focus mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); //Create an array of number words final ArrayList<Word> phrases = new ArrayList<Word>(); phrases.add(new Word("Where are you going?","minto wuksus",R.raw.phrase_where_are_you_going)); phrases.add(new Word("What is your name?","tinnә oyaase'nә",R.raw.phrase_what_is_your_name)); phrases.add(new Word("My name is...","oyaaset...",R.raw.phrase_my_name_is)); phrases.add(new Word("How are you feeling?","michәksәs?",R.raw.phrase_how_are_you_feeling)); phrases.add(new Word("I'm feeling good.","kuchi achit",R.raw.phrase_im_feeling_good)); phrases.add(new Word("Are you coming?","әәnәs'aa?",R.raw.phrase_are_you_coming)); phrases.add(new Word("Yes, I'm coming.","hәә’ әәnәm",R.raw.phrase_yes_im_coming)); phrases.add(new Word("I'm coming.","әәnәm",R.raw.phrase_im_coming)); phrases.add(new Word("Let's go.","yoowutis",R.raw.phrase_lets_go)); phrases.add(new Word("Come here.","әnni'nem",R.raw.phrase_come_here)); WordAdapter itemsAdapter = new WordAdapter(getActivity(), phrases, R.color.category_phrases); ListView listView = (ListView) rootView.findViewById(R.id.list); listView.setAdapter(itemsAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Release the media player if it currently exists because we are about to // play a different sound file releaseMediaPlayer(); Word word = phrases.get(position); // Request audio focus so in order to play the audio file. The app needs to play a // short audio file, so we will request audio focus with a short amount of time // with AUDIOFOCUS_GAIN_TRANSIENT. int result = mAudioManager.requestAudioFocus(mAudioFocusChangeListener, AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // We have audio focus now. // Create and setup the {@link MediaPlayer} for the audio resource associated // with the current word mMediaPlayer = MediaPlayer.create(getActivity(),word.getAudioResourceId()); // Start the audio file mMediaPlayer.start(); // Setup a listener on the media player, so that we can stop and release the // media player once the sound has finished playing. mMediaPlayer.setOnCompletionListener(mCompletionListener); } } }); return rootView; } @Override public void onStop() { super.onStop(); //When activity is stopped release the MediaPlayer properly because we wont be playing sounds anymore releaseMediaPlayer(); } private void releaseMediaPlayer() { // If the media player is not null, then it may be currently playing a sound. if (mMediaPlayer != null) { // Regardless of the current state of the media player, release its resources // because we no longer need it. mMediaPlayer.release(); // Set the media player back to null. For our code, we've decided that // setting the media player to null is an easy way to tell that the media player // is not configured to play an audio file at the moment. mMediaPlayer = null; mAudioManager.abandonAudioFocus(mAudioFocusChangeListener); } } }
923e88029645ed4cb5318fb26b8a5ae17e86cba2
1,387
java
Java
ocfl-java-core/src/main/java/edu/wisc/library/ocfl/core/lock/ObjectLock.java
bbpennel/ocfl-java
704c6ad45685f7adf81c839cae7830d181ea9e3f
[ "MIT" ]
null
null
null
ocfl-java-core/src/main/java/edu/wisc/library/ocfl/core/lock/ObjectLock.java
bbpennel/ocfl-java
704c6ad45685f7adf81c839cae7830d181ea9e3f
[ "MIT" ]
null
null
null
ocfl-java-core/src/main/java/edu/wisc/library/ocfl/core/lock/ObjectLock.java
bbpennel/ocfl-java
704c6ad45685f7adf81c839cae7830d181ea9e3f
[ "MIT" ]
null
null
null
27.74
123
0.663302
1,000,799
package edu.wisc.library.ocfl.core.lock; import java.util.concurrent.Callable; /** * Extension point that allows the OCFL repository to use any number of different lock implementations so long as they * conform to this interface. * * @see InMemoryObjectLock */ public interface ObjectLock { /** * Executes the code block after securing a read lock on the objectId. The lock is released after the block completes. * * @param objectId * @param doInLock */ void doInReadLock(String objectId, Runnable doInLock); /** * Executes the code block after securing a read lock on the objectId. The lock is released after the block completes. * * @param objectId * @param doInLock * @param <T> * @return */ <T> T doInReadLock(String objectId, Callable<T> doInLock); /** * Executes the code block after securing a write lock on the objectId. The lock is released after the block completes. * * @param objectId * @param doInLock */ void doInWriteLock(String objectId, Runnable doInLock); /** * Executes the code block after securing a write lock on the objectId. The lock is released after the block completes. * * @param objectId * @param doInLock * @param <T> * @return */ <T> T doInWriteLock(String objectId, Callable<T> doInLock); }
923e885825d193fddbab9a942e48efe559c27bba
1,738
java
Java
dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java
humyna/dubbox
3be9af732d9306023b2d8be31bdf751061953eca
[ "Apache-2.0" ]
5,534
2015-01-02T07:54:20.000Z
2022-03-28T05:29:31.000Z
dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java
humyna/dubbox
3be9af732d9306023b2d8be31bdf751061953eca
[ "Apache-2.0" ]
319
2015-01-05T10:04:03.000Z
2021-12-23T09:38:53.000Z
dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java
humyna/dubbox
3be9af732d9306023b2d8be31bdf751061953eca
[ "Apache-2.0" ]
2,772
2015-01-04T10:43:49.000Z
2022-03-30T01:12:02.000Z
36.978723
133
0.710587
1,000,800
/** * Copyright 1999-2014 dangdang.com. * * 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.alibaba.dubbo.rpc.benchmark; import org.apache.commons.lang.StringUtils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; /** * @author lishen */ public class TextClientRunnable extends AbstractClientRunnable{ private final Text text = new Text(StringUtils.leftPad("", 50000)); public TextClientRunnable(String protocol, String serialization, String targetIP, int targetPort, int clientNums, int rpcTimeout, CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime){ super(protocol, serialization, targetIP, targetPort, clientNums, rpcTimeout, barrier, latch, startTime, endTime); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Object invoke(ServiceFactory serviceFactory) { EchoService echoService = (EchoService) serviceFactory.get(EchoService.class); return echoService.text(text); } // // public static void main(String[] args) { // System.out.println( StringUtils.leftPad("", 1000).getBytes().length); // } }
923e886669a9d68dc5b5aa157e6a6de5cfee970f
10,897
java
Java
src/test/java/jkanvas/animation/AnimatedPositionTest.java
JosuaKrause/JKanvas
82a1e79964f1abd3679404fab21ecdb76989a7f3
[ "MIT" ]
1
2017-06-27T03:50:13.000Z
2017-06-27T03:50:13.000Z
src/test/java/jkanvas/animation/AnimatedPositionTest.java
JosuaKrause/JKanvas
82a1e79964f1abd3679404fab21ecdb76989a7f3
[ "MIT" ]
null
null
null
src/test/java/jkanvas/animation/AnimatedPositionTest.java
JosuaKrause/JKanvas
82a1e79964f1abd3679404fab21ecdb76989a7f3
[ "MIT" ]
null
null
null
33.036364
80
0.635388
1,000,801
package jkanvas.animation; import static org.junit.Assert.*; import java.awt.geom.Point2D; import jkanvas.util.Interpolator; import org.junit.Test; /** * Tests for animated positions. * * @author Joschi <efpyi@example.com> */ public class AnimatedPositionTest { /** Tests the immediate feed back before a call to animate. */ @Test public void immediateFeedback() { final AnimationTiming at = new AnimationTiming(Interpolator.LINEAR, 2); final AnimatedPosition p = new AnimatedPosition(3, 4); p.setPosition(4, 3); final Point2D cur0 = p.getPos(); assertEquals(4, cur0.getX(), 0); assertEquals(3, cur0.getY(), 0); final Point2D pred0 = p.getPredict(); assertEquals(4, pred0.getX(), 0); assertEquals(3, pred0.getY(), 0); assertFalse(p.inAnimation()); p.startAnimationTo(new Point2D.Double(6, 5), at); assertEquals(4, p.getX(), 0); assertEquals(3, p.getY(), 0); final Point2D pred1 = p.getPredict(); assertEquals(6, pred1.getX(), 0); assertEquals(5, pred1.getY(), 0); assertTrue(p.inAnimation()); p.animate(0); assertEquals(4, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(6, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(1); assertEquals(5, p.getX(), 0); assertEquals(4, p.getY(), 0); assertEquals(6, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(2); assertEquals(6, p.getX(), 0); assertEquals(5, p.getY(), 0); assertEquals(6, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertFalse(p.inAnimation()); } /** * Tests the immediate feed back before a call to animate -- with change * animation. */ @Test public void immediateFeedbackForChangingAnimations() { final AnimationTiming at = new AnimationTiming(Interpolator.LINEAR, 2); final AnimatedPosition p = new AnimatedPosition(new Point2D.Double(3, 4)); p.setPosition(new Point2D.Double(4, 3)); assertEquals(4, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(4, p.getPredictX(), 0); assertEquals(3, p.getPredictY(), 0); assertFalse(p.inAnimation()); p.startAnimationTo(new Point2D.Double(6, 5), at); assertEquals(4, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(6, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(0); assertEquals(4, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(6, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(1); assertEquals(5, p.getX(), 0); assertEquals(4, p.getY(), 0); assertEquals(6, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(2); assertEquals(6, p.getX(), 0); assertEquals(5, p.getY(), 0); assertEquals(6, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertFalse(p.inAnimation()); } /** Clearing an animation before a call to animate. */ @Test public void clearingAnimationsBeforeAnimate() { final AnimationTiming at = new AnimationTiming(Interpolator.LINEAR, 2); final AnimatedPosition p = new AnimatedPosition(new Point2D.Double(3, 4)); p.startAnimationTo(new Point2D.Double(4, 3), at); assertEquals(3, p.getX(), 0); assertEquals(4, p.getY(), 0); assertEquals(4, p.getPredictX(), 0); assertEquals(3, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.clearAnimation(); assertFalse(p.inAnimation()); p.animate(0); assertEquals(3, p.getX(), 0); assertEquals(4, p.getY(), 0); assertEquals(3, p.getPredictX(), 0); assertEquals(4, p.getPredictY(), 0); assertFalse(p.inAnimation()); p.animate(1); assertEquals(3, p.getX(), 0); assertEquals(4, p.getY(), 0); assertEquals(3, p.getPredictX(), 0); assertEquals(4, p.getPredictY(), 0); assertFalse(p.inAnimation()); } /** Clearing an animation after a call to animate. */ @Test public void clearingAnimationsAfterAnimate() { final AnimationTiming at = new AnimationTiming(Interpolator.LINEAR, 2); final AnimatedPosition p = new AnimatedPosition(new Point2D.Double(3, 4)); p.startAnimationTo(new Point2D.Double(5, 6), at); p.animate(0); assertEquals(3, p.getX(), 0); assertEquals(4, p.getY(), 0); assertEquals(5, p.getPredictX(), 0); assertEquals(6, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(1); assertEquals(4, p.getX(), 0); assertEquals(5, p.getY(), 0); assertEquals(5, p.getPredictX(), 0); assertEquals(6, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.clearAnimation(); assertEquals(4, p.getX(), 0); assertEquals(5, p.getY(), 0); assertEquals(4, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertFalse(p.inAnimation()); p.animate(2); assertEquals(4, p.getX(), 0); assertEquals(5, p.getY(), 0); assertEquals(4, p.getPredictX(), 0); assertEquals(5, p.getPredictY(), 0); assertFalse(p.inAnimation()); } /** * A call to start animation with no duration should behave exactly like * setPosition(). */ @Test public void actAsNoAnimation() { final AnimationTiming at = new AnimationTiming(Interpolator.LINEAR, 0); final AnimatedPosition p = new AnimatedPosition(new Point2D.Double(3, 4)); assertEquals(3, p.getX(), 0); assertEquals(4, p.getY(), 0); assertEquals(3, p.getPredictX(), 0); assertEquals(4, p.getPredictY(), 0); assertFalse(p.inAnimation()); p.startAnimationTo(new Point2D.Double(4, 3), at); assertEquals(4, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(4, p.getPredictX(), 0); assertEquals(3, p.getPredictY(), 0); assertFalse(p.inAnimation()); p.animate(0); assertEquals(4, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(4, p.getPredictX(), 0); assertEquals(3, p.getPredictY(), 0); assertFalse(p.inAnimation()); } /** * Using an interpolator that reaches the end position before its time should * not cancel the animation. */ @Test public void unusualInterpolator() { final Interpolator i = new Interpolator() { @Override public double interpolate(final double t) { return (t > .25 && t < .75) ? 0 : 1; } @Override public double inverseInterpolate(final double t) { throw new UnsupportedOperationException(); } }; final AnimationTiming at = new AnimationTiming(i, 5); final AnimatedPosition p = new AnimatedPosition(new Point2D.Double(0, 0)); p.startAnimationTo(new Point2D.Double(1, 1), at); assertEquals(0, p.getX(), 0); assertEquals(0, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(1, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(0); assertEquals(0, p.getX(), 0); assertEquals(0, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(1, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(1); assertEquals(1, p.getX(), 0); assertEquals(1, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(1, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(2); assertEquals(0, p.getX(), 0); assertEquals(0, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(1, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(3); assertEquals(0, p.getX(), 0); assertEquals(0, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(1, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(4); assertEquals(1, p.getX(), 0); assertEquals(1, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(1, p.getPredictY(), 0); assertTrue(p.inAnimation()); p.animate(5); assertEquals(1, p.getX(), 0); assertEquals(1, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(1, p.getPredictY(), 0); assertFalse(p.inAnimation()); } /** * Tests that the prediction value is immediately set after directly setting a * position. */ @Test public void predWhenSetting() { final AnimationTiming at = new AnimationTiming(Interpolator.LINEAR, 2); final AnimatedPosition p = new AnimatedPosition(new Point2D.Double(0, 0)); p.startAnimationTo(new Point2D.Double(2, 2), at); p.animate(0); p.animate(1); assertEquals(1, p.getX(), 0); assertEquals(1, p.getY(), 0); assertEquals(2, p.getPredictX(), 0); assertEquals(2, p.getPredictY(), 0); p.setPosition(new Point2D.Double(3, 3)); assertEquals(3, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(3, p.getPredictX(), 0); assertEquals(3, p.getPredictY(), 0); p.animate(2); assertEquals(3, p.getX(), 0); assertEquals(3, p.getY(), 0); assertEquals(3, p.getPredictX(), 0); assertEquals(3, p.getPredictY(), 0); } /** * Ensures that modifications after passing (getting) a value to (from) a * public method does not affect the {@link AnimatedPosition}. */ @Test public void immutability() { final Point2D passing = new Point2D.Double(0, 0); final AnimationTiming at = new AnimationTiming(Interpolator.LINEAR, 2); final AnimatedPosition p = new AnimatedPosition(passing); passing.setLocation(1, 2); assertEquals(0, p.getX(), 0); assertEquals(0, p.getY(), 0); assertEquals(0, p.getPredictX(), 0); assertEquals(0, p.getPredictY(), 0); p.setPosition(passing); passing.setLocation(0, 0); assertEquals(1, p.getX(), 0); assertEquals(2, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(2, p.getPredictY(), 0); p.startAnimationTo(passing, at); passing.setLocation(3, 4); p.animate(0); p.animate(1); p.animate(2); assertEquals(0, p.getX(), 0); assertEquals(0, p.getY(), 0); assertEquals(0, p.getPredictX(), 0); assertEquals(0, p.getPredictY(), 0); passing.setLocation(1, 2); p.startAnimationTo(passing, at); passing.setLocation(0, 0); p.animate(0); p.animate(1); p.animate(2); assertEquals(1, p.getX(), 0); assertEquals(2, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(2, p.getPredictY(), 0); final Point2D pos = p.getPos(); pos.setLocation(0, 0); assertEquals(1, p.getX(), 0); assertEquals(2, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(2, p.getPredictY(), 0); final Point2D pred = p.getPredict(); pred.setLocation(3, 4); assertEquals(1, p.getX(), 0); assertEquals(2, p.getY(), 0); assertEquals(1, p.getPredictX(), 0); assertEquals(2, p.getPredictY(), 0); } }
923e88b860abf4649683aa11227179086118ca93
3,072
java
Java
core/repository/src/main/java/de/acosix/alfresco/utility/repo/component/SiteBootstrapAwareImportPackageHandlerFacade.java
abhinavmishra14/alfresco-utility
876b613394046872f605a0f97c517c145a160442
[ "Apache-2.0" ]
10
2016-10-11T19:03:36.000Z
2022-03-24T04:47:31.000Z
core/repository/src/main/java/de/acosix/alfresco/utility/repo/component/SiteBootstrapAwareImportPackageHandlerFacade.java
abhinavmishra14/alfresco-utility
876b613394046872f605a0f97c517c145a160442
[ "Apache-2.0" ]
11
2017-03-13T22:22:28.000Z
2021-04-19T08:14:58.000Z
core/repository/src/main/java/de/acosix/alfresco/utility/repo/component/SiteBootstrapAwareImportPackageHandlerFacade.java
abhinavmishra14/alfresco-utility
876b613394046872f605a0f97c517c145a160442
[ "Apache-2.0" ]
14
2017-02-27T19:50:21.000Z
2021-06-04T19:05:41.000Z
28.444444
117
0.666016
1,000,802
/* * Copyright 2016 - 2021 Acosix GmbH * * 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 de.acosix.alfresco.utility.repo.component; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.charset.StandardCharsets; import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.service.cmr.view.ImportPackageHandler; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Axel Faust */ public class SiteBootstrapAwareImportPackageHandlerFacade implements ImportPackageHandler { private final static Logger LOGGER = LoggerFactory.getLogger(SiteBootstrapAwareImportPackageHandlerFacade.class); private final static String SITE_NAME_PLACEHOLDER = "${siteName}"; protected final ImportPackageHandler delegate; protected final String siteName; public SiteBootstrapAwareImportPackageHandlerFacade(final ImportPackageHandler delegate, final String siteName) { this.delegate = delegate; this.siteName = siteName; } /** * {@inheritDoc} */ @Override public void startImport() { this.delegate.startImport(); } /** * {@inheritDoc} */ @Override public Reader getDataStream() { return this.delegate.getDataStream(); } /** * {@inheritDoc} */ @Override public InputStream importStream(final String content) { InputStream is; if (content.endsWith(".xml")) { try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(this.delegate.importStream(content), bos); String xmlContent = new String(bos.toByteArray(), StandardCharsets.UTF_8); xmlContent = xmlContent.replace(SITE_NAME_PLACEHOLDER, this.siteName); is = new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)); } catch (final IOException ex) { LOGGER.error("Error handling import of site XML content", ex); throw new AlfrescoRuntimeException("Error handling site XML content", ex); } } else { is = this.delegate.importStream(content); } return is; } /** * {@inheritDoc} */ @Override public void endImport() { this.delegate.endImport(); } }
923e8922b3836cd95a993edc9191f6d164ff308f
1,969
java
Java
src/main/java/pl/betoncraft/flier/event/FlierCollectBonusEvent.java
averyanalex/Flier
fb7a8aa9ade4b580ef375fc2a65c615c46de0727
[ "MIT" ]
4
2017-11-01T09:43:56.000Z
2019-04-24T14:20:56.000Z
src/main/java/pl/betoncraft/flier/event/FlierCollectBonusEvent.java
Tominous/Flier
136dca100483080d7cb45610b210239998699586
[ "MIT" ]
5
2020-12-28T18:10:44.000Z
2022-03-11T19:25:26.000Z
src/main/java/pl/betoncraft/flier/event/FlierCollectBonusEvent.java
Tominous/Flier
136dca100483080d7cb45610b210239998699586
[ "MIT" ]
6
2020-12-28T17:52:38.000Z
2022-01-11T14:21:17.000Z
30.292308
88
0.752666
1,000,803
/** * Copyright (c) 2017 Jakub Sapalski * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package pl.betoncraft.flier.event; import org.bukkit.event.Cancellable; import pl.betoncraft.flier.api.content.Bonus; import pl.betoncraft.flier.api.core.InGamePlayer; import pl.betoncraft.flier.core.MatchingPlayerEvent; /** * Fires when a player collects a Bonus. * * @author Jakub Sapalski */ public class FlierCollectBonusEvent extends MatchingPlayerEvent implements Cancellable { private static final String BONUS = "bonus"; private Bonus bonus; private boolean cancel = false; public FlierCollectBonusEvent(InGamePlayer player, Bonus bonus) { super(player); this.bonus = bonus; setString(BONUS, bonus.getID()); } public Bonus getBonus() { return bonus; } @Override public boolean isCancelled() { return cancel; } @Override public void setCancelled(boolean cancel) { this.cancel = cancel; } }
923e893d179c157cada97778d5d82adabcaca3f7
556
java
Java
wegas-core/src/main/java/com/wegas/editor/jsonschema/JSONRef.java
maxencelaurent/Wegas
d29b910085ad377cd2924969c53b96d48da6a1ac
[ "MIT" ]
null
null
null
wegas-core/src/main/java/com/wegas/editor/jsonschema/JSONRef.java
maxencelaurent/Wegas
d29b910085ad377cd2924969c53b96d48da6a1ac
[ "MIT" ]
null
null
null
wegas-core/src/main/java/com/wegas/editor/jsonschema/JSONRef.java
maxencelaurent/Wegas
d29b910085ad377cd2924969c53b96d48da6a1ac
[ "MIT" ]
null
null
null
20.592593
78
0.661871
1,000,804
/** * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013-2020 School of Business and Engineering Vaud, Comem, MEI * Licensed under the MIT License */ package com.wegas.editor.jsonschema; import ch.albasim.wegas.annotations.JSONSchema; import com.fasterxml.jackson.annotation.JsonProperty; public class JSONRef implements JSONSchema { @JsonProperty("$ref") private String ref; public JSONRef(String ref) { this.ref = ref; } /** * @return the ref */ public String getRef() { return ref; } }
923e8a415597c9b6c76fb27cf8b8d4789ca16545
4,027
java
Java
springfox-core/src/main/java/springfox/documentation/builders/CompoundModelSpecificationBuilder.java
ToWe0815/springfox
cb54233014c1d937e8c197546d1ae629e776878d
[ "Apache-2.0" ]
1
2019-12-25T05:59:57.000Z
2019-12-25T05:59:57.000Z
springfox-core/src/main/java/springfox/documentation/builders/CompoundModelSpecificationBuilder.java
ToWe0815/springfox
cb54233014c1d937e8c197546d1ae629e776878d
[ "Apache-2.0" ]
null
null
null
springfox-core/src/main/java/springfox/documentation/builders/CompoundModelSpecificationBuilder.java
ToWe0815/springfox
cb54233014c1d937e8c197546d1ae629e776878d
[ "Apache-2.0" ]
null
null
null
34.715517
116
0.70822
1,000,805
package springfox.documentation.builders; import springfox.documentation.schema.CompoundModelSpecification; import springfox.documentation.schema.ModelKeyBuilder; import springfox.documentation.schema.PropertySpecification; import springfox.documentation.schema.ReferenceModelSpecification; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class CompoundModelSpecificationBuilder { private final Map<String, PropertySpecificationBuilder> properties = new HashMap<>(); private final List<ReferenceModelSpecification> subclassReferences = new ArrayList<>(); private Integer maxProperties; private Integer minProperties; private ModelKeyBuilder modelKey; private String discriminator; private PropertySpecificationBuilder propertyBuilder(String name) { return properties.computeIfAbsent(name, PropertySpecificationBuilder::new); } public Function<Consumer<PropertySpecificationBuilder>, CompoundModelSpecificationBuilder> property(String name) { return property -> { property.accept(propertyBuilder(name)); return this; }; } public CompoundModelSpecificationBuilder modelKey(Consumer<ModelKeyBuilder> consumer) { if (modelKey == null) { this.modelKey = new ModelKeyBuilder(); } consumer.accept(modelKey); return this; } public CompoundModelSpecificationBuilder maxProperties(Integer maxProperties) { this.maxProperties = maxProperties; return this; } public CompoundModelSpecificationBuilder minProperties(Integer minProperties) { this.minProperties = minProperties; return this; } public CompoundModelSpecification build() { List<PropertySpecification> properties = this.properties.values().stream() .map(PropertySpecificationBuilder::build) .collect(Collectors.toList()); if (modelKey != null) { return new CompoundModelSpecification( modelKey.build(), properties, maxProperties, minProperties, discriminator, subclassReferences); } return null; } public CompoundModelSpecificationBuilder copyOf(CompoundModelSpecification other) { if (other == null) { return this; } return modelKey(m -> m.copyOf(other.getModelKey())) .properties(other.getProperties()) .maxProperties(other.getMaxProperties()) .minProperties(other.getMinProperties()) .discriminator(other.getDiscriminator()) .subclassReferences(other.getSubclassReferences()); } public CompoundModelSpecificationBuilder properties(Collection<PropertySpecification> properties) { properties.forEach(each -> this.property(each.getName()) .apply(p -> { p.type(each.getType()) .allowEmptyValue(each.getAllowEmptyValue()) .defaultValue(each.getDefaultValue()) .deprecated(each.getDeprecated()) .description(each.getDescription()) .example(each.getExample()) .isHidden(each.getHidden()) .nullable(each.getNullable()) .position(each.getPosition()) .readOnly(each.getReadOnly()) .required(each.getRequired()) .vendorExtensions(each.getVendorExtensions()) .xml(each.getXml()) .writeOnly(each.getWriteOnly()); each.getFacets() .forEach(f -> p.facetBuilder(f.facetBuilder()) .copyOf(f)); })); return this; } public CompoundModelSpecificationBuilder discriminator(String discriminator) { this.discriminator = discriminator; return this; } public CompoundModelSpecificationBuilder subclassReferences( Collection<ReferenceModelSpecification> subclassReferences) { this.subclassReferences.addAll(subclassReferences); return this; } }
923e8b65b270c7a659aedaff44274552a179bc57
424
java
Java
mantis_tests/src/test/java/model/Project.java
Juribt/Java_Challenge_
8cb38679676a7cc67bcf6de1e6ddf5ba7378cf83
[ "Apache-2.0" ]
null
null
null
mantis_tests/src/test/java/model/Project.java
Juribt/Java_Challenge_
8cb38679676a7cc67bcf6de1e6ddf5ba7378cf83
[ "Apache-2.0" ]
null
null
null
mantis_tests/src/test/java/model/Project.java
Juribt/Java_Challenge_
8cb38679676a7cc67bcf6de1e6ddf5ba7378cf83
[ "Apache-2.0" ]
null
null
null
15.142857
42
0.54717
1,000,806
package model; /** * Created by bilovyur on 30.04.2017. */ public class Project { private int id; private String name; public int getId() { return id; } public Project withId(int id) { this.id = id; return this; } public String getName() { return name; } public Project withName(String name) { this.name = name; return this; } }
923e8b9cfc2477f798b34ef48800b69e34bb8063
1,057
java
Java
notas/src/main/java/com/universidad/informacionacademica/domain/asignatura/Docente.java
MarlonDValencia/GestorNotasUniversidad-DDD
0052cdfb85e4c724b549ec1489f862e112d42c38
[ "MIT" ]
null
null
null
notas/src/main/java/com/universidad/informacionacademica/domain/asignatura/Docente.java
MarlonDValencia/GestorNotasUniversidad-DDD
0052cdfb85e4c724b549ec1489f862e112d42c38
[ "MIT" ]
null
null
null
notas/src/main/java/com/universidad/informacionacademica/domain/asignatura/Docente.java
MarlonDValencia/GestorNotasUniversidad-DDD
0052cdfb85e4c724b549ec1489f862e112d42c38
[ "MIT" ]
null
null
null
29.361111
108
0.751183
1,000,807
package com.universidad.informacionacademica.domain.asignatura; import co.com.sofka.domain.generic.Entity; import com.universidad.informacionacademica.domain.asignatura.values.*; import java.util.Objects; public class Docente extends Entity<IdDocente> { protected NombreDocente nombreDocente; protected AreaCurricular areaCurricular; protected Asignatura asignaturaAsignada; public Docente(IdDocente idDocente, NombreDocente nombreDocente, AreaCurricular areaCurricular){ super(idDocente); this.nombreDocente = nombreDocente; this.areaCurricular = areaCurricular; } public void organizarProgramaDelCurso(Asignatura asignaturaAsignada){ Objects.requireNonNull(this.asignaturaAsignada.programa, "El programa del curso no puede ser nulo"); } public NombreDocente NombreDocente() { return nombreDocente; } public AreaCurricular AreaCurricular() { return areaCurricular; } public Asignatura AsignaturaAsignada() { return asignaturaAsignada; } }
923e8cb1a99894a2ffb73f1eec13633cac1fb543
3,238
java
Java
api/src/test/java/org/jmisb/api/klv/st1206/DocumentVersionTest.java
DooblyNoobly/jmisb
6d947769058e96debb3b6ee09e1b922e651ab25b
[ "MIT" ]
26
2018-05-31T01:36:10.000Z
2022-03-23T21:40:31.000Z
api/src/test/java/org/jmisb/api/klv/st1206/DocumentVersionTest.java
DooblyNoobly/jmisb
6d947769058e96debb3b6ee09e1b922e651ab25b
[ "MIT" ]
206
2018-05-22T17:56:12.000Z
2022-03-18T10:55:27.000Z
api/src/test/java/org/jmisb/api/klv/st1206/DocumentVersionTest.java
DooblyNoobly/jmisb
6d947769058e96debb3b6ee09e1b922e651ab25b
[ "MIT" ]
10
2019-03-30T00:53:40.000Z
2022-03-16T18:27:22.000Z
38.547619
84
0.672329
1,000,808
package org.jmisb.api.klv.st1206; import static org.testng.Assert.*; import org.jmisb.api.common.KlvParseException; import org.testng.annotations.Test; /** Tests for ST 1206 Document Version (ST1206 Tag 28). */ public class DocumentVersionTest { @Test public void testConstructFromValue() { DocumentVersion version = new DocumentVersion(1); assertEquals(version.getBytes(), new byte[] {(byte) 0x01}); assertEquals(version.getDisplayName(), "Document Version"); assertEquals(version.getDisplayableValue(), "ST1206.1"); assertEquals(version.getVersion(), 1); } @Test public void testConstructFromValue255() { DocumentVersion version = new DocumentVersion(255); assertEquals(version.getBytes(), new byte[] {(byte) 0xFF}); assertEquals(version.getDisplayName(), "Document Version"); assertEquals(version.getDisplayableValue(), "ST1206.255"); assertEquals(version.getVersion(), 255); } @Test public void testConstructFromEncodedBytes() { DocumentVersion version = new DocumentVersion(new byte[] {(byte) 0x04}); assertEquals(version.getBytes(), new byte[] {(byte) 0x04}); assertEquals(version.getDisplayName(), "Document Version"); assertEquals(version.getDisplayableValue(), "ST1206.4"); assertEquals(version.getVersion(), 4); } @Test public void testConstructFromEncodedBytes0() { DocumentVersion version = new DocumentVersion(new byte[] {(byte) 0x00}); assertEquals(version.getBytes(), new byte[] {(byte) 0x00}); assertEquals(version.getDisplayName(), "Document Version"); assertEquals(version.getDisplayableValue(), "ST1206.0"); assertEquals(version.getVersion(), 0); } @Test public void testConstructFromEncodedBytes255() { DocumentVersion version = new DocumentVersion(new byte[] {(byte) 0xFF}); assertEquals(version.getBytes(), new byte[] {(byte) 0xFF}); assertEquals(version.getDisplayName(), "Document Version"); assertEquals(version.getDisplayableValue(), "ST1206.255"); assertEquals(version.getVersion(), 255); } @Test public void testFactoryEncodedBytes() throws KlvParseException { ISARMIMetadataValue value = SARMILocalSet.createValue( SARMIMetadataKey.DocumentVersion, new byte[] {(byte) 0x01}); assertTrue(value instanceof DocumentVersion); DocumentVersion version = (DocumentVersion) value; assertEquals(version.getBytes(), new byte[] {(byte) 0x01}); assertEquals(version.getDisplayName(), "Document Version"); assertEquals(version.getDisplayableValue(), "ST1206.1"); assertEquals(version.getVersion(), 1); } @Test(expectedExceptions = IllegalArgumentException.class) public void testTooSmall() { new DocumentVersion(-1); } @Test(expectedExceptions = IllegalArgumentException.class) public void testTooBig() { new DocumentVersion(256); ; } @Test(expectedExceptions = IllegalArgumentException.class) public void badArrayLength() { new DocumentVersion(new byte[] {0x01, 0x02}); } }
923e8e27f8d86d277e7bca27a540378309879d98
2,398
java
Java
imagemap/src/main/java/com/android/imagemap/MapResource.java
BhupeshSahu/ImageMapSample
5e650b281b237f68bf3a65dd3a1465e38ffaf60a
[ "MIT" ]
1
2019-09-11T09:30:54.000Z
2019-09-11T09:30:54.000Z
imagemap/src/main/java/com/android/imagemap/MapResource.java
BhupeshSahu/ImageMapAndroid
5e650b281b237f68bf3a65dd3a1465e38ffaf60a
[ "MIT" ]
null
null
null
imagemap/src/main/java/com/android/imagemap/MapResource.java
BhupeshSahu/ImageMapAndroid
5e650b281b237f68bf3a65dd3a1465e38ffaf60a
[ "MIT" ]
null
null
null
33.774648
99
0.638449
1,000,809
package com.android.imagemap; import android.content.Context; import android.view.View; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.StringReader; /** * Created by Android on 22-10-2018. */ public class MapResource { private ResourceType resourceType = null; private int resourceId = View.NO_ID; private String url = ""; private String rawString = ""; public MapResource(int resourceId) { this.resourceType = ResourceType.INTERNAL_RESOURCE; this.resourceId = resourceId; } public MapResource(ResourceType resourceType, String resValue) { this.resourceType = resourceType; if (resourceType == ResourceType.LOCAL_FILE) this.url = resValue; else if (resourceType == ResourceType.RAW_STRING) this.rawString = resValue; } public MapResource(String rawString) { resourceType = ResourceType.RAW_STRING; this.rawString = rawString; } XmlPullParser getParser(Context context) throws XmlPullParserException, FileNotFoundException { switch (resourceType) { case INTERNAL_RESOURCE: if (resourceId == 0) throw new IllegalStateException("please supply valid resource for map"); return context.getResources().getXml(resourceId); case LOCAL_FILE: if (url == null || url.trim().isEmpty()) throw new IllegalStateException("please supply valid resource for map"); File file = new File(url); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(new FileInputStream(file), "UTF-8"); return xpp; case RAW_STRING: if (rawString == null || rawString.trim().isEmpty()) throw new IllegalStateException("please supply valid resource for map"); factory = XmlPullParserFactory.newInstance(); xpp = factory.newPullParser(); xpp.setInput(new StringReader(rawString)); return xpp; } return null; } }
923e8e332a30e06e233277c33e9c375f16b78e1e
947
java
Java
src/main/java/com/jihun/study/ribbon/utils/Utils.java
nicesick/NetflixRibbonWithoutAnnotation
3a7e097a90e3fddcf9d86ceba553683180cecbb5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/jihun/study/ribbon/utils/Utils.java
nicesick/NetflixRibbonWithoutAnnotation
3a7e097a90e3fddcf9d86ceba553683180cecbb5
[ "Apache-2.0" ]
null
null
null
src/main/java/com/jihun/study/ribbon/utils/Utils.java
nicesick/NetflixRibbonWithoutAnnotation
3a7e097a90e3fddcf9d86ceba553683180cecbb5
[ "Apache-2.0" ]
null
null
null
27.057143
72
0.518479
1,000,810
package com.jihun.study.ribbon.utils; import java.io.BufferedInputStream; import java.io.InputStream; public class Utils { public static String parseResponse(InputStream inputStream) { BufferedInputStream bis = new BufferedInputStream(null); StringBuilder builder = new StringBuilder(); try { bis = new BufferedInputStream(inputStream); byte[] buffer = new byte[1024]; while(bis.read(buffer) != -1) { String bufferString = new String(buffer, "utf-8"); builder.append(bufferString); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return builder.toString(); } }
923e8f0d7299743877a8eb91d4852e7a84eabeaa
902
java
Java
src/main/java/no/ssb/dc/api/content/ContentStreamProducer.java
statisticsnorway/data-collector-api
cbac24a1a088f485f15b2bd060623ac2b5c06467
[ "Apache-2.0" ]
null
null
null
src/main/java/no/ssb/dc/api/content/ContentStreamProducer.java
statisticsnorway/data-collector-api
cbac24a1a088f485f15b2bd060623ac2b5c06467
[ "Apache-2.0" ]
3
2021-10-06T07:51:56.000Z
2022-03-10T11:11:30.000Z
src/main/java/no/ssb/dc/api/content/ContentStreamProducer.java
statisticsnorway/data-collector-api
cbac24a1a088f485f15b2bd060623ac2b5c06467
[ "Apache-2.0" ]
null
null
null
31.103448
113
0.751663
1,000,811
package no.ssb.dc.api.content; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public interface ContentStreamProducer extends AutoCloseable { ContentStreamBuffer.Builder builder(); ContentStreamProducer copy(ContentStreamBuffer buffer); ContentStreamProducer produce(ContentStreamBuffer.Builder bufferBuilder); default void publishBuilders(ContentStreamBuffer.Builder... builders) throws ClosedContentStreamException { for (ContentStreamBuffer.Builder builder : builders) { produce(builder); } publish(Arrays.stream(builders).map(ContentStreamBuffer.Builder::position).collect(Collectors.toList())); } default void publish(List<String> positions) throws ClosedContentStreamException { publish(positions.toArray(new String[positions.size()])); } void publish(String... position); }
923e91a8805686ff20611558287c1edac4dd7f6c
898
java
Java
src/main/java/com/open/coinnews/basic/interceptor/MyWebAppConfig.java
mustang2247/eth-scan-service
88e9ca029504ca7a3202b173d881b42067d8e611
[ "Apache-2.0" ]
null
null
null
src/main/java/com/open/coinnews/basic/interceptor/MyWebAppConfig.java
mustang2247/eth-scan-service
88e9ca029504ca7a3202b173d881b42067d8e611
[ "Apache-2.0" ]
null
null
null
src/main/java/com/open/coinnews/basic/interceptor/MyWebAppConfig.java
mustang2247/eth-scan-service
88e9ca029504ca7a3202b173d881b42067d8e611
[ "Apache-2.0" ]
null
null
null
39.043478
97
0.766147
1,000,812
package com.open.coinnews.basic.interceptor; import com.open.coinnews.basic.auth.interceptor.AuthInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 应用配置 */ @Configuration public class MyWebAppConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SystemInterceptor()).addPathPatterns("/**"); registry.addInterceptor(new WeixinInterceptor()).addPathPatterns("/weixin/**", "/wx/**"); registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/**"); registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/admin/**"); super.addInterceptors(registry); } }
923e91dbdc5dd1d78c20ae2ec4a53a9c35be9a4c
213
java
Java
delivery/app-release_source_from_JADX/com/google/android/gms/internal/zzjx.java
ANDROFAST/delivery_articulos
ddcc8b06d7ea2895ccda2e13c179c658703fec96
[ "Apache-2.0" ]
null
null
null
delivery/app-release_source_from_JADX/com/google/android/gms/internal/zzjx.java
ANDROFAST/delivery_articulos
ddcc8b06d7ea2895ccda2e13c179c658703fec96
[ "Apache-2.0" ]
null
null
null
delivery/app-release_source_from_JADX/com/google/android/gms/internal/zzjx.java
ANDROFAST/delivery_articulos
ddcc8b06d7ea2895ccda2e13c179c658703fec96
[ "Apache-2.0" ]
null
null
null
23.666667
67
0.807512
1,000,813
package com.google.android.gms.internal; import android.os.Bundle; import com.google.android.gms.ads.mediation.MediationBannerAdapter; public interface zzjx extends MediationBannerAdapter { Bundle zzew(); }
923e931898a754964cfd60c8ef3527413f96c27c
1,263
java
Java
src/main/java/com/touwolf/mailchimp/model/campaign/folder/CampaignFolderReadRequest.java
touwolf/mailchimp-client-api-v3
7ce92cc98a5d1f9e20cc98a245cceed223f939f3
[ "Apache-2.0" ]
1
2016-06-24T16:39:33.000Z
2016-06-24T16:39:33.000Z
src/main/java/com/touwolf/mailchimp/model/campaign/folder/CampaignFolderReadRequest.java
touwolf/mailchimp-client-api-v3
7ce92cc98a5d1f9e20cc98a245cceed223f939f3
[ "Apache-2.0" ]
2
2016-06-16T19:17:23.000Z
2016-06-16T19:18:43.000Z
src/main/java/com/touwolf/mailchimp/model/campaign/folder/CampaignFolderReadRequest.java
touwolf/mailchimp-client-api-v3
7ce92cc98a5d1f9e20cc98a245cceed223f939f3
[ "Apache-2.0" ]
null
null
null
22.553571
121
0.639747
1,000,814
package com.touwolf.mailchimp.model.campaign.folder; public class CampaignFolderReadRequest { private String fields; private String excludeFields; private Integer count; private Integer offset; /** * A comma-separated list of fields to return. Reference parameters of sub-objects with dot notation. */ public String getFields() { return fields; } public void setFields(String fields) { this.fields = fields; } /** * A comma-separated list of fields to exclude. Reference parameters of sub-objects with dot notation. */ public String getExcludeFields() { return excludeFields; } public void setExcludeFields(String excludeFields) { this.excludeFields = excludeFields; } /** * The number of records to return. */ public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } /** * The number of records from a collection to skip. Iterating over large collections with this parameter can be slow. */ public Integer getOffset() { return offset; } public void setOffset(Integer offset) { this.offset = offset; } }
923e93416d97ce4068ea013609364cff57fa47e2
546
java
Java
src/main/java/org/knard/swingConsole/syntax/StandardSyntaxCompleter.java
knard/SwingConsole
a2997e3e2871c44d38df8528aceac2069edcd969
[ "Apache-2.0" ]
null
null
null
src/main/java/org/knard/swingConsole/syntax/StandardSyntaxCompleter.java
knard/SwingConsole
a2997e3e2871c44d38df8528aceac2069edcd969
[ "Apache-2.0" ]
null
null
null
src/main/java/org/knard/swingConsole/syntax/StandardSyntaxCompleter.java
knard/SwingConsole
a2997e3e2871c44d38df8528aceac2069edcd969
[ "Apache-2.0" ]
null
null
null
21
86
0.71978
1,000,815
package org.knard.swingConsole.syntax; import java.util.List; import jline.console.completer.Completer; public class StandardSyntaxCompleter implements Completer { private Syntax syntax; public StandardSyntaxCompleter(Syntax syntax) { this.syntax = syntax; } @Override public int complete(String buffer, int cursorPos, List<CharSequence> propositions) { try { return syntax.getPropositions(buffer, cursorPos, propositions); } catch (ParseException e) { e.printStackTrace(); return -1; } } }
923e9476bae0b5c102dcb241643557339e454f3f
291
java
Java
CodingExercises/33_CarpetCostCalculator/src/Calculator.java
ntdai95-1565490/JAVA-MC
4d40a84993c54d072d0cd519bae97d6e10566e5d
[ "MIT" ]
1
2021-09-03T19:36:15.000Z
2021-09-03T19:36:15.000Z
CodingExercises/33_CarpetCostCalculator/src/Calculator.java
ntdai95-1565490/JAVA-MC
4d40a84993c54d072d0cd519bae97d6e10566e5d
[ "MIT" ]
null
null
null
CodingExercises/33_CarpetCostCalculator/src/Calculator.java
ntdai95-1565490/JAVA-MC
4d40a84993c54d072d0cd519bae97d6e10566e5d
[ "MIT" ]
null
null
null
19.4
51
0.618557
1,000,816
public class Calculator { private Floor floor; private Carpet carpet; public Calculator(Floor floor, Carpet carpet) { this.floor = floor; this.carpet = carpet; } public double getTotalCost() { return floor.getArea() * carpet.getCost(); } }
923e94ca15c0c69fdbcfb151ded72ea4fecbbca3
685
java
Java
src/test/java/com/qiniu/process/other/DownloadFileTest.java
NigelWu95/qiniu-suits
f1e8e8325fcb7e652285c181c824be200d1f9b4f
[ "Apache-2.0" ]
83
2018-12-19T01:16:10.000Z
2021-05-19T13:33:45.000Z
src/test/java/com/qiniu/process/other/DownloadFileTest.java
NigelWu95/qiniu-suits
f1e8e8325fcb7e652285c181c824be200d1f9b4f
[ "Apache-2.0" ]
9
2019-07-22T08:19:09.000Z
2022-01-04T16:34:43.000Z
src/test/java/com/qiniu/process/other/DownloadFileTest.java
NigelWu95/qiniu-suits
f1e8e8325fcb7e652285c181c824be200d1f9b4f
[ "Apache-2.0" ]
20
2018-11-14T11:04:28.000Z
2021-12-14T01:07:45.000Z
29.782609
103
0.6
1,000,817
package com.qiniu.process.other; import org.junit.Test; import java.io.IOException; import java.util.HashMap; public class DownloadFileTest { @Test public void testProcessLine() { try { DownloadFile downloadFile = new DownloadFile(null, null, null, "url", null, null,"?v=1", null, null, "~/Downloads"); String result = downloadFile.processLine(new HashMap<String, String>(){{ put("url", "http://xxx.com/-YVzTgC_I8zlDYIm8eCcPnA76pU=/ltSP7XPbPGviBNjXiZEHX7mpdm6o"); }}); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } }
923e94d676994f9dea9ada7b8a12ee91d38edcbe
169
java
Java
2201/core-java/src/main/java/com/dipanjal/batch1/polymorphism/Dog.java
dipanjal/java-learning-path
f3bd737c0509cd26570d07745c867b5707221ee6
[ "MIT" ]
1
2022-03-10T03:33:46.000Z
2022-03-10T03:33:46.000Z
2201/core-java/src/main/java/com/dipanjal/batch1/polymorphism/Dog.java
rashed-08/java-learning-path
505acc77f7cf091a1585096ccf12793877dab8fc
[ "MIT" ]
null
null
null
2201/core-java/src/main/java/com/dipanjal/batch1/polymorphism/Dog.java
rashed-08/java-learning-path
505acc77f7cf091a1585096ccf12793877dab8fc
[ "MIT" ]
4
2022-03-05T13:43:14.000Z
2022-03-22T16:11:53.000Z
15.363636
41
0.64497
1,000,818
package com.dipanjal.batch1.polymorphism; public class Dog extends Animal { @Override public void whoAmI() { System.out.println("I'm a Dog"); } }
923e950493221d4e99b6391b1273691cdfab5150
18,225
java
Java
com/mongodb/connection/BaseCluster.java
CoOwner/StaffAuth
0f7abd4f6b10f36a2de8bb732bca19f4c101e644
[ "MIT" ]
null
null
null
com/mongodb/connection/BaseCluster.java
CoOwner/StaffAuth
0f7abd4f6b10f36a2de8bb732bca19f4c101e644
[ "MIT" ]
null
null
null
com/mongodb/connection/BaseCluster.java
CoOwner/StaffAuth
0f7abd4f6b10f36a2de8bb732bca19f4c101e644
[ "MIT" ]
null
null
null
46.492347
278
0.643292
1,000,819
package com.mongodb.connection; import java.util.concurrent.atomic.*; import com.mongodb.internal.connection.*; import com.mongodb.assertions.*; import java.util.concurrent.*; import com.mongodb.async.*; import com.mongodb.selector.*; import com.mongodb.event.*; import com.mongodb.diagnostics.logging.*; import com.mongodb.*; import java.util.*; abstract class BaseCluster implements Cluster { private static final Logger LOGGER; private final AtomicReference<CountDownLatch> phase; private final ClusterableServerFactory serverFactory; private final ThreadLocal<Random> random; private final ClusterId clusterId; private final ClusterSettings settings; private final ClusterListener clusterListener; private final Deque<ServerSelectionRequest> waitQueue; private final AtomicInteger waitQueueSize; private Thread waitQueueHandler; private volatile boolean isClosed; private volatile ClusterDescription description; public BaseCluster(final ClusterId clusterId, final ClusterSettings settings, final ClusterableServerFactory serverFactory) { this.phase = new AtomicReference<CountDownLatch>(new CountDownLatch(1)); this.random = new ThreadLocal<Random>(); this.waitQueue = new ConcurrentLinkedDeque<ServerSelectionRequest>(); this.waitQueueSize = new AtomicInteger(0); this.clusterId = Assertions.notNull("clusterId", clusterId); this.settings = Assertions.notNull("settings", settings); this.serverFactory = Assertions.notNull("serverFactory", serverFactory); (this.clusterListener = (settings.getClusterListeners().isEmpty() ? new NoOpClusterListener() : new ClusterEventMulticaster(settings.getClusterListeners()))).clusterOpening(new ClusterOpeningEvent(clusterId)); } @Override public Server selectServer(final ServerSelector serverSelector) { Assertions.isTrue("open", !this.isClosed()); try { CountDownLatch currentPhase = this.phase.get(); ClusterDescription curDescription = this.description; final ServerSelector compositeServerSelector = this.getCompositeServerSelector(serverSelector); Server server = this.selectRandomServer(compositeServerSelector, curDescription); boolean selectionFailureLogged = false; long curTimeNanos; final long startTimeNanos = curTimeNanos = System.nanoTime(); final long maxWaitTimeNanos = this.getMaxWaitTimeNanos(); while (true) { this.throwIfIncompatible(curDescription); if (server != null) { return server; } if (curTimeNanos - startTimeNanos > maxWaitTimeNanos) { throw this.createTimeoutException(serverSelector, curDescription); } if (!selectionFailureLogged) { this.logServerSelectionFailure(serverSelector, curDescription); selectionFailureLogged = true; } this.connect(); currentPhase.await(Math.min(maxWaitTimeNanos - (curTimeNanos - startTimeNanos), this.getMinWaitTimeNanos()), TimeUnit.NANOSECONDS); curTimeNanos = System.nanoTime(); currentPhase = this.phase.get(); curDescription = this.description; server = this.selectRandomServer(compositeServerSelector, curDescription); } } catch (InterruptedException e) { throw new MongoInterruptedException(String.format("Interrupted while waiting for a server that matches %s", serverSelector), e); } } @Override public void selectServerAsync(final ServerSelector serverSelector, final SingleResultCallback<Server> callback) { Assertions.isTrue("open", !this.isClosed()); if (BaseCluster.LOGGER.isTraceEnabled()) { BaseCluster.LOGGER.trace(String.format("Asynchronously selecting server with selector %s", serverSelector)); } final ServerSelectionRequest request = new ServerSelectionRequest(serverSelector, this.getCompositeServerSelector(serverSelector), this.getMaxWaitTimeNanos(), callback); final CountDownLatch currentPhase = this.phase.get(); final ClusterDescription currentDescription = this.description; if (!this.handleServerSelectionRequest(request, currentPhase, currentDescription)) { this.notifyWaitQueueHandler(request); } } @Override public ClusterDescription getDescription() { Assertions.isTrue("open", !this.isClosed()); try { CountDownLatch currentPhase = this.phase.get(); ClusterDescription curDescription = this.description; boolean selectionFailureLogged = false; long curTimeNanos; final long startTimeNanos = curTimeNanos = System.nanoTime(); final long maxWaitTimeNanos = this.getMaxWaitTimeNanos(); while (curDescription.getType() == ClusterType.UNKNOWN) { if (curTimeNanos - startTimeNanos > maxWaitTimeNanos) { throw new MongoTimeoutException(String.format("Timed out after %d ms while waiting to connect. Client view of cluster state is %s", this.settings.getServerSelectionTimeout(TimeUnit.MILLISECONDS), curDescription.getShortDescription())); } if (!selectionFailureLogged) { if (BaseCluster.LOGGER.isInfoEnabled()) { if (this.settings.getServerSelectionTimeout(TimeUnit.MILLISECONDS) < 0L) { BaseCluster.LOGGER.info(String.format("Cluster description not yet available. Waiting indefinitely.", new Object[0])); } else { BaseCluster.LOGGER.info(String.format("Cluster description not yet available. Waiting for %d ms before timing out", this.settings.getServerSelectionTimeout(TimeUnit.MILLISECONDS))); } } selectionFailureLogged = true; } this.connect(); currentPhase.await(Math.min(maxWaitTimeNanos - (curTimeNanos - startTimeNanos), this.getMinWaitTimeNanos()), TimeUnit.NANOSECONDS); curTimeNanos = System.nanoTime(); currentPhase = this.phase.get(); curDescription = this.description; } return curDescription; } catch (InterruptedException e) { throw new MongoInterruptedException(String.format("Interrupted while waiting to connect", new Object[0]), e); } } protected ClusterId getClusterId() { return this.clusterId; } @Override public ClusterSettings getSettings() { return this.settings; } public ClusterableServerFactory getServerFactory() { return this.serverFactory; } protected abstract void connect(); @Override public void close() { if (!this.isClosed()) { this.isClosed = true; this.phase.get().countDown(); this.clusterListener.clusterClosed(new ClusterClosedEvent(this.clusterId)); this.stopWaitQueueHandler(); } } @Override public boolean isClosed() { return this.isClosed; } protected abstract ClusterableServer getServer(final ServerAddress p0); protected synchronized void updateDescription(final ClusterDescription newDescription) { if (BaseCluster.LOGGER.isDebugEnabled()) { BaseCluster.LOGGER.debug(String.format("Updating cluster description to %s", newDescription.getShortDescription())); } this.description = newDescription; this.phase.getAndSet(new CountDownLatch(1)).countDown(); } protected void fireChangeEvent(final ClusterDescriptionChangedEvent event) { this.clusterListener.clusterDescriptionChanged(event); } ClusterDescription getCurrentDescription() { return this.description; } private long getMaxWaitTimeNanos() { if (this.settings.getServerSelectionTimeout(TimeUnit.NANOSECONDS) < 0L) { return Long.MAX_VALUE; } return this.settings.getServerSelectionTimeout(TimeUnit.NANOSECONDS); } private long getMinWaitTimeNanos() { return this.serverFactory.getSettings().getMinHeartbeatFrequency(TimeUnit.NANOSECONDS); } private boolean handleServerSelectionRequest(final ServerSelectionRequest request, final CountDownLatch currentPhase, final ClusterDescription description) { try { if (currentPhase != request.phase) { final CountDownLatch prevPhase = request.phase; request.phase = currentPhase; if (!description.isCompatibleWithDriver()) { if (BaseCluster.LOGGER.isTraceEnabled()) { BaseCluster.LOGGER.trace(String.format("Asynchronously failed server selection due to driver incompatibility with server", new Object[0])); } request.onResult(null, this.createIncompatibleException(description)); return true; } final Server server = this.selectRandomServer(request.compositeSelector, description); if (server != null) { if (BaseCluster.LOGGER.isTraceEnabled()) { BaseCluster.LOGGER.trace(String.format("Asynchronously selected server %s", server.getDescription().getAddress())); } request.onResult(server, null); return true; } if (prevPhase == null) { this.logServerSelectionFailure(request.originalSelector, description); } } if (request.timedOut()) { if (BaseCluster.LOGGER.isTraceEnabled()) { BaseCluster.LOGGER.trace(String.format("Asynchronously failed server selection after timeout", new Object[0])); } request.onResult(null, this.createTimeoutException(request.originalSelector, description)); return true; } return false; } catch (Exception e) { request.onResult(null, e); return true; } } private void logServerSelectionFailure(final ServerSelector serverSelector, final ClusterDescription curDescription) { if (BaseCluster.LOGGER.isInfoEnabled()) { if (this.settings.getServerSelectionTimeout(TimeUnit.MILLISECONDS) < 0L) { BaseCluster.LOGGER.info(String.format("No server chosen by %s from cluster description %s. Waiting indefinitely.", serverSelector, curDescription)); } else { BaseCluster.LOGGER.info(String.format("No server chosen by %s from cluster description %s. Waiting for %d ms before timing out", serverSelector, curDescription, this.settings.getServerSelectionTimeout(TimeUnit.MILLISECONDS))); } } } private Server selectRandomServer(final ServerSelector serverSelector, final ClusterDescription clusterDescription) { final List<ServerDescription> serverDescriptions = serverSelector.select(clusterDescription); if (!serverDescriptions.isEmpty()) { return this.getRandomServer(new ArrayList<ServerDescription>(serverDescriptions)); } return null; } private ServerSelector getCompositeServerSelector(final ServerSelector serverSelector) { if (this.settings.getServerSelector() == null) { return serverSelector; } return new CompositeServerSelector(Arrays.asList(serverSelector, this.settings.getServerSelector())); } private ClusterableServer getRandomServer(final List<ServerDescription> serverDescriptions) { while (!serverDescriptions.isEmpty()) { final int serverPos = this.getRandom().nextInt(serverDescriptions.size()); final ClusterableServer server = this.getServer(serverDescriptions.get(serverPos).getAddress()); if (server != null) { return server; } serverDescriptions.remove(serverPos); } return null; } private Random getRandom() { Random result = this.random.get(); if (result == null) { result = new Random(); this.random.set(result); } return result; } protected ClusterableServer createServer(final ServerAddress serverAddress, final ServerListener serverListener) { final ClusterableServer server = this.serverFactory.create(serverAddress, serverListener); return server; } private void throwIfIncompatible(final ClusterDescription curDescription) { if (!curDescription.isCompatibleWithDriver()) { throw this.createIncompatibleException(curDescription); } } private MongoIncompatibleDriverException createIncompatibleException(final ClusterDescription curDescription) { return new MongoIncompatibleDriverException(String.format("This version of the driver is not compatible with one or more of the servers to which it is connected: %s", curDescription), curDescription); } private MongoTimeoutException createTimeoutException(final ServerSelector serverSelector, final ClusterDescription curDescription) { return new MongoTimeoutException(String.format("Timed out after %d ms while waiting for a server that matches %s. Client view of cluster state is %s", this.settings.getServerSelectionTimeout(TimeUnit.MILLISECONDS), serverSelector, curDescription.getShortDescription())); } private MongoWaitQueueFullException createWaitQueueFullException() { return new MongoWaitQueueFullException(String.format("Too many operations are already waiting for a server. Max number of operations (maxWaitQueueSize) of %d has been exceeded.", this.settings.getMaxWaitQueueSize())); } private synchronized void notifyWaitQueueHandler(final ServerSelectionRequest request) { if (this.isClosed) { return; } if (this.waitQueueSize.incrementAndGet() > this.settings.getMaxWaitQueueSize()) { this.waitQueueSize.decrementAndGet(); request.onResult(null, this.createWaitQueueFullException()); } else { this.waitQueue.add(request); if (this.waitQueueHandler == null) { (this.waitQueueHandler = new Thread(new WaitQueueHandler(), "cluster-" + this.clusterId.getValue())).setDaemon(true); this.waitQueueHandler.start(); } } } private synchronized void stopWaitQueueHandler() { if (this.waitQueueHandler != null) { this.waitQueueHandler.interrupt(); } } static { LOGGER = Loggers.getLogger("cluster"); } private static final class ServerSelectionRequest { private final ServerSelector originalSelector; private final ServerSelector compositeSelector; private final long maxWaitTimeNanos; private final SingleResultCallback<Server> callback; private final long startTimeNanos; private CountDownLatch phase; ServerSelectionRequest(final ServerSelector serverSelector, final ServerSelector compositeSelector, final long maxWaitTimeNanos, final SingleResultCallback<Server> callback) { this.startTimeNanos = System.nanoTime(); this.originalSelector = serverSelector; this.compositeSelector = compositeSelector; this.maxWaitTimeNanos = maxWaitTimeNanos; this.callback = callback; } void onResult(final Server server, final Throwable t) { try { this.callback.onResult(server, t); } catch (Throwable t2) {} } boolean timedOut() { return System.nanoTime() - this.startTimeNanos > this.maxWaitTimeNanos; } long getRemainingTime() { return this.startTimeNanos + this.maxWaitTimeNanos - System.nanoTime(); } } private final class WaitQueueHandler implements Runnable { @Override public void run() { while (!BaseCluster.this.isClosed) { final CountDownLatch currentPhase = BaseCluster.this.phase.get(); final ClusterDescription curDescription = BaseCluster.this.description; long waitTimeNanos = Long.MAX_VALUE; final Iterator<ServerSelectionRequest> iter = BaseCluster.this.waitQueue.iterator(); while (iter.hasNext()) { final ServerSelectionRequest nextRequest = iter.next(); if (BaseCluster.this.handleServerSelectionRequest(nextRequest, currentPhase, curDescription)) { iter.remove(); BaseCluster.this.waitQueueSize.decrementAndGet(); } else { waitTimeNanos = Math.min(nextRequest.getRemainingTime(), Math.min(BaseCluster.this.getMinWaitTimeNanos(), waitTimeNanos)); } } if (waitTimeNanos < Long.MAX_VALUE) { BaseCluster.this.connect(); } try { currentPhase.await(waitTimeNanos, TimeUnit.NANOSECONDS); } catch (InterruptedException ex) {} } final Iterator<ServerSelectionRequest> iter2 = BaseCluster.this.waitQueue.iterator(); while (iter2.hasNext()) { iter2.next().onResult(null, new MongoClientException("Shutdown in progress")); iter2.remove(); } } } }
923e95583f97f8562080e802c09c2ba95ec35584
13,382
java
Java
languages/FluentEditor/source_gen/FluentEditor/editor/BlockRoot_EditorBuilder_a.java
peterquiel/mps-sandbox
60ea3dc88a88cfc326be3d1f8b00c12fd1cc110e
[ "Apache-2.0" ]
null
null
null
languages/FluentEditor/source_gen/FluentEditor/editor/BlockRoot_EditorBuilder_a.java
peterquiel/mps-sandbox
60ea3dc88a88cfc326be3d1f8b00c12fd1cc110e
[ "Apache-2.0" ]
null
null
null
languages/FluentEditor/source_gen/FluentEditor/editor/BlockRoot_EditorBuilder_a.java
peterquiel/mps-sandbox
60ea3dc88a88cfc326be3d1f8b00c12fd1cc110e
[ "Apache-2.0" ]
null
null
null
49.932836
306
0.780825
1,000,820
package FluentEditor.editor; /*Generated by MPS */ import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.openapi.editor.EditorContext; import jetbrains.mps.openapi.editor.cells.EditorCell; import jetbrains.mps.nodeEditor.cells.EditorCell_Collection; import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent; import jetbrains.mps.openapi.editor.style.Style; import jetbrains.mps.editor.runtime.style.StyleImpl; import jetbrains.mps.editor.runtime.style.StyleAttributes; import jetbrains.mps.nodeEditor.cells.EditorCell_Constant; import org.jetbrains.mps.openapi.language.SProperty; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import jetbrains.mps.openapi.editor.menus.transformation.SPropertyInfo; import jetbrains.mps.nodeEditor.cells.EditorCell_Property; import jetbrains.mps.nodeEditor.cells.SPropertyAccessor; import jetbrains.mps.openapi.editor.cells.CellActionType; import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSPropertyOrNode; import jetbrains.mps.nodeEditor.cellActions.CellAction_DeleteNode; import jetbrains.mps.nodeEditor.cellMenu.SPropertySubstituteInfo; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.AttributeOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.IAttributeDescriptor; import jetbrains.mps.internal.collections.runtime.Sequence; import jetbrains.mps.internal.collections.runtime.IWhereFilter; import java.util.Objects; import jetbrains.mps.lang.core.behavior.PropertyAttribute__BehaviorDescriptor; import jetbrains.mps.nodeEditor.EditorManager; import jetbrains.mps.openapi.editor.update.AttributeKind; import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSmart; import jetbrains.mps.openapi.editor.cells.DefaultSubstituteInfo; import jetbrains.mps.nodeEditor.cellMenu.SEmptyContainmentSubstituteInfo; import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfo; import jetbrains.mps.openapi.editor.menus.transformation.SNodeLocation; import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Horizontal; import jetbrains.mps.nodeEditor.cellProviders.AbstractCellListHandler; import jetbrains.mps.lang.editor.cellProviders.RefNodeListHandler; import org.jetbrains.mps.openapi.language.SAbstractConcept; /*package*/ class BlockRoot_EditorBuilder_a extends AbstractEditorBuilder { @NotNull private SNode myNode; public BlockRoot_EditorBuilder_a(@NotNull EditorContext context, @NotNull SNode node) { super(context); myNode = node; } @NotNull @Override public SNode getNode() { return myNode; } /*package*/ EditorCell createCell() { return createCollection_0(); } private EditorCell createCollection_0() { EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent()); editorCell.setCellId("Collection_izxkry_a"); editorCell.setBig(true); setCellContext(editorCell); Style style = new StyleImpl(); style.set(StyleAttributes.INDENT_LAYOUT_CHILDREN_NEWLINE, true); editorCell.getStyle().putAll(style); editorCell.addEditorCell(createCollection_1()); editorCell.addEditorCell(createRefNode_0()); editorCell.addEditorCell(createConstant_1()); editorCell.addEditorCell(createCollection_2()); editorCell.addEditorCell(createConstant_3()); editorCell.addEditorCell(createRefNodeList_0()); return editorCell; } private EditorCell createCollection_1() { EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent()); editorCell.setCellId("Collection_izxkry_a0"); Style style = new StyleImpl(); style.set(StyleAttributes.SELECTABLE, false); editorCell.getStyle().putAll(style); editorCell.addEditorCell(createConstant_0()); editorCell.addEditorCell(createProperty_0()); return editorCell; } private EditorCell createConstant_0() { EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "Name:"); editorCell.setCellId("Constant_izxkry_a0a"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createProperty_0() { getCellFactory().pushCellContext(); try { final SProperty property = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"); getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property)); EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, false, false), myNode); editorCell.setDefaultText("<no name>"); editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.FORWARD)); editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.BACKWARD)); editorCell.setCellId("property_name"); editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property)); setCellContext(editorCell); Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute")); Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property); } }); if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) { EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext()); return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell); } else return editorCell; } finally { getCellFactory().popCellContext(); } } private EditorCell createRefNode_0() { SingleRoleCellProvider provider = new BlockRoot_EditorBuilder_a.docSingleRoleHandler_izxkry_b0(myNode, MetaAdapterFactory.getContainmentLink(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x152366698d5110baL, 0x46c894612c37b5fcL, "doc"), getEditorContext()); return provider.createCell(); } private static class docSingleRoleHandler_izxkry_b0 extends SingleRoleCellProvider { @NotNull private SNode myNode; public docSingleRoleHandler_izxkry_b0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) { super(containmentLink, context); myNode = ownerNode; } @Override @NotNull public SNode getNode() { return myNode; } protected EditorCell createChildCell(SNode child) { EditorCell editorCell = getUpdateSession().updateChildNodeCell(child); editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x152366698d5110baL, 0x46c894612c37b5fcL, "doc"), child)); editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x152366698d5110baL, 0x46c894612c37b5fcL, "doc"), child)); installCellInfo(child, editorCell, false); return editorCell; } private void installCellInfo(SNode child, EditorCell editorCell, boolean isEmpty) { if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) { editorCell.setSubstituteInfo((isEmpty ? new SEmptyContainmentSubstituteInfo(editorCell) : new SChildSubstituteInfo(editorCell))); } if (editorCell.getSRole() == null) { editorCell.setSRole(MetaAdapterFactory.getContainmentLink(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x152366698d5110baL, 0x46c894612c37b5fcL, "doc")); } } @Override protected EditorCell createEmptyCell() { getCellFactory().pushCellContext(); getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), MetaAdapterFactory.getContainmentLink(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x152366698d5110baL, 0x46c894612c37b5fcL, "doc"))); try { EditorCell editorCell = super.createEmptyCell(); editorCell.setCellId("empty_doc"); installCellInfo(null, editorCell, true); setCellContext(editorCell); return editorCell; } finally { getCellFactory().popCellContext(); } } protected String getNoTargetText() { return "<no doc>"; } } private EditorCell createConstant_1() { EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ""); editorCell.setCellId("Constant_izxkry_c0"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createCollection_2() { EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Horizontal()); editorCell.setCellId("Collection_izxkry_d0"); editorCell.addEditorCell(createConstant_2()); return editorCell; } private EditorCell createConstant_2() { EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "Blocks:"); editorCell.setCellId("Constant_izxkry_a3a"); Style style = new StyleImpl(); style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, false); editorCell.getStyle().putAll(style); editorCell.setDefaultText(""); return editorCell; } private EditorCell createConstant_3() { EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ""); editorCell.setCellId("Constant_izxkry_e0"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createRefNodeList_0() { AbstractCellListHandler handler = new BlockRoot_EditorBuilder_a.blocksListHandler_izxkry_f0(myNode, getEditorContext()); EditorCell_Collection editorCell = handler.createCells(new CellLayout_Indent(), false); editorCell.setCellId("refNodeList_blocks"); Style style = new StyleImpl(); style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true); editorCell.getStyle().putAll(style); editorCell.setSRole(handler.getElementSRole()); return editorCell; } private static class blocksListHandler_izxkry_f0 extends RefNodeListHandler { @NotNull private SNode myNode; public blocksListHandler_izxkry_f0(SNode ownerNode, EditorContext context) { super(context, false); myNode = ownerNode; } @NotNull public SNode getNode() { return myNode; } public SContainmentLink getSLink() { return MetaAdapterFactory.getContainmentLink(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x152366698d5110baL, 0x6409f53087b16c5eL, "blocks"); } public SAbstractConcept getChildSConcept() { return MetaAdapterFactory.getConcept(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x6409f53087b16c5dL, "FluentEditor.structure.Block"); } public EditorCell createNodeCell(SNode elementNode) { EditorCell elementCell = getUpdateSession().updateChildNodeCell(elementNode); installElementCellActions(elementNode, elementCell, false); return elementCell; } public EditorCell createEmptyCell() { getCellFactory().pushCellContext(); getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(blocksListHandler_izxkry_f0.this.getNode(), MetaAdapterFactory.getContainmentLink(0x2d38ea1d8ed2480eL, 0xa77f95b0aabfe4dfL, 0x152366698d5110baL, 0x6409f53087b16c5eL, "blocks"))); try { EditorCell emptyCell = null; emptyCell = super.createEmptyCell(); installElementCellActions(null, emptyCell, true); setCellContext(emptyCell); return emptyCell; } finally { getCellFactory().popCellContext(); } } public void installElementCellActions(SNode elementNode, EditorCell elementCell, boolean isEmptyCell) { if (elementCell.getUserObject(AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET) == null) { elementCell.putUserObject(AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET, AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET); if (elementNode != null) { elementCell.setAction(CellActionType.DELETE, new CellAction_DeleteNode(elementNode, CellAction_DeleteNode.DeleteDirection.FORWARD)); elementCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteNode(elementNode, CellAction_DeleteNode.DeleteDirection.BACKWARD)); } if (elementCell.getSubstituteInfo() == null || elementCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) { elementCell.setSubstituteInfo((isEmptyCell ? new SEmptyContainmentSubstituteInfo(elementCell) : new SChildSubstituteInfo(elementCell))); } } } } }
923e95f7953bf1a0f2c41bd81a06bc6ba8330ff0
1,966
java
Java
src/main/java/org/tightblog/domain/AtomEnclosure.java
smolakalaLoginsoft/tightblog
a3f8edd44c6bb3680ca4212e13349982f00c902c
[ "Apache-2.0" ]
12
2015-05-22T02:27:41.000Z
2021-11-08T20:28:29.000Z
src/main/java/org/tightblog/domain/AtomEnclosure.java
smolakalaLoginsoft/tightblog
a3f8edd44c6bb3680ca4212e13349982f00c902c
[ "Apache-2.0" ]
410
2015-05-17T13:15:42.000Z
2022-02-14T04:20:04.000Z
src/main/java/org/tightblog/domain/AtomEnclosure.java
smolakalaLoginsoft/tightblog
a3f8edd44c6bb3680ca4212e13349982f00c902c
[ "Apache-2.0" ]
5
2016-08-13T11:21:51.000Z
2021-11-08T20:28:35.000Z
29.787879
99
0.685656
1,000,821
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. * * Source file modified from the original ASF source; all changes made * are also under Apache License. */ package org.tightblog.domain; /** * Information held within the enclosure element of an Atom entry (blog entry). * Enclosures are usually URLs to podcasts and other multimedia targets. */ public class AtomEnclosure { private String url; private String contentType; private long length; public AtomEnclosure(String u, String c, long l) { this.setUrl(u); this.setContentType(c); this.setLength(l); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public long getLength() { return length; } public void setLength(long length) { this.length = length; } public String toString() { return "AtomEnclosure: url=" + url + ", contentType=" + contentType + ", length=" + length; } }
923e9676ab8fe3596fdb5601f80ffc5d73319ee7
655
java
Java
src/test/java/com/nordstrom/automation/junit/HookInstallationTestCases.java
xjc90s/JUnit-Foundation
eb6f69d60d585357563ea3d50e7e76f96fae69b5
[ "Apache-2.0" ]
18
2018-10-24T16:08:31.000Z
2020-11-27T16:41:26.000Z
src/test/java/com/nordstrom/automation/junit/HookInstallationTestCases.java
xjc90s/JUnit-Foundation
eb6f69d60d585357563ea3d50e7e76f96fae69b5
[ "Apache-2.0" ]
19
2020-07-28T10:36:57.000Z
2022-03-27T23:04:40.000Z
src/test/java/com/nordstrom/automation/junit/HookInstallationTestCases.java
xjc90s/JUnit-Foundation
eb6f69d60d585357563ea3d50e7e76f96fae69b5
[ "Apache-2.0" ]
4
2018-11-02T08:01:27.000Z
2021-02-03T01:06:27.000Z
18.714286
47
0.632061
1,000,822
package com.nordstrom.automation.junit; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class HookInstallationTestCases { @BeforeClass public static void unitTestBeforeClass() { } @Before public void unitTestBeforeMethod() { } @Test public void unitTestMethod() { assertTrue(true); } @After public void unitTestAfterMethod() { } @AfterClass public static void unitTestAfterClass() { } }
923e96a6b51f2383311fda9383e6d0f910f6c392
328
java
Java
demo/guest-service/src/main/java/io/stepinto/demo/wildfly/swarm/guest/service/repository/GuestRepository.java
step-into-meetups/01-18-oct-wildfly-swarm-avagy-egy-spring-boot-alternativa
6258c3ae80671f32f0497992d903d1a6612b1c52
[ "MIT" ]
1
2018-09-20T15:40:38.000Z
2018-09-20T15:40:38.000Z
demo/guest-service/src/main/java/io/stepinto/demo/wildfly/swarm/guest/service/repository/GuestRepository.java
stepintomeetups/01-18-oct-wildfly-swarm-avagy-egy-spring-boot-alternativa
6258c3ae80671f32f0497992d903d1a6612b1c52
[ "MIT" ]
null
null
null
demo/guest-service/src/main/java/io/stepinto/demo/wildfly/swarm/guest/service/repository/GuestRepository.java
stepintomeetups/01-18-oct-wildfly-swarm-avagy-egy-spring-boot-alternativa
6258c3ae80671f32f0497992d903d1a6612b1c52
[ "MIT" ]
null
null
null
32.8
74
0.835366
1,000,823
package io.stepinto.demo.wildfly.swarm.guest.service.repository; import io.stepinto.demo.wildfly.swarm.guest.service.entity.Guest; import org.apache.deltaspike.data.api.EntityRepository; import org.apache.deltaspike.data.api.Repository; @Repository public interface GuestRepository extends EntityRepository<Guest, String> { }
923e96bf2ffc51007d1767677ab3c8325d1de689
3,093
java
Java
core/src/main/java/net/raumzeitfalle/registration/DegreesOfFreedom.java
Oliver-Loeffler/mask-registration
42007de2314a1bf9e962b7c3d57b27f51c978760
[ "Apache-2.0" ]
4
2019-08-23T18:59:03.000Z
2020-10-23T14:15:18.000Z
image-registration/src/main/java/net/raumzeitfalle/registration/DegreesOfFreedom.java
Oliver-Loeffler/image-registration
08b9e8ff035ff39b22d7fc758ef11fa54055bb68
[ "Apache-2.0" ]
20
2019-08-22T20:28:33.000Z
2022-02-13T19:32:44.000Z
image-registration/src/main/java/net/raumzeitfalle/registration/DegreesOfFreedom.java
Oliver-Loeffler/image-registration
08b9e8ff035ff39b22d7fc758ef11fa54055bb68
[ "Apache-2.0" ]
null
null
null
25.352459
131
0.686712
1,000,824
/*- * #%L * Image-Registration * %% * Copyright (C) 2019, 2021 Oliver Loeffler, Raumzeitfalle.net * %% * 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. * #L% */ package net.raumzeitfalle.registration; import java.util.*; import java.util.function.*; import net.raumzeitfalle.registration.displacement.Displacement; /** * * Rigid Body 3-parameter Model * <ul> * <li>DoF = 0 -&gt; no calculation possible</li> * <li>DoF = 1 -&gt; translation only</li> * <li>DoF &gt;= 2 -&gt; translation and rotation</li> * </ul> * * */ public class DegreesOfFreedom implements Consumer<Displacement>, UnaryOperator<Displacement>, OrientedOperation<Integer> { private final Set<Double> xLocations = new HashSet<>(1000); private final Set<Double> yLocations = new HashSet<>(1000); @Override public void accept(Displacement t) { if (Double.isFinite(t.getXd())) xLocations.add(Double.valueOf(t.getX())); if (Double.isFinite(t.getYd())) yLocations.add(Double.valueOf(t.getY())); } public Orientation getDirection() { if (xLocations.size() == 0 && yLocations.size() == 0) { return Orientations.XY; } if (xLocations.size() > 0 && yLocations.size() > 0) { return Orientations.XY; } if (xLocations.size() > 0) { return Orientations.X; } return Orientations.Y; } public Distribution getDistribution() { if (xLocations.isEmpty() && yLocations.isEmpty()) { throw new IllegalArgumentException("Could not determine data distribution as no valid displacements have been processed yet."); } if (xLocations.size() > 1 && yLocations.size() > 1) return Distribution.AREA; if (xLocations.size() == 1 && yLocations.size() > 1) return Distribution.VERTICAL; if (yLocations.size() == 1 && xLocations.size() > 1) return Distribution.HORIZONTAL; return Distribution.SINGULARITY; } @Override public Displacement apply(Displacement t) { accept(t); return t; } public Integer getX() { return this.xLocations.size(); } public Integer getY() { return this.yLocations.size(); } public Integer getCombined() { return Math.max(this.getX(),this.getY()); // return this.xLocations.size() + this.yLocations.size(); } public int getDimensions() { return getDirection().getDimensions(); } public int getDegrees() { Orientation orientation = this.getDirection(); return orientation.runOperation(this); } @Override public String toString() { return String.format("DegreesOfFreedom [xLocations=%s, yLocations=%s]", xLocations.size(), yLocations.size()); } }
923e979e48e3c7ce8841cd53bb1dfcdd70203635
5,791
java
Java
src/main/java/com/datengaertnerei/jira/rest/client/model/JQLReferenceData.java
datengaertnerei/jira-client
898de73da06b6bfa0347759f5132ed0121b52ce4
[ "Unlicense" ]
null
null
null
src/main/java/com/datengaertnerei/jira/rest/client/model/JQLReferenceData.java
datengaertnerei/jira-client
898de73da06b6bfa0347759f5132ed0121b52ce4
[ "Unlicense" ]
null
null
null
src/main/java/com/datengaertnerei/jira/rest/client/model/JQLReferenceData.java
datengaertnerei/jira-client
898de73da06b6bfa0347759f5132ed0121b52ce4
[ "Unlicense" ]
null
null
null
31.166667
138
0.746766
1,000,825
/* * The Jira Cloud platform REST API * Jira Cloud platform REST API documentation * * The version of the OpenAPI document: 1001.0.0-SNAPSHOT * Contact: hzdkv@example.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.datengaertnerei.jira.rest.client.model; import java.util.Objects; import java.util.Arrays; import com.datengaertnerei.jira.rest.client.model.FieldReferenceData; import com.datengaertnerei.jira.rest.client.model.FunctionReferenceData; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Lists of JQL reference data. */ @ApiModel(description = "Lists of JQL reference data.") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-05-17T17:45:56.601554Z[Etc/UTC]") public class JQLReferenceData { public static final String SERIALIZED_NAME_VISIBLE_FIELD_NAMES = "visibleFieldNames"; @SerializedName(SERIALIZED_NAME_VISIBLE_FIELD_NAMES) private List<FieldReferenceData> visibleFieldNames = null; public static final String SERIALIZED_NAME_VISIBLE_FUNCTION_NAMES = "visibleFunctionNames"; @SerializedName(SERIALIZED_NAME_VISIBLE_FUNCTION_NAMES) private List<FunctionReferenceData> visibleFunctionNames = null; public static final String SERIALIZED_NAME_JQL_RESERVED_WORDS = "jqlReservedWords"; @SerializedName(SERIALIZED_NAME_JQL_RESERVED_WORDS) private List<String> jqlReservedWords = null; public JQLReferenceData visibleFieldNames(List<FieldReferenceData> visibleFieldNames) { this.visibleFieldNames = visibleFieldNames; return this; } public JQLReferenceData addVisibleFieldNamesItem(FieldReferenceData visibleFieldNamesItem) { if (this.visibleFieldNames == null) { this.visibleFieldNames = new ArrayList<>(); } this.visibleFieldNames.add(visibleFieldNamesItem); return this; } /** * List of fields usable in JQL queries. * @return visibleFieldNames **/ @javax.annotation.Nullable @ApiModelProperty(value = "List of fields usable in JQL queries.") public List<FieldReferenceData> getVisibleFieldNames() { return visibleFieldNames; } public void setVisibleFieldNames(List<FieldReferenceData> visibleFieldNames) { this.visibleFieldNames = visibleFieldNames; } public JQLReferenceData visibleFunctionNames(List<FunctionReferenceData> visibleFunctionNames) { this.visibleFunctionNames = visibleFunctionNames; return this; } public JQLReferenceData addVisibleFunctionNamesItem(FunctionReferenceData visibleFunctionNamesItem) { if (this.visibleFunctionNames == null) { this.visibleFunctionNames = new ArrayList<>(); } this.visibleFunctionNames.add(visibleFunctionNamesItem); return this; } /** * List of functions usable in JQL queries. * @return visibleFunctionNames **/ @javax.annotation.Nullable @ApiModelProperty(value = "List of functions usable in JQL queries.") public List<FunctionReferenceData> getVisibleFunctionNames() { return visibleFunctionNames; } public void setVisibleFunctionNames(List<FunctionReferenceData> visibleFunctionNames) { this.visibleFunctionNames = visibleFunctionNames; } public JQLReferenceData jqlReservedWords(List<String> jqlReservedWords) { this.jqlReservedWords = jqlReservedWords; return this; } public JQLReferenceData addJqlReservedWordsItem(String jqlReservedWordsItem) { if (this.jqlReservedWords == null) { this.jqlReservedWords = new ArrayList<>(); } this.jqlReservedWords.add(jqlReservedWordsItem); return this; } /** * List of JQL query reserved words. * @return jqlReservedWords **/ @javax.annotation.Nullable @ApiModelProperty(value = "List of JQL query reserved words.") public List<String> getJqlReservedWords() { return jqlReservedWords; } public void setJqlReservedWords(List<String> jqlReservedWords) { this.jqlReservedWords = jqlReservedWords; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JQLReferenceData jqLReferenceData = (JQLReferenceData) o; return Objects.equals(this.visibleFieldNames, jqLReferenceData.visibleFieldNames) && Objects.equals(this.visibleFunctionNames, jqLReferenceData.visibleFunctionNames) && Objects.equals(this.jqlReservedWords, jqLReferenceData.jqlReservedWords); } @Override public int hashCode() { return Objects.hash(visibleFieldNames, visibleFunctionNames, jqlReservedWords); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class JQLReferenceData {\n"); sb.append(" visibleFieldNames: ").append(toIndentedString(visibleFieldNames)).append("\n"); sb.append(" visibleFunctionNames: ").append(toIndentedString(visibleFunctionNames)).append("\n"); sb.append(" jqlReservedWords: ").append(toIndentedString(jqlReservedWords)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
923e97b1d96458f3f0bca11928354d83aa5572eb
190
java
Java
spring/spring-aop/src/main/java/com/zjq/aop/Target.java
helloMrZhan/main-framework
40212c2f18eac0c493a8f2712d580c622fc29fa8
[ "Apache-2.0" ]
1
2022-03-14T11:34:03.000Z
2022-03-14T11:34:03.000Z
spring/spring-aop/src/main/java/com/zjq/aop/Target.java
helloMrZhan/main-framework
40212c2f18eac0c493a8f2712d580c622fc29fa8
[ "Apache-2.0" ]
null
null
null
spring/spring-aop/src/main/java/com/zjq/aop/Target.java
helloMrZhan/main-framework
40212c2f18eac0c493a8f2712d580c622fc29fa8
[ "Apache-2.0" ]
null
null
null
19
48
0.594737
1,000,826
package com.zjq.aop; public class Target implements TargetInterface { @Override public void save() { System.out.println("save running....."); //int i = 1/0; } }
923e97e3a0601a2cff2a04a03bcd9b2cab09f8df
602
java
Java
custom/src/main/java/com/centricsoftware/custom/controller/CustomController.java
Shanaforever/csDemo
63e18d0fc7bf459a0f95406cc47f1ebd21cb66ce
[ "Apache-2.0" ]
null
null
null
custom/src/main/java/com/centricsoftware/custom/controller/CustomController.java
Shanaforever/csDemo
63e18d0fc7bf459a0f95406cc47f1ebd21cb66ce
[ "Apache-2.0" ]
null
null
null
custom/src/main/java/com/centricsoftware/custom/controller/CustomController.java
Shanaforever/csDemo
63e18d0fc7bf459a0f95406cc47f1ebd21cb66ce
[ "Apache-2.0" ]
null
null
null
26.173913
67
0.772425
1,000,827
package com.centricsoftware.custom.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 用户自定义开发 * @author zheng.gong * @date 2020/5/6 */ @RestController @RequestMapping("/custom") @Slf4j public class CustomController { @PostMapping("/test") public String customControllerTest(@RequestBody String param){ return "test "+param; } }
923e98244e04a7a0256c114d81c9a3cac68771d4
1,234
java
Java
achmed-client/src/main/java/com/github/aureliano/achmed/client/idiom/LanguageSingleton.java
aureliano/achmed
914b3502c34a27598ffcb5aa65608ec5ecb19401
[ "MIT" ]
1
2016-01-21T17:35:27.000Z
2016-01-21T17:35:27.000Z
achmed-client/src/main/java/com/github/aureliano/achmed/client/idiom/LanguageSingleton.java
aureliano/achmed
914b3502c34a27598ffcb5aa65608ec5ecb19401
[ "MIT" ]
null
null
null
achmed-client/src/main/java/com/github/aureliano/achmed/client/idiom/LanguageSingleton.java
aureliano/achmed
914b3502c34a27598ffcb5aa65608ec5ecb19401
[ "MIT" ]
null
null
null
24.196078
83
0.758509
1,000,828
package com.github.aureliano.achmed.client.idiom; import java.util.Properties; import com.github.aureliano.achmed.common.helper.PropertyHelper; public class LanguageSingleton { private static LanguageSingleton instance; private Properties language; private LanguageCode defaultLanguageCode; private LanguageSingleton() { this.language = PropertyHelper.loadProperties("internationalization.properties"); this.defaultLanguageCode = LanguageCode.EN_US; } public static LanguageSingleton instance() { if (instance == null) { instance = new LanguageSingleton(); } return instance; } public String getValue(LanguageCode language, String key) { key = new StringBuilder(language.name().toLowerCase()) .append(".") .append(key) .toString(); return this.language.getProperty(key); } public String getValue(String key) { if (this.defaultLanguageCode == null) { this.defaultLanguageCode = LanguageCode.EN_US; } return this.getValue(this.defaultLanguageCode, key); } public LanguageCode getDefaultLanguageCode() { return defaultLanguageCode; } public void setDefaultLanguageCode(LanguageCode defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; } }
923e9841eae01e49d75b584df3824f6016dd01a4
1,283
java
Java
src/main/java/com/aliyun/openservices/log/common/JobScheduleType.java
git-wuweiwei/LegendUtil
d920da92ac7380a6a1508fd5ced08bd20a6c69d4
[ "Apache-2.0", "BSD-3-Clause" ]
116
2016-12-29T13:16:22.000Z
2022-02-28T06:12:15.000Z
src/main/java/com/aliyun/openservices/log/common/JobScheduleType.java
git-wuweiwei/LegendUtil
d920da92ac7380a6a1508fd5ced08bd20a6c69d4
[ "Apache-2.0", "BSD-3-Clause" ]
36
2018-01-17T06:42:34.000Z
2022-02-28T08:38:40.000Z
src/main/java/com/aliyun/openservices/log/common/JobScheduleType.java
git-wuweiwei/LegendUtil
d920da92ac7380a6a1508fd5ced08bd20a6c69d4
[ "Apache-2.0", "BSD-3-Clause" ]
58
2017-02-11T07:19:14.000Z
2022-03-03T07:27:20.000Z
18.328571
98
0.570538
1,000,829
package com.aliyun.openservices.log.common; import com.alibaba.fastjson.serializer.JSONSerializable; import com.alibaba.fastjson.serializer.JSONSerializer; import java.lang.reflect.Type; public enum JobScheduleType implements JSONSerializable { /** * Trigger in a fixed rate. */ FIXED_RATE("FixedRate"), /** * Run each hour. */ HOURLY("Hourly"), /** * Run each day */ DAILY("Daily"), /** * Run each week. */ WEEKLY("Weekly"), /** * Custom cron expression. */ CRON("Cron"), /** * Only once. */ DRY_RUN("DryRun"), /** * Long live. */ RESIDENT("Resident"), ; private final String value; JobScheduleType(String value) { this.value = value; } @Override public String toString() { return value; } public static JobScheduleType fromString(String value) { for (JobScheduleType type : JobScheduleType.values()) { if (type.value.equals(value)) { return type; } } return null; } @Override public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) { serializer.write(toString()); } }
923e98bff7ba3cf3dccbfef07853bb3e9b547374
1,347
java
Java
android_app/GuessMaster/app/src/main/java/com/example/brent/guessmaster/Person.java
bchampp/guess-master
40421ce7ad13fb77366138653541370adfce2007
[ "MIT" ]
null
null
null
android_app/GuessMaster/app/src/main/java/com/example/brent/guessmaster/Person.java
bchampp/guess-master
40421ce7ad13fb77366138653541370adfce2007
[ "MIT" ]
null
null
null
android_app/GuessMaster/app/src/main/java/com/example/brent/guessmaster/Person.java
bchampp/guess-master
40421ce7ad13fb77366138653541370adfce2007
[ "MIT" ]
null
null
null
24.490909
115
0.584261
1,000,830
/* ELEC279 | Guess Master v2 */ package com.example.brent.guessmaster; public class Person extends Entity //child class of Entity { private String gender; //Constructors public Person() { super(); //call constructor from parent class gender = "no gender"; }//Person() //Constructor with input parameters public Person(String name, Date birthDate, String entgender, double difficulty) { super(name, birthDate, difficulty); if (entgender != null) { gender = entgender; } else { System.out.println("Fatal Error"); System.exit(0); } }//Person() //Clone Constructors public Person(Person entity) { super(entity); //call parent class constructors gender = entity.gender; }//Person() //Accessors public String getGender() { return gender; }//getGender() //Mutators public void setGender(String gender) { this.gender = gender; }//setGender() public Person clone() { return new Person(this); }//clone() public String toString() { return "Name is: " + getName() + "\n" + "Born on: " + getBorn().toString() + "\n" + "Gender is: " + gender; }//toString() public String entityType() { return "Person!"; }//entityType() }
923e98fe2be4ff63b85337a58aa12bfd34742879
334
java
Java
UltimateWeb/src/com/summithill/ultimate/controller/ResourceNotFoundException.java
ultianalytics/UltimateWeb
5b0c81cd2093187239e915ba014b3c8c2e3a5d81
[ "MIT" ]
null
null
null
UltimateWeb/src/com/summithill/ultimate/controller/ResourceNotFoundException.java
ultianalytics/UltimateWeb
5b0c81cd2093187239e915ba014b3c8c2e3a5d81
[ "MIT" ]
null
null
null
UltimateWeb/src/com/summithill/ultimate/controller/ResourceNotFoundException.java
ultianalytics/UltimateWeb
5b0c81cd2093187239e915ba014b3c8c2e3a5d81
[ "MIT" ]
null
null
null
27.833333
65
0.832335
1,000,831
package com.summithill.ultimate.controller; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; // throws a 404 @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; }
923e9915d436ea730d18ea632550d03818c7eccb
1,637
java
Java
src/com/github/rytina/snake/BlockLocation.java
rytina/SnakeBukkit
d873f588c73b89b30f49641172735284284f2f20
[ "MIT" ]
null
null
null
src/com/github/rytina/snake/BlockLocation.java
rytina/SnakeBukkit
d873f588c73b89b30f49641172735284284f2f20
[ "MIT" ]
null
null
null
src/com/github/rytina/snake/BlockLocation.java
rytina/SnakeBukkit
d873f588c73b89b30f49641172735284284f2f20
[ "MIT" ]
null
null
null
20.987179
103
0.607819
1,000,832
package com.github.rytina.snake; import org.bukkit.Bukkit; import org.bukkit.block.Block; public class BlockLocation { String world; int x; int y; int z; public BlockLocation(Block b) { this.world = b.getWorld().getName(); this.x = b.getX(); this.y = b.getY(); this.z = b.getZ(); } public BlockLocation(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public BlockLocation(int x, int y, int z, String world) { this.x = x; this.y = y; this.z = z; this.world = world; } public Block getBlock() { return Bukkit.getWorld(this.world).getBlockAt(this.x, this.y, this.z); } public String getWorld() { return this.world; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public BlockLocation minus(BlockLocation toMinus) { return new BlockLocation(this.x - toMinus.x, this.y - toMinus.y, this.z - toMinus.z, this.world); } public BlockLocation add(BlockLocation toAdd) { return new BlockLocation(this.x + toAdd.x, this.y + toAdd.y, this.z + toAdd.z, this.world); } public void set(BlockLocation bL) { this.x = bL.x; this.y = bL.y; this.z = bL.z; } public BlockLocation invert() { return new BlockLocation(-this.x, -this.y, -this.z); } public Boolean equivalent(BlockLocation toTest) { return this.x == toTest.getX() && this.y == toTest.getY() && this.z == toTest.getZ() ? true : false; } public String toString() { return "World=" + this.world + "x=" + this.x + "y=" + this.y + "z=" + this.z; } }
923e99d39de8045c3349a1ab83d8427d4164553b
9,693
java
Java
src/main/java/com/covens/common/block/tiles/BlockCircleGlyph.java
zabi94/Covens-reborn
6fe956025ad47051e14e2e7c45893ddebc5c330a
[ "MIT" ]
11
2019-01-02T17:22:55.000Z
2019-12-31T21:22:29.000Z
src/main/java/com/covens/common/block/tiles/BlockCircleGlyph.java
zabi94/Covens-reborn
6fe956025ad47051e14e2e7c45893ddebc5c330a
[ "MIT" ]
66
2019-01-03T14:41:49.000Z
2021-02-24T17:47:24.000Z
src/main/java/com/covens/common/block/tiles/BlockCircleGlyph.java
zabi94/Covens-reborn
6fe956025ad47051e14e2e7c45893ddebc5c330a
[ "MIT" ]
2
2019-04-17T09:52:23.000Z
2020-05-13T17:13:03.000Z
34.37234
213
0.738471
1,000,833
package com.covens.common.block.tiles; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.covens.api.ritual.EnumGlyphType; import com.covens.api.state.StateProperties; import com.covens.common.block.BlockMod; import com.covens.common.core.statics.ModConfig; import com.covens.common.item.ModItems; import com.covens.common.tile.tiles.TileEntityGlyph; import net.minecraft.block.Block; import net.minecraft.block.BlockHorizontal; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.EnumPushReaction; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.ParticleEndRod; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.pathfinding.PathNodeType; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockCircleGlyph extends BlockMod implements ITileEntityProvider { protected static final AxisAlignedBB FLAT_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.0025D, 1.0D); public BlockCircleGlyph(String id) { super(id, Material.GRASS); this.setDefaultState(this.blockState.getBaseState().withProperty(BlockHorizontal.FACING, EnumFacing.SOUTH).withProperty(StateProperties.GLYPH_TYPE, EnumGlyphType.NORMAL).withProperty(StateProperties.LETTER, 0)); this.setHardness(5); } @Override public TileEntity createNewTileEntity(World worldIn, int meta) { if (this.getStateFromMeta(meta).getValue(StateProperties.GLYPH_TYPE).equals(EnumGlyphType.GOLDEN)) { return new TileEntityGlyph(); } return null; } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (state.getValue(StateProperties.GLYPH_TYPE) == EnumGlyphType.GOLDEN) { ((TileEntityGlyph) worldIn.getTileEntity(pos)).onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ); return true; } return false; } @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { IBlockState floor = worldIn.getBlockState(pos.down()); return floor.getBlock().canPlaceTorchOnTop(floor, worldIn, pos); } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { // Dont change the actual bounding box to the offset, as that's only a visual // thing. // This is used on the server return FLAT_AABB; } @SuppressWarnings("deprecation") @Override public Vec3d getOffset(IBlockState state, IBlockAccess worldIn, BlockPos pos) { return super.getOffset(state, worldIn, pos).scale(ModConfig.CLIENT.glyphImprecision); } @Override public boolean hasTileEntity(IBlockState state) { return state.getValue(StateProperties.GLYPH_TYPE).equals(EnumGlyphType.GOLDEN); } @Override public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { return new ArrayList<ItemStack>(0); } @Override public boolean canSilkHarvest(World world, BlockPos pos, IBlockState state, EntityPlayer player) { return false; } @Override public boolean canPlaceTorchOnTop(IBlockState state, IBlockAccess world, BlockPos pos) { return false; } @Override public float getExplosionResistance(World world, BlockPos pos, Entity exploder, Explosion explosion) { return 100; } @Override public PathNodeType getAiPathNodeType(IBlockState state, IBlockAccess world, BlockPos pos) { return PathNodeType.OPEN; } @Override public boolean isCollidable() { return true; } @Override public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return null; } @Override public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, EnumFacing side) { return super.canPlaceBlockOnSide(worldIn, pos, side) && (side == EnumFacing.UP); } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.CUTOUT; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public BlockFaceShape getBlockFaceShape(IBlockAccess world, IBlockState blockState, BlockPos pos, EnumFacing face) { return BlockFaceShape.UNDEFINED; } @Override public IBlockState getStateFromMeta(int meta) { int color = meta & 3; int dir = (meta >> 2) & 3; return this.getDefaultState().withProperty(StateProperties.GLYPH_TYPE, EnumGlyphType.values()[color]).withProperty(BlockHorizontal.FACING, EnumFacing.HORIZONTALS[dir]); } @Override public int getMetaFromState(IBlockState state) { int color = state.getValue(StateProperties.GLYPH_TYPE).ordinal(); int dir = state.getValue(BlockHorizontal.FACING).getHorizontalIndex(); return (dir << 2) | color; // Bitwise that's DDCC, where DD is either 00=south, 01=... and CC is 00=normal, // 01=golden... } @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { int letter = Math.abs(pos.getX() + (pos.getZ() * 2)) % 6; return state.withProperty(StateProperties.LETTER, letter); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, BlockHorizontal.FACING, StateProperties.GLYPH_TYPE, StateProperties.LETTER); } @Override public EnumPushReaction getPushReaction(IBlockState state) { return EnumPushReaction.DESTROY; } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) { double d0 = pos.getX() + 0.5D; double d1 = pos.getY() + 0.05D; double d2 = pos.getZ() + 0.5D; EnumParticleTypes part = this.getParticleFor(stateIn); if (part != null) { double spreadX = rand.nextGaussian() / 3; double spreadZ = rand.nextGaussian() / 3; worldIn.spawnParticle(part, d0 + spreadX, d1, d2 + spreadZ, 0.0D, 0.0D, 0.0D, new int[0]); } TileEntityGlyph te = (TileEntityGlyph) worldIn.getTileEntity(pos); if ((te != null) && te.hasRunningRitual()) { double spreadX = rand.nextGaussian() * 0.4; double spreadZ = rand.nextGaussian() * 0.4; Minecraft.getMinecraft().effectRenderer.addEffect(new ParticleEndRod(worldIn, d0 + spreadX, d1, d2 + spreadZ, 0, 0.02 + (0.1 * rand.nextDouble()), 0)); if (ModConfig.CLIENT.allGlyphParticles) { EnumParticleTypes p = this.getParticleFor(worldIn.getBlockState(pos.add(TileEntityGlyph.small.get(0)[0], 0, TileEntityGlyph.small.get(0)[1]))); if (p != null) { for (int[] coo : TileEntityGlyph.small) { if (rand.nextInt(5) == 0) { spreadX = rand.nextGaussian() * 0.4; spreadZ = rand.nextGaussian() * 0.4; worldIn.spawnParticle(p, pos.getX() + coo[0], pos.getY(), pos.getZ() + coo[1], 0, 0.05 + (0.1 * rand.nextDouble()), 0); } } } p = this.getParticleFor(worldIn.getBlockState(pos.add(TileEntityGlyph.medium.get(0)[0], 0, TileEntityGlyph.medium.get(0)[1]))); if (p != null) { for (int[] coo : TileEntityGlyph.medium) { if (rand.nextInt(5) == 0) { spreadX = rand.nextGaussian() * 0.4; spreadZ = rand.nextGaussian() * 0.4; worldIn.spawnParticle(p, pos.getX() + coo[0], pos.getY(), pos.getZ() + coo[1], 0, 0.05 + (0.1 * rand.nextDouble()), 0); } } } p = this.getParticleFor(worldIn.getBlockState(pos.add(TileEntityGlyph.big.get(0)[0], 0, TileEntityGlyph.big.get(0)[1]))); if (p != null) { for (int[] coo : TileEntityGlyph.big) { if (rand.nextInt(5) == 0) { spreadX = rand.nextGaussian() * 0.4; spreadZ = rand.nextGaussian() * 0.4; worldIn.spawnParticle(p, pos.getX() + coo[0], pos.getY(), pos.getZ() + coo[1], 0, 0.05 + (0.1 * rand.nextDouble()), 0); } } } } } } @SideOnly(Side.CLIENT) private EnumParticleTypes getParticleFor(IBlockState blockState) { if (blockState.getBlock() == this) { EnumGlyphType type = blockState.getValue(StateProperties.GLYPH_TYPE); switch (type) { case ENDER: return EnumParticleTypes.PORTAL; case NETHER: return EnumParticleTypes.FLAME; default: break; } } return null; } @Override public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { if (!this.canPlaceBlockAt(worldIn, pos)) { worldIn.destroyBlock(pos, false); } } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { int meta = state.getValue(StateProperties.GLYPH_TYPE).ordinal(); if (meta < 0 || meta >= ModItems.chalkType.length) { return ItemStack.EMPTY; } return new ItemStack(ModItems.chalkType[meta]); } @Override public void registerModel() {// No associated item } @Override public EnumOffsetType getOffsetType() { return EnumOffsetType.XZ; } }
923e99dc711eeb2a751f61ac475769f91022c096
15,939
java
Java
AndroidAnnotations/androidannotations-core/androidannotations-api/src/main/java/org/androidannotations/api/BackgroundExecutor.java
Derinmasal/androidannotations
52566338e49182279b3bc453f5fbc3f650d0da7e
[ "Apache-2.0" ]
3,850
2016-10-09T12:41:02.000Z
2022-03-28T02:16:19.000Z
AndroidAnnotations/androidannotations-core/androidannotations-api/src/main/java/org/androidannotations/api/BackgroundExecutor.java
Derinmasal/androidannotations
52566338e49182279b3bc453f5fbc3f650d0da7e
[ "Apache-2.0" ]
455
2016-10-09T11:33:31.000Z
2022-03-31T10:25:24.000Z
AndroidAnnotations/androidannotations-core/androidannotations-api/src/main/java/org/androidannotations/api/BackgroundExecutor.java
Derinmasal/androidannotations
52566338e49182279b3bc453f5fbc3f650d0da7e
[ "Apache-2.0" ]
722
2016-10-10T02:08:08.000Z
2022-03-28T09:51:27.000Z
32.728953
182
0.677709
1,000,834
/** * Copyright (C) 2010-2016 eBusiness Information, Excilys Group * Copyright (C) 2016-2020 the AndroidAnnotations project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed To in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.androidannotations.api; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import android.os.Looper; import android.os.SystemClock; import android.util.Log; public final class BackgroundExecutor { private static final String TAG = "BackgroundExecutor"; public static final Executor DEFAULT_EXECUTOR = Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors()); private static Executor executor = DEFAULT_EXECUTOR; /** * The default invocation handler for wrong thread execution. It just throws * {@link IllegalStateException} with explanation what is going wrong. * * @see #setWrongThreadListener(BackgroundExecutor.WrongThreadListener) * @see org.androidannotations.annotations.SupposeBackground * @see org.androidannotations.annotations.SupposeUiThread */ public static final WrongThreadListener DEFAULT_WRONG_THREAD_LISTENER = new WrongThreadListener() { @Override public void onUiExpected() { throw new IllegalStateException("Method invocation is expected from the UI thread"); } @Override public void onBgExpected(String... expectedSerials) { if (expectedSerials.length == 0) { throw new IllegalStateException("Method invocation is expected from a background thread, but it was called from the UI thread"); } throw new IllegalStateException("Method invocation is expected from one of serials " + Arrays.toString(expectedSerials) + ", but it was called from the UI thread"); } @Override public void onWrongBgSerial(String currentSerial, String... expectedSerials) { if (currentSerial == null) { currentSerial = "anonymous"; } throw new IllegalStateException("Method invocation is expected from one of serials " + Arrays.toString(expectedSerials) + ", but it was called from " + currentSerial + " serial"); } }; private static WrongThreadListener wrongThreadListener = DEFAULT_WRONG_THREAD_LISTENER; private static final List<Task> TASKS = new ArrayList<>(); private static final ThreadLocal<String> CURRENT_SERIAL = new ThreadLocal<>(); private BackgroundExecutor() { } /** * Execute a runnable after the given delay. * * @param runnable * the task to execute * @param delay * the time from now to delay execution, in milliseconds * * if <code>delay</code> is strictly positive and the current * executor does not support scheduling (if * {@link #setExecutor(Executor)} has been called with such an * executor) * @return Future associated to the running task * * @throws IllegalArgumentException * if the current executor set by {@link #setExecutor(Executor)} * does not support scheduling */ private static Future<?> directExecute(Runnable runnable, long delay) { Future<?> future = null; if (delay > 0) { /* no serial, but a delay: schedule the task */ if (!(executor instanceof ScheduledExecutorService)) { throw new IllegalArgumentException("The executor set does not support scheduling"); } ScheduledExecutorService scheduledExecutorService = (ScheduledExecutorService) executor; future = scheduledExecutorService.schedule(runnable, delay, TimeUnit.MILLISECONDS); } else { if (executor instanceof ExecutorService) { ExecutorService executorService = (ExecutorService) executor; future = executorService.submit(runnable); } else { /* non-cancellable task */ executor.execute(runnable); } } return future; } /** * Execute a task after (at least) its delay <strong>and</strong> after all * tasks added with the same non-null <code>serial</code> (if any) have * completed execution. * * @param task * the task to execute * @throws IllegalArgumentException * if <code>task.delay</code> is strictly positive and the current * executor does not support scheduling (if * {@link #setExecutor(Executor)} has been called with such an * executor) */ public static synchronized void execute(Task task) { if (task.id != null || task.serial != null) { /* keep task */ TASKS.add(task); } if (task.serial == null || !hasSerialRunning(task.serial)) { task.executionAsked = true; task.future = directExecute(task, task.remainingDelay); } } /** * Execute a task. * * @param runnable * the task to execute * @param id * identifier used for task cancellation * @param delay * the time from now to delay execution, in milliseconds * @param serial * the serial queue (<code>null</code> or <code>""</code> for no * serial execution) * @throws IllegalArgumentException * if <code>delay</code> is strictly positive and the current * executor does not support scheduling (if * {@link #setExecutor(Executor)} has been called with such an * executor) */ public static void execute(final Runnable runnable, String id, long delay, String serial) { execute(new Task(id, delay, serial) { @Override public void execute() { runnable.run(); } }); } /** * Execute a task after the given delay. * * @param runnable * the task to execute * @param delay * the time from now to delay execution, in milliseconds * @throws IllegalArgumentException * if <code>delay</code> is strictly positive and the current * executor does not support scheduling (if * {@link #setExecutor(Executor)} has been called with such an * executor) */ public static void execute(Runnable runnable, long delay) { directExecute(runnable, delay); } /** * Execute a task. * * @param runnable * the task to execute */ public static void execute(Runnable runnable) { directExecute(runnable, 0); } /** * Execute a task after all tasks added with the same non-null * <code>serial</code> (if any) have completed execution. * * Equivalent to {@link #execute(Runnable, String, long, String) * execute(runnable, id, 0, serial)}. * * @param runnable * the task to execute * @param id * identifier used for task cancellation * @param serial * the serial queue to use (<code>null</code> or <code>""</code> for * no serial execution) */ public static void execute(Runnable runnable, String id, String serial) { execute(runnable, id, 0, serial); } /** * Change the executor. * * Note that if the given executor is not a {@link ScheduledExecutorService} * then executing a task after a delay will not be supported anymore. If it is * not even a {@link ExecutorService} then tasks will not be cancellable * anymore. * * @param executor * the new executor */ public static void setExecutor(Executor executor) { BackgroundExecutor.executor = executor; } /** * Changes the default {@link WrongThreadListener}. To restore the default one * use {@link #DEFAULT_WRONG_THREAD_LISTENER}. * * @param listener * the new {@link WrongThreadListener} */ public static void setWrongThreadListener(WrongThreadListener listener) { wrongThreadListener = listener; } /** * Cancel all tasks having the specified <code>id</code>. * * @param id * the cancellation identifier * @param mayInterruptIfRunning * <code>true</code> if the thread executing this task should be * interrupted; otherwise, in-progress tasks are allowed to complete */ public static synchronized void cancelAll(String id, boolean mayInterruptIfRunning) { for (int i = TASKS.size() - 1; i >= 0; i--) { Task task = TASKS.get(i); if (id.equals(task.id)) { if (task.future != null) { task.future.cancel(mayInterruptIfRunning); if (!task.managed.getAndSet(true)) { /* * the task has been submitted to the executor, but its execution has not * started yet, so that its run() method will never call postExecute() */ task.postExecute(); } } else if (task.executionAsked) { Log.w(TAG, "A task with id " + task.id + " cannot be cancelled (the executor set does not support it)"); } else { /* this task has not been submitted to the executor */ TASKS.remove(i); } } } } /** * Checks if the current thread is UI thread and notifies * {@link BackgroundExecutor.WrongThreadListener#onUiExpected()} if it doesn't. */ public static void checkUiThread() { if (Looper.getMainLooper().getThread() != Thread.currentThread()) { wrongThreadListener.onUiExpected(); } } /** * Checks if the current thread is a background thread and, optionally, * restricts it with passed serials. If no serials passed and current thread is * the UI thread, then {@link WrongThreadListener#onBgExpected(String...)} will * be called. If the current thread is not UI and serials list is empty, then * this method just returns. Otherwise, if the method was called not during * {@link Task} execution or the task has no serial, then the * {@link WrongThreadListener#onWrongBgSerial(String, String...)} will be called * with null for the first parameter. If task has a serial but passed serials * don't contain that, then * {@link WrongThreadListener#onWrongBgSerial(String, String...)} will be called * with the task's serial for the first parameter. * * @param serials * (optional) list of allowed serials */ public static void checkBgThread(String... serials) { if (serials.length == 0) { if (Looper.getMainLooper().getThread() == Thread.currentThread()) { wrongThreadListener.onBgExpected(serials); } return; } String current = CURRENT_SERIAL.get(); if (current == null) { wrongThreadListener.onWrongBgSerial(null, serials); return; } for (String serial : serials) { if (serial.equals(current)) { return; } } wrongThreadListener.onWrongBgSerial(current, serials); } /** * Indicates whether a task with the specified <code>serial</code> has been * submitted to the executor. * * @param serial * the serial queue * @return <code>true</code> if such a task has been submitted, * <code>false</code> otherwise */ private static boolean hasSerialRunning(String serial) { for (Task task : TASKS) { if (task.executionAsked && serial.equals(task.serial)) { return true; } } return false; } /** * Retrieve and remove the first task having the specified <code>serial</code> * (if any). * * @param serial * the serial queue * @return task if found, <code>null</code> otherwise */ private static Task take(String serial) { int len = TASKS.size(); for (int i = 0; i < len; i++) { if (serial.equals(TASKS.get(i).serial)) { return TASKS.remove(i); } } return null; } public static abstract class Task implements Runnable { private String id; private long remainingDelay; private long targetTimeMillis; /* since epoch */ private String serial; private boolean executionAsked; private Future<?> future; /* * A task can be cancelled after it has been submitted to the executor but * before its run() method is called. In that case, run() will never be called, * hence neither will postExecute(): the tasks with the same serial identifier * (if any) will never be submitted. * * Therefore, cancelAll() *must* call postExecute() if run() is not started. * * This flag guarantees that either cancelAll() or run() manages this task post * execution, but not both. */ private AtomicBoolean managed = new AtomicBoolean(); public Task(String id, long delay, String serial) { if (!"".equals(id)) { this.id = id; } if (delay > 0) { remainingDelay = delay; targetTimeMillis = SystemClock.elapsedRealtime() + delay; } if (!"".equals(serial)) { this.serial = serial; } } @Override public void run() { if (managed.getAndSet(true)) { /* cancelled and postExecute() already called */ return; } try { CURRENT_SERIAL.set(serial); execute(); } finally { /* handle next tasks */ postExecute(); } } public abstract void execute(); private void postExecute() { if (id == null && serial == null) { /* nothing to do */ return; } CURRENT_SERIAL.set(null); synchronized (BackgroundExecutor.class) { /* execution complete */ TASKS.remove(this); if (serial != null) { Task next = take(serial); if (next != null) { if (next.remainingDelay != 0) { /* the delay may not have elapsed yet */ next.remainingDelay = Math.max(0L, next.targetTimeMillis - SystemClock.elapsedRealtime()); } /* a task having the same serial was queued, execute it */ BackgroundExecutor.execute(next); } } } } } /** * A callback interface to be notified when a method invocation is expected from * another thread. * * @see #setWrongThreadListener(WrongThreadListener) * @see #checkUiThread() * @see #checkBgThread(String...) * @see org.androidannotations.annotations.SupposeUiThread * @see org.androidannotations.annotations.SupposeBackground */ public interface WrongThreadListener { /** * Will be called, if the method is supposed to be called from the UI-thread, * but was called from a background thread. * * @see org.androidannotations.annotations.SupposeUiThread * @see #setWrongThreadListener(WrongThreadListener) * @see #DEFAULT_WRONG_THREAD_LISTENER */ void onUiExpected(); /** * Will be called, if the method is supposed to be called from a background * thread, but was called from the UI-thread. * * @param expectedSerials * a list of allowed serials. If any background thread is allowed the * list will be empty. * @see org.androidannotations.annotations.SupposeBackground * @see #setWrongThreadListener(WrongThreadListener) * @see #DEFAULT_WRONG_THREAD_LISTENER */ void onBgExpected(String... expectedSerials); /** * Will be called, if the method is supposed to be called from a background * thread with one of {@code expectedSerials}, but was called from a * {@code currentSerial}. {@code currentSerial} will be null, if it is called * from a background thread without a serial. * * @param currentSerial * the serial of caller thread or null if there is no serial * @param expectedSerials * a list of allowed serials * @see org.androidannotations.annotations.SupposeBackground * @see #setWrongThreadListener(WrongThreadListener) * @see #DEFAULT_WRONG_THREAD_LISTENER */ void onWrongBgSerial(String currentSerial, String... expectedSerials); } }
923e9a2c01f8d9d9d6cf5c6ed1b6dab37589210e
616
java
Java
OAS/src/main/java/com/xue/oas/dao/impl/PersonDaoImpl.java
mingwayXue/project
7891df67225eede50cd03f6c350d3665a21ad3de
[ "Apache-2.0" ]
null
null
null
OAS/src/main/java/com/xue/oas/dao/impl/PersonDaoImpl.java
mingwayXue/project
7891df67225eede50cd03f6c350d3665a21ad3de
[ "Apache-2.0" ]
null
null
null
OAS/src/main/java/com/xue/oas/dao/impl/PersonDaoImpl.java
mingwayXue/project
7891df67225eede50cd03f6c350d3665a21ad3de
[ "Apache-2.0" ]
null
null
null
25.666667
76
0.806818
1,000,835
package com.xue.oas.dao.impl; import javax.annotation.Resource; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import com.xue.oas.dao.PersonDao; import com.xue.oas.dao.base.impl.BaseDaoImpl; import com.xue.oas.domain.Person; @Repository("personDao") public class PersonDaoImpl extends BaseDaoImpl<Person> implements PersonDao{ /*由于实现了BaseDaoImpl,所以不需要实现注解及其方法. @Resource(name="hibernateTemplate") private HibernateTemplate hibernateTemplate; @Override public void savePerson(Person person) { this.hibernateTemplate.save(person); } */ }
923e9dd46afad0ab006a633e7eb0accf94ac1ae2
224
java
Java
org/apache/http/annotation/ThreadingBehavior.java
RIPBackdoored/Deluxe-2.6-Discord-Bot-Deobf-Source-Code
eae3657ed58dd26754d9b5ce29086e6bc1c1c9cf
[ "MIT" ]
3
2020-01-24T14:23:31.000Z
2020-11-26T18:01:44.000Z
org/apache/http/annotation/ThreadingBehavior.java
RIPBackdoored/Deluxe-2.6-Discord-Bot-Deobf-Source-Code
eae3657ed58dd26754d9b5ce29086e6bc1c1c9cf
[ "MIT" ]
null
null
null
org/apache/http/annotation/ThreadingBehavior.java
RIPBackdoored/Deluxe-2.6-Discord-Bot-Deobf-Source-Code
eae3657ed58dd26754d9b5ce29086e6bc1c1c9cf
[ "MIT" ]
2
2020-09-20T07:39:44.000Z
2021-06-07T22:14:36.000Z
14.933333
53
0.6875
1,000,836
/* * Decompiled with CFR <Could not determine version>. */ package org.apache.http.annotation; public enum ThreadingBehavior { IMMUTABLE, IMMUTABLE_CONDITIONAL, SAFE, SAFE_CONDITIONAL, UNSAFE; }
923e9e6ef4e7ce16e5fd2ed83ff608f929873cc5
6,110
java
Java
K.SparakisResume/app/src/main/java/sparakis/com/ksparakisresume/activities/AddCommentActivity.java
ksparakis/android-resume
281188a2db753f4ea2b5830e9647d468d85e0d63
[ "MIT", "Unlicense" ]
null
null
null
K.SparakisResume/app/src/main/java/sparakis/com/ksparakisresume/activities/AddCommentActivity.java
ksparakis/android-resume
281188a2db753f4ea2b5830e9647d468d85e0d63
[ "MIT", "Unlicense" ]
null
null
null
K.SparakisResume/app/src/main/java/sparakis/com/ksparakisresume/activities/AddCommentActivity.java
ksparakis/android-resume
281188a2db753f4ea2b5830e9647d468d85e0d63
[ "MIT", "Unlicense" ]
null
null
null
35.114943
144
0.638134
1,000,837
package sparakis.com.ksparakisresume.activities; import android.app.ActionBar; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONObject; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import sparakis.com.ksparakisresume.R; import sparakis.com.ksparakisresume.apicalls.ApiCallFunctions; import sparakis.com.ksparakisresume.database.Comments; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class AddCommentActivity extends AppCompatActivity { ImageButton backBtn; ImageButton sendBtn; EditText nameET; EditText companyET; ProgressBar spinner; EditText commentET; JsonHttpResponseHandler sendComment = new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ"); String nowAsString = df.format(new Date()); Comments dbComments = new Comments( nameET.getText().toString(), companyET.getText().toString(), commentET.getText().toString(), nowAsString ); dbComments.save(); finish(); } @Override public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject errorResponse) { super.onFailure(statusCode, headers, throwable, errorResponse); onError(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_comment); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); LayoutInflater inflator = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflator.inflate(R.layout.comment_toolbar, null); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(v); spinner = (ProgressBar)findViewById(R.id.progressBar1); backBtn = (ImageButton) findViewById(R.id.back_btn); sendBtn = (ImageButton) findViewById(R.id.send_btn); nameET = (EditText) findViewById(R.id.name_et); companyET = (EditText) findViewById(R.id.company_et); commentET = (EditText) findViewById(R.id.comment_et); spinner.setVisibility(View.GONE); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Send POST Request freeze(); if(nameET.getText().toString().length() < 3 || commentET.getText().toString().length() < 10) { inputError(); } else { ApiCallFunctions.post_comments(nameET.getText().toString(),companyET.getText().toString(), commentET.getText().toString(), getApplicationContext(),sendComment); } } }); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } void onError() { unfreeze(); Snackbar snackbar = Snackbar .make(findViewById(android.R.id.content), "No internet connection!", Snackbar.LENGTH_LONG) .setAction("RETRY", new View.OnClickListener() { @Override public void onClick(View view) { ApiCallFunctions.post_comments(nameET.getText().toString(),companyET.getText().toString(), commentET.getText().toString(), getApplicationContext(),sendComment); } }); // Changing message text color snackbar.setActionTextColor(Color.RED); // Changing action button text color View sbView = snackbar.getView(); TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.YELLOW); snackbar.show(); } void inputError() { unfreeze(); Snackbar snackbar = Snackbar .make(findViewById(android.R.id.content), "Inputs Error: Comment at least 20 Char, Name at least 3 Char", Snackbar.LENGTH_LONG); // Changing message text color snackbar.setActionTextColor(Color.RED); // Changing action button text color View sbView = snackbar.getView(); TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.YELLOW); snackbar.show(); } void freeze() { spinner.setVisibility(View.VISIBLE); //backBtn.setEnabled(false); companyET.setEnabled(false); commentET.setEnabled(false); nameET.setEnabled(false); sendBtn.setEnabled(false); } void unfreeze() { spinner.setVisibility(View.GONE); backBtn.setEnabled(true); companyET.setEnabled(true); commentET.setEnabled(true); nameET.setEnabled(true); sendBtn.setEnabled(true); } }
923e9e77a583d53fccf8f822a335a5e8400b2abb
2,747
java
Java
inlong-sort/sort-common/src/test/java/org/apache/inlong/sort/protocol/node/load/KafkaLoadNodeTest.java
crancchen/incubator-inlong
b0b81976ac53b947aae21eec0b11abf62d3a1cdc
[ "Apache-2.0" ]
3
2022-01-24T10:03:02.000Z
2022-02-10T04:52:33.000Z
inlong-sort/sort-common/src/test/java/org/apache/inlong/sort/protocol/node/load/KafkaLoadNodeTest.java
crancchen/incubator-inlong
b0b81976ac53b947aae21eec0b11abf62d3a1cdc
[ "Apache-2.0" ]
null
null
null
inlong-sort/sort-common/src/test/java/org/apache/inlong/sort/protocol/node/load/KafkaLoadNodeTest.java
crancchen/incubator-inlong
b0b81976ac53b947aae21eec0b11abf62d3a1cdc
[ "Apache-2.0" ]
null
null
null
47.362069
115
0.647252
1,000,838
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.inlong.sort.protocol.node.load; import org.apache.inlong.sort.formats.common.StringFormatInfo; import org.apache.inlong.sort.protocol.FieldInfo; import org.apache.inlong.sort.protocol.node.Node; import org.apache.inlong.sort.protocol.node.NodeBaseTest; import org.apache.inlong.sort.protocol.node.format.CanalJsonFormat; import org.apache.inlong.sort.protocol.transformation.FieldRelationShip; import java.util.Arrays; import java.util.TreeMap; /** * Unit test for {@link KafkaLoadNode} */ public class KafkaLoadNodeTest extends NodeBaseTest { @Override public Node getNode() { return new KafkaLoadNode("1", null, Arrays.asList(new FieldInfo("field", new StringFormatInfo())), Arrays.asList(new FieldRelationShip(new FieldInfo("field", new StringFormatInfo()), new FieldInfo("field", new StringFormatInfo()))), null, "topic", "localhost:9092", new CanalJsonFormat(), 1, new TreeMap<>(), null); } @Override public String getExpectSerializeStr() { return "{\"type\":\"kafkaLoad\",\"id\":\"1\",\"fields\":[{\"type\":\"base\",\"name\":\"field\"," + "\"formatInfo\":{\"type\":\"string\"}}],\"fieldRelationShips\":[{\"type\":\"fieldRelationShip\"," + "\"inputField\":{\"type\":\"base\",\"name\":\"field\",\"formatInfo\":{\"type\":\"string\"}}," + "\"outputField\":{\"type\":\"base\",\"name\":\"field\",\"formatInfo\":{\"type\":\"string\"}}}]," + "\"topic\":\"topic\",\"bootstrapServers\":\"localhost:9092\"," + "\"format\":{\"type\":\"canalJsonFormat\",\"ignoreParseErrors\":true," + "\"timestampFormatStandard\":\"SQL\",\"mapNullKeyMode\":\"DROP\",\"mapNullKeyLiteral\":\"null\"," + "\"encodeDecimalAsPlainNumber\":true},\"sinkParallelism\":1," + "\"properties\":{}}"; } }
923ea0b4a50b8043fa1563b1d212ebc6ef655ed9
8,429
java
Java
core/src/main/java/org/apache/accumulo/core/security/crypto/CachingHDFSSecretKeyEncryptionStrategy.java
DalavanCloud/accumulo
02eaab99469ddfcf9cd0ddd4f11bbf4b4e6d2c69
[ "Apache-2.0" ]
1
2018-07-29T20:57:50.000Z
2018-07-29T20:57:50.000Z
core/src/main/java/org/apache/accumulo/core/security/crypto/CachingHDFSSecretKeyEncryptionStrategy.java
DalavanCloud/accumulo
02eaab99469ddfcf9cd0ddd4f11bbf4b4e6d2c69
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/apache/accumulo/core/security/crypto/CachingHDFSSecretKeyEncryptionStrategy.java
DalavanCloud/accumulo
02eaab99469ddfcf9cd0ddd4f11bbf4b4e6d2c69
[ "Apache-2.0" ]
null
null
null
35.868085
99
0.693914
1,000,839
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.core.security.crypto; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.spec.SecretKeySpec; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.util.CachedConfiguration; import org.apache.commons.io.IOUtils; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A {@link SecretKeyEncryptionStrategy} that gets its key from HDFS and caches it for IO. */ public class CachingHDFSSecretKeyEncryptionStrategy implements SecretKeyEncryptionStrategy { private static final Logger log = LoggerFactory .getLogger(CachingHDFSSecretKeyEncryptionStrategy.class); private SecretKeyCache secretKeyCache = new SecretKeyCache(); @Override public CryptoModuleParameters encryptSecretKey(CryptoModuleParameters context) throws IOException { try { secretKeyCache.ensureSecretKeyCacheInitialized(context); doKeyEncryptionOperation(Cipher.WRAP_MODE, context); } catch (IOException e) { log.error("{}", e.getMessage(), e); throw new IOException(e); } return context; } @Override public CryptoModuleParameters decryptSecretKey(CryptoModuleParameters context) { try { secretKeyCache.ensureSecretKeyCacheInitialized(context); doKeyEncryptionOperation(Cipher.UNWRAP_MODE, context); } catch (IOException e) { log.error("{}", e.getMessage(), e); throw new RuntimeException(e); } return context; } private void doKeyEncryptionOperation(int encryptionMode, CryptoModuleParameters params) throws IOException { Cipher cipher = DefaultCryptoModuleUtils.getCipher( params.getAllOptions().get(Property.CRYPTO_DEFAULT_KEY_STRATEGY_CIPHER_SUITE.getKey()), params.getSecurityProvider()); try { cipher.init(encryptionMode, new SecretKeySpec(secretKeyCache.getKeyEncryptionKey(), params.getKeyAlgorithmName())); } catch (InvalidKeyException e) { log.error("{}", e.getMessage(), e); throw new RuntimeException(e); } if (Cipher.UNWRAP_MODE == encryptionMode) { try { Key plaintextKey = cipher.unwrap(params.getEncryptedKey(), params.getKeyAlgorithmName(), Cipher.SECRET_KEY); params.setPlaintextKey(plaintextKey.getEncoded()); } catch (InvalidKeyException | NoSuchAlgorithmException e) { log.error("{}", e.getMessage(), e); throw new RuntimeException(e); } } else { Key plaintextKey = new SecretKeySpec(params.getPlaintextKey(), params.getKeyAlgorithmName()); try { byte[] encryptedSecretKey = cipher.wrap(plaintextKey); params.setEncryptedKey(encryptedSecretKey); params.setOpaqueKeyEncryptionKeyID(secretKeyCache.getPathToKeyName()); } catch (InvalidKeyException | IllegalBlockSizeException e) { log.error("{}", e.getMessage(), e); throw new RuntimeException(e); } } } private static class SecretKeyCache { private boolean initialized = false; private byte[] keyEncryptionKey; private String pathToKeyName; public SecretKeyCache() {} public synchronized void ensureSecretKeyCacheInitialized(CryptoModuleParameters context) throws IOException { if (initialized) { return; } // First identify if the KEK already exists pathToKeyName = getFullPathToKey(context); if (pathToKeyName == null || pathToKeyName.equals("")) { pathToKeyName = Property.CRYPTO_DEFAULT_KEY_STRATEGY_KEY_LOCATION.getDefaultValue(); } // TODO ACCUMULO-2530 Ensure volumes are properly supported Path pathToKey = new Path(pathToKeyName); FileSystem fs = FileSystem.get(CachedConfiguration.getInstance()); DataInputStream in = null; boolean invalidFile = false; int keyEncryptionKeyLength = 0; try { if (!fs.exists(pathToKey)) { initializeKeyEncryptionKey(fs, pathToKey, context); } in = fs.open(pathToKey); keyEncryptionKeyLength = in.readInt(); // If the file length does not correctly relate to the expected key size, there is an // inconsistency and // we have no way of knowing the correct key length. // The keyEncryptionKeyLength+4 accounts for the integer read from the file. if (fs.getFileStatus(pathToKey).getLen() != keyEncryptionKeyLength + 4) { invalidFile = true; // Passing this exception forward so we can provide the more useful error message throw new IOException(); } keyEncryptionKey = new byte[keyEncryptionKeyLength]; in.readFully(keyEncryptionKey); initialized = true; } catch (EOFException e) { throw new IOException( "Could not initialize key encryption cache, malformed key encryption key file", e); } catch (IOException e) { if (invalidFile) { throw new IOException("Could not initialize key encryption cache," + " malformed key encryption key file. Expected key of lengh " + keyEncryptionKeyLength + " but file contained " + (fs.getFileStatus(pathToKey).getLen() - 4) + "bytes for key encryption key."); } else { throw new IOException("Could not initialize key encryption cache," + " unable to access or find key encryption key file", e); } } finally { IOUtils.closeQuietly(in); } } private void initializeKeyEncryptionKey(FileSystem fs, Path pathToKey, CryptoModuleParameters params) throws IOException { DataOutputStream out = null; try { out = fs.create(pathToKey); // Very important, lets hedge our bets fs.setReplication(pathToKey, (short) 5); SecureRandom random = DefaultCryptoModuleUtils.getSecureRandom( params.getRandomNumberGenerator(), params.getRandomNumberGeneratorProvider()); int keyLength = params.getKeyLength(); byte[] newRandomKeyEncryptionKey = new byte[keyLength / 8]; random.nextBytes(newRandomKeyEncryptionKey); out.writeInt(newRandomKeyEncryptionKey.length); out.write(newRandomKeyEncryptionKey); out.flush(); } finally { if (out != null) { out.close(); } } } @SuppressWarnings("deprecation") private String getFullPathToKey(CryptoModuleParameters params) { String pathToKeyName = params.getAllOptions() .get(Property.CRYPTO_DEFAULT_KEY_STRATEGY_KEY_LOCATION.getKey()); String instanceDirectory = params.getAllOptions().get(Property.INSTANCE_DFS_DIR.getKey()); if (pathToKeyName == null) { pathToKeyName = Property.CRYPTO_DEFAULT_KEY_STRATEGY_KEY_LOCATION.getDefaultValue(); } if (instanceDirectory == null) { instanceDirectory = Property.INSTANCE_DFS_DIR.getDefaultValue(); } if (!pathToKeyName.startsWith("/")) { pathToKeyName = "/" + pathToKeyName; } return instanceDirectory + pathToKeyName; } public byte[] getKeyEncryptionKey() { return keyEncryptionKey; } public String getPathToKeyName() { return pathToKeyName; } } }
923ea0c8e93c48d7c9d8257925f8c9c129dc09e7
3,540
java
Java
src/main/java/eu/benschroeder/testdata/WithRandomDateAndTime.java
ben-schroeder/random-test-data
f169d9468c4199dc9d0274e7fa841aeaed5600a0
[ "MIT" ]
1
2020-02-19T09:59:19.000Z
2020-02-19T09:59:19.000Z
src/main/java/eu/benschroeder/testdata/WithRandomDateAndTime.java
ben-schroeder/random-test-data
f169d9468c4199dc9d0274e7fa841aeaed5600a0
[ "MIT" ]
27
2020-05-12T05:13:39.000Z
2022-02-28T04:25:00.000Z
src/main/java/eu/benschroeder/testdata/WithRandomDateAndTime.java
ben-schroeder/random-test-data
f169d9468c4199dc9d0274e7fa841aeaed5600a0
[ "MIT" ]
null
null
null
27.44186
74
0.672881
1,000,840
package eu.benschroeder.testdata; import eu.benschroeder.testdata.statics.RandomDateAndTime; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.ZonedDateTime; import java.util.Date; /** * Provides random date and time objects in an interface. * * @author Benjamin Schröder **/ public interface WithRandomDateAndTime extends WithRandomNumbers { /** * Random {@link OffsetDateTime} between 1970-01-01T00:00:00Z and now. * * @see RandomDateAndTime#randomPastOffsetDateTime() */ default OffsetDateTime randomPastOffsetDateTime() { return RandomDateAndTime.randomPastOffsetDateTime(); } /** * Random {@link OffsetDateTime} between now and 2200-01-01T00:00:00Z. * * @see RandomDateAndTime#randomFutureOffsetDateTime() */ default OffsetDateTime randomFutureOffsetDateTime() { return RandomDateAndTime.randomFutureOffsetDateTime(); } /** * Random {@link ZonedDateTime} between 1970-01-01T00:00:00Z and now. * * @see RandomDateAndTime#randomPastZonedDateTime() */ default ZonedDateTime randomPastZonedDateTime() { return RandomDateAndTime.randomPastZonedDateTime(); } /** * Random {@link ZonedDateTime} between now and 2200-01-01T00:00:00Z. * * @see RandomDateAndTime#randomFutureZonedDateTime() */ default ZonedDateTime randomFutureZonedDateTime() { return RandomDateAndTime.randomFutureZonedDateTime(); } /** * Random {@link LocalDateTime} between 1970-01-01T00:00:00 and now. * * @see RandomDateAndTime#randomPastLocalDateTime() */ default LocalDateTime randomPastLocalDateTime() { return RandomDateAndTime.randomPastLocalDateTime(); } /** * Random {@link LocalDateTime} between now and 2200-01-01T00:00:00. * * @see RandomDateAndTime#randomFutureLocalDateTime() */ default LocalDateTime randomFutureLocalDateTime() { return RandomDateAndTime.randomFutureLocalDateTime(); } /** * Random {@link LocalDate} between 1970-01-01 and now. * * @see RandomDateAndTime#randomPastLocalDate() */ default LocalDate randomPastLocalDate() { return RandomDateAndTime.randomPastLocalDate(); } /** * Random {@link LocalDate} between now and 2200-01-01T00:00:00. * * @see RandomDateAndTime#randomFutureLocalDate() */ default LocalDate randomFutureLocalDate() { return RandomDateAndTime.randomFutureLocalDate(); } /** * Random {@link java.time.LocalTime}. * * @see RandomDateAndTime#randomLocalTime() */ default LocalTime randomLocalTime() { return RandomDateAndTime.randomLocalTime(); } /** * Random {@link java.time.OffsetTime}. * * @see RandomDateAndTime#randomOffsetTime() */ default OffsetTime randomOffsetTime() { return RandomDateAndTime.randomOffsetTime(); } /** * Random {@link Date} between 1970-02-01T00:00:00 and now. * * @see RandomDateAndTime#randomPastDate() */ default Date randomPastDate() { return RandomDateAndTime.randomPastDate(); } /** * Random {@link Date} between now and 2200-01-01T00:00:00. * * @see RandomDateAndTime#randomFutureDate() */ default Date randomFutureDate() { return RandomDateAndTime.randomFutureDate(); } }
923ea16d2d952b9404822180ed8050f56646d96a
571
java
Java
src/main/java/gulp/rest/alarm/model/AlarmMedicine.java
thxtome/gulp-api
d9fbf614d334d40f221bcf5309c537c0550b7d8e
[ "MIT" ]
1
2022-03-17T13:39:11.000Z
2022-03-17T13:39:11.000Z
src/main/java/gulp/rest/alarm/model/AlarmMedicine.java
thxtome/gulp-api
d9fbf614d334d40f221bcf5309c537c0550b7d8e
[ "MIT" ]
null
null
null
src/main/java/gulp/rest/alarm/model/AlarmMedicine.java
thxtome/gulp-api
d9fbf614d334d40f221bcf5309c537c0550b7d8e
[ "MIT" ]
null
null
null
19.033333
41
0.791594
1,000,841
package gulp.rest.alarm.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import gulp.rest.medicine.model.Medicine; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class AlarmMedicine { @Id @GeneratedValue private Long alarmMedicineId; private String day; @ManyToOne @JoinColumn(name = "alarm_id") private Alarm alarm; @ManyToOne @JoinColumn(name = "medicine_id") private Medicine medicine; }
923ea1a084f193bf1f22d45d7257c69c129e4975
2,176
java
Java
core/src/test/java/com/github/K0zka/jaxartes/injectables/AsyncResponseImplTest.java
K0zka/jaxartes
7c78a8aa9a056e56fc2b8ba849019b94e666c411
[ "Apache-2.0" ]
null
null
null
core/src/test/java/com/github/K0zka/jaxartes/injectables/AsyncResponseImplTest.java
K0zka/jaxartes
7c78a8aa9a056e56fc2b8ba849019b94e666c411
[ "Apache-2.0" ]
null
null
null
core/src/test/java/com/github/K0zka/jaxartes/injectables/AsyncResponseImplTest.java
K0zka/jaxartes
7c78a8aa9a056e56fc2b8ba849019b94e666c411
[ "Apache-2.0" ]
null
null
null
31.536232
117
0.732996
1,000,842
package com.github.K0zka.jaxartes.injectables; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.AsyncContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; @RunWith(MockitoJUnitRunner.class) public class AsyncResponseImplTest { @Mock HttpServletRequest request; @Mock HttpServletResponse response; @Mock AsyncContext asyncContext; AsyncResponseImpl asyncResponse; PrintWriter printWriter; StringWriter stringWriter; @Before public void setup() throws IOException { stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter); Mockito.when(request.getAsyncContext()).thenReturn(asyncContext); Mockito.when(response.getWriter()).thenReturn(printWriter); asyncResponse = new AsyncResponseImpl(request, response); } @Test public void resumeWithResponse() throws IOException { asyncResponse.resume("PASSED"); Mockito.verify(response).getWriter(); Mockito.verify(response).setContentType(Matchers.eq(MediaType.APPLICATION_JSON)); Mockito.verify(asyncContext).complete(); Assert.assertEquals("\"PASSED\"", stringWriter.toString()); } @Test public void cancel() { asyncResponse.cancel(); Mockito.verify(response).setStatus(Matchers.eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE)); Mockito.verify(asyncContext).complete(); } @Test public void cancelFail() { Mockito.when(request.getAsyncContext()).thenThrow(new IllegalStateException("async context not started")); asyncResponse.cancel(); Mockito.verify(response, Mockito.never()).setStatus(Matchers.eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE)); Mockito.verify(asyncContext, Mockito.never()).complete(); } }
923ea22679848509f0d45772eaf4de7405eab749
271
java
Java
src/main/java/br/edu/utfpr/tsi/utfparking/models/dtos/UserDTO.java
MarcusViniciusCavalcanti/web-app-utfpr-parking
70f20cd097debd9d3531a03379a1adef9d880670
[ "MIT" ]
null
null
null
src/main/java/br/edu/utfpr/tsi/utfparking/models/dtos/UserDTO.java
MarcusViniciusCavalcanti/web-app-utfpr-parking
70f20cd097debd9d3531a03379a1adef9d880670
[ "MIT" ]
16
2019-08-14T13:09:44.000Z
2019-09-20T23:11:06.000Z
src/main/java/br/edu/utfpr/tsi/utfparking/models/dtos/UserDTO.java
MarcusViniciusCavalcanti/web-app-utfpr-parking
70f20cd097debd9d3531a03379a1adef9d880670
[ "MIT" ]
null
null
null
14.263158
48
0.726937
1,000,843
package br.edu.utfpr.tsi.utfparking.models.dtos; import lombok.Builder; import lombok.Data; @Data @Builder public class UserDTO { private Long id; private String name; private String type; private AccessCardDTO accessCard; private CarDTO car; }
923ea25c84bac62bed186e41ab921fe9f4c80e54
1,276
java
Java
src/com/procippus/ivy/model/Publications.java
ivytools/ivy-facade
3fa223ecb34fe449dcc290a3d163cd5fcffa8db0
[ "Apache-2.0" ]
null
null
null
src/com/procippus/ivy/model/Publications.java
ivytools/ivy-facade
3fa223ecb34fe449dcc290a3d163cd5fcffa8db0
[ "Apache-2.0" ]
null
null
null
src/com/procippus/ivy/model/Publications.java
ivytools/ivy-facade
3fa223ecb34fe449dcc290a3d163cd5fcffa8db0
[ "Apache-2.0" ]
null
null
null
33.578947
75
0.71395
1,000,844
package com.procippus.ivy.model; /* * * Copyright 2011 Procippus, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * A publication is a list of artifacts for a given Ivy project. * * @author Procippus, LLC * @author Ryan McGuinness <i>[ryan@procippus.com]</i> */ public class Publications implements Serializable { private static final long serialVersionUID = 9003914813891505533L; List<Artifact> artifacts = new ArrayList<Artifact>(); public void addArtifact(Artifact artifact) { if (!artifacts.contains(artifact)) { artifacts.add(artifact); } } public List<Artifact> getArtifacts() { return artifacts; } }
923ea2f1c1c43798dfa06019aed1c2eb85008c3f
199
java
Java
app/src/main/java/com/example/interfaces/OnItemClickListener.java
imurluck/dreamera-master
728a1fae93ddd140432044c8ae6d1b0eb37e521b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/interfaces/OnItemClickListener.java
imurluck/dreamera-master
728a1fae93ddd140432044c8ae6d1b0eb37e521b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/interfaces/OnItemClickListener.java
imurluck/dreamera-master
728a1fae93ddd140432044c8ae6d1b0eb37e521b
[ "Apache-2.0" ]
null
null
null
16.583333
46
0.738693
1,000,845
package com.example.interfaces; import android.view.View; /** * Created by ZhangZongxiang on 2017/6/1. */ public interface OnItemClickListener { void onItemClick(View view, int position); }
923ea36d50d328018420a0b76de04300a12753ca
4,828
java
Java
codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java
dalaro/netty
80ce2bf3e4e7cd273d1bf78731b25a1b348c2875
[ "Apache-2.0" ]
3
2016-10-23T06:55:44.000Z
2018-07-09T10:21:44.000Z
codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java
dalaro/netty
80ce2bf3e4e7cd273d1bf78731b25a1b348c2875
[ "Apache-2.0" ]
13
2017-09-11T19:20:23.000Z
2020-04-07T11:33:47.000Z
codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java
dalaro/netty
80ce2bf3e4e7cd273d1bf78731b25a1b348c2875
[ "Apache-2.0" ]
8
2018-05-20T00:07:13.000Z
2019-02-22T13:29:40.000Z
32.402685
101
0.6628
1,000,846
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.http; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.FileRegion; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.util.CharsetUtil; import org.junit.Test; import java.io.IOException; import java.nio.channels.WritableByteChannel; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class HttpResponseEncoderTest { private static final long INTEGER_OVERLFLOW = (long) Integer.MAX_VALUE + 1; private static final FileRegion FILE_REGION = new DummyLongFileRegion(); @Test public void testLargeFileRegionChunked() throws Exception { EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder()); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); assertTrue(channel.writeOutbound(response)); ByteBuf buffer = channel.readOutbound(); assertEquals("HTTP/1.1 200 OK\r\n" + HttpHeaderNames.TRANSFER_ENCODING + ": " + HttpHeaderValues.CHUNKED + "\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); assertTrue(channel.writeOutbound(FILE_REGION)); buffer = channel.readOutbound(); assertEquals("80000000\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); FileRegion region = channel.readOutbound(); assertSame(FILE_REGION, region); region.release(); buffer = channel.readOutbound(); assertEquals("\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); assertTrue(channel.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT)); buffer = channel.readOutbound(); assertEquals("0\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); assertFalse(channel.finish()); } private static class DummyLongFileRegion implements FileRegion { @Override public long position() { return 0; } @Override public long transfered() { return 0; } @Override public long count() { return INTEGER_OVERLFLOW; } @Override public long transferTo(WritableByteChannel target, long position) throws IOException { throw new UnsupportedOperationException(); } @Override public FileRegion touch(Object hint) { return this; } @Override public FileRegion touch() { return this; } @Override public FileRegion retain() { return this; } @Override public FileRegion retain(int increment) { return this; } @Override public int refCnt() { return 1; } @Override public boolean release() { return false; } @Override public boolean release(int decrement) { return false; } } @Test public void testEmptyBufferBypass() throws Exception { EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder()); // Test writing an empty buffer works when the encoder is at ST_INIT. channel.writeOutbound(Unpooled.EMPTY_BUFFER); ByteBuf buffer = channel.readOutbound(); assertThat(buffer, is(sameInstance(Unpooled.EMPTY_BUFFER))); // Leave the ST_INIT state. HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); assertTrue(channel.writeOutbound(response)); buffer = channel.readOutbound(); assertEquals("HTTP/1.1 200 OK\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); // Test writing an empty buffer works when the encoder is not at ST_INIT. channel.writeOutbound(Unpooled.EMPTY_BUFFER); buffer = channel.readOutbound(); assertThat(buffer, is(sameInstance(Unpooled.EMPTY_BUFFER))); assertFalse(channel.finish()); } }
923ea3816fb4db28cdc7c5366e963d8d2c598e8b
2,472
java
Java
querystream-jpa/src/main/java/org/dellroad/querystream/jpa/querytype/SearchType.java
archiecobbs/querystream
3ebc0fb24c3652137cfb094c60b9130c9ba4298c
[ "Apache-2.0" ]
6
2018-10-23T20:36:52.000Z
2022-03-30T20:49:33.000Z
querystream-jpa/src/main/java/org/dellroad/querystream/jpa/querytype/SearchType.java
archiecobbs/querystream
3ebc0fb24c3652137cfb094c60b9130c9ba4298c
[ "Apache-2.0" ]
3
2022-01-06T23:59:30.000Z
2022-01-21T23:54:43.000Z
querystream-jpa/src/main/java/org/dellroad/querystream/jpa/querytype/SearchType.java
archiecobbs/querystream
3ebc0fb24c3652137cfb094c60b9130c9ba4298c
[ "Apache-2.0" ]
2
2020-12-16T02:46:49.000Z
2022-01-26T14:46:05.000Z
31.291139
100
0.679612
1,000,847
/* * Copyright (C) 2018 Archie L. Cobbs. All rights reserved. */ package org.dellroad.querystream.jpa.querytype; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.AbstractQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Selection; /** * Represents the JPA Criteria API search query type. * * @param <X> query result type */ public class SearchType<X> extends QueryType<X, AbstractQuery<?>, CriteriaQuery<X>, TypedQuery<X>> { /** * Constructor. * * @param type query result type * @throws IllegalArgumentException if {@code type} is null */ public SearchType(Class<X> type) { super(type); } @Override public CriteriaQuery<X> createCriteriaQuery(CriteriaBuilder builder) { if (builder == null) throw new IllegalArgumentException("null builder"); return builder.createQuery(this.type); } @Override public TypedQuery<X> createQuery(EntityManager entityManager, CriteriaQuery<X> query) { if (entityManager == null) throw new IllegalArgumentException("null entityManager"); if (query == null) throw new IllegalArgumentException("null query"); return entityManager.createQuery(query); } @Override public void where(AbstractQuery<?> query, Expression<Boolean> restriction) { if (query == null) throw new IllegalArgumentException("null query"); if (restriction == null) throw new IllegalArgumentException("null restriction"); query.where(restriction); } @Override public void where(AbstractQuery<?> query, Predicate restriction) { if (query == null) throw new IllegalArgumentException("null query"); if (restriction == null) throw new IllegalArgumentException("null restriction"); query.where(restriction); } /** * Configure the result expression associated with a query. * * @param query criteria query object * @param expression query result * @return updated criteria query object */ public CriteriaQuery<X> select(CriteriaQuery<X> query, Selection<X> expression) { return query.select(expression); } }
923ea4d285613ebc20b4f3ddbe0d1486fed0d634
1,172
java
Java
wbdemo/src/main/java/com/example/wbdemo/business/main/CommentsViewPager.java
zhoujunyuj813/ActivityTest
b877ea88969c43d3c79b83f888f499749bb248e6
[ "Apache-2.0" ]
null
null
null
wbdemo/src/main/java/com/example/wbdemo/business/main/CommentsViewPager.java
zhoujunyuj813/ActivityTest
b877ea88969c43d3c79b83f888f499749bb248e6
[ "Apache-2.0" ]
null
null
null
wbdemo/src/main/java/com/example/wbdemo/business/main/CommentsViewPager.java
zhoujunyuj813/ActivityTest
b877ea88969c43d3c79b83f888f499749bb248e6
[ "Apache-2.0" ]
null
null
null
30.051282
99
0.68686
1,000,848
package com.example.wbdemo.business.main; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.View; /** * Created by zhoujunyu on 2019/6/3. */ public class CommentsViewPager extends ViewPager { public CommentsViewPager(@NonNull Context context) { super(context); } public CommentsViewPager(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for(int i = 0 ; i < getChildCount() ; i++ ){ View child = getChildAt(i); child.measure(widthMeasureSpec,MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED)); if( child.getMeasuredHeight() > height){ height = child.getMeasuredHeight(); } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
923ea531ffb743bf8f91f82a5519fe617bbc6f81
2,971
java
Java
classpath-0.98/javax/swing/colorchooser/ColorChooserComponentFactory.java
nmldiegues/jvm-stm
d422d78ba8efc99409ecb49efdb4edf4884658df
[ "Apache-2.0" ]
2
2015-09-08T15:40:04.000Z
2017-02-09T15:19:33.000Z
llvm-gcc-4.2-2.9/libjava/classpath/javax/swing/colorchooser/ColorChooserComponentFactory.java
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-gcc-4.2-2.9/libjava/classpath/javax/swing/colorchooser/ColorChooserComponentFactory.java
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
34.149425
75
0.712218
1,000,849
/* ColorChooserComponentFactory.java -- Copyright (C) 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.swing.colorchooser; import javax.swing.JComponent; /** * ColorChooserComponentFactory * * @author Andrew Selkirk * @version 1.0 */ public class ColorChooserComponentFactory { /** * Constructor ColorChooserComponentFactory */ private ColorChooserComponentFactory() { // Nothing to do here. } /** * This method returns the three default chooser panels to be used in * JColorChooser. * * @return The default chooser panels. */ public static AbstractColorChooserPanel[] getDefaultChooserPanels() { AbstractColorChooserPanel[] values = { new DefaultSwatchChooserPanel(), new DefaultHSBChooserPanel(), new DefaultRGBChooserPanel() }; return values; } /** * This method returns the default preview panel to be used with * JColorChoosers. * * @return The default preview panel. */ public static JComponent getPreviewPanel() { return new DefaultPreviewPanel(); } // getPreviewPanel() } // ColorChooserComponentFactory
923ea5c07133d09c48bdb349edf626090fd3f097
1,458
java
Java
src/main/java/com/zx5435/idea/kubernetes/node/config/SecretNode.java
zx5435/idea-kubernetes
72e06c5f0e8c6e108dd3fc02345ea340790e3641
[ "Apache-2.0" ]
1
2021-06-01T05:22:13.000Z
2021-06-01T05:22:13.000Z
src/main/java/com/zx5435/idea/kubernetes/node/config/SecretNode.java
zx5435/k8show
72e06c5f0e8c6e108dd3fc02345ea340790e3641
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zx5435/idea/kubernetes/node/config/SecretNode.java
zx5435/k8show
72e06c5f0e8c6e108dd3fc02345ea340790e3641
[ "Apache-2.0" ]
null
null
null
25.137931
113
0.663923
1,000,850
package com.zx5435.idea.kubernetes.node.config; import com.intellij.icons.AllIcons; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.JBMenuItem; import com.intellij.openapi.ui.JBPopupMenu; import com.zx5435.idea.kubernetes.editor.YamlEditorView; import com.zx5435.idea.kubernetes.node.ATreeNode; import com.zx5435.idea.kubernetes.utils.KubeUtil; import io.fabric8.kubernetes.api.model.Secret; import lombok.extern.slf4j.Slf4j; import javax.swing.*; /** * @author zx5435 */ @Slf4j public class SecretNode extends ATreeNode { Secret ins; public SecretNode(Secret ns) { this.ins = ns; } @Override public String getLabel() { return ins.getMetadata().getName(); } @Override public Icon getIcon() { return AllIcons.Actions.ShowCode; } @Override public JBPopupMenu getMenu(Project project) { JBPopupMenu menu = new JBPopupMenu(); JBMenuItem b1 = new JBMenuItem("Load", AllIcons.Actions.Show); b1.addActionListener(e -> { String yaml = KubeUtil.getSecret(getCtx().getClient(), ins.getMetadata().getNamespace(), getLabel()); YamlEditorView.load(project, getLabel(), yaml); }); menu.add(b1); JBMenuItem b2 = new JBMenuItem("Delete", AllIcons.Actions.Close); b2.addActionListener(e -> { log.warn("todo"); }); menu.add(b2); return menu; } }
923ea5e076d48dbffc3cff4c64628832ba450cb2
12,072
java
Java
MLSClientes/src/util/BLMascaras.java
mlssystem/mlsClientes
43f5d8cd5a0af90fb1afa087d6c26db4020aa426
[ "MIT" ]
null
null
null
MLSClientes/src/util/BLMascaras.java
mlssystem/mlsClientes
43f5d8cd5a0af90fb1afa087d6c26db4020aa426
[ "MIT" ]
null
null
null
MLSClientes/src/util/BLMascaras.java
mlssystem/mlsClientes
43f5d8cd5a0af90fb1afa087d6c26db4020aa426
[ "MIT" ]
null
null
null
28.606635
95
0.549702
1,000,851
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package util; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /** * * @author Leandro */ public class BLMascaras { /** * converte a virgula de uma string para ponto * * @param pString * @return String */ public String converterVirgulaParaPonto(String pString) { String retorno = new String(); int tamanhoString = pString.length(); for (int i = 0; i < tamanhoString; i++) { if (pString.charAt(i) == ',') { retorno += '.'; } else { retorno += pString.charAt(i); } } return retorno; } /** * converte a virgula de uma string para ponto * * @param pString * @return String */ public String converterPontoPraVirgula(String pString) { String retorno = new String(); int tamanhoString = pString.length(); for (int i = 0; i < tamanhoString; i++) { if (pString.charAt(i) == '.') { retorno += ','; } else { retorno += pString.charAt(i); } } return retorno; } /** * converte a virgula de uma string para ponto * * @param pString * @return float */ public float converterVirgulaParaPontoReturnFloat(String pString) { String retorno = new String(); int tamanhoString = pString.length(); for (int i = 0; i < tamanhoString; i++) { if (pString.charAt(i) == ',') { retorno += '.'; } else { retorno += pString.charAt(i); } } return Float.parseFloat(retorno); } /** * retira os pontos do valor * * @param pString * @return */ public String removerPontos(String pString) { String retorno = new String(); int tamanhoString = pString.length(); for (int i = 0; i < tamanhoString; i++) { if (pString.charAt(i) == '.') { retorno += ""; } else { retorno += pString.charAt(i); } } return retorno; } /** * adiciona um ponto a string * * @param pString * @return String */ public String addPonto(String pString) { int pontoConter = 0; for (int i = 0; i < pString.length(); i++) { if (pString.charAt(i) == '.') { pontoConter++; } } if (pontoConter == 0) { pString += ".0"; } return pString; } /** * truca o valor com 3 casas decimais * * @param pValor * @return double */ public double truncar3Casas(double pValor) { return Math.round(pValor * 100) / 100d; } public int converteInteiro(int pString) { DecimalFormat df = new DecimalFormat("#.0"); pString = Integer.parseInt(df.format(pString)); return pString; } /** * Arredonda com 2 casas decimais. */ public double converteArredondar2Casas(double pDouble) { DecimalFormat df = new DecimalFormat("#,00"); pDouble = Double.parseDouble(df.format(pDouble)); return pDouble; } /** * arredonda um valor com ponto * * @param pValor * @return */ public float arredondamentoComPontoDuasCasas(float pValor) { DecimalFormat df = new DecimalFormat("#.00"); return Float.parseFloat(this.converterVirgulaParaPonto(df.format(pValor))); } /** * arredonda um valor com ponto * * @param pValor * @return */ public double arredondamentoComPontoDuasCasasDouble(float pValor) { DecimalFormat df = new DecimalFormat("#.00"); return Double.parseDouble(this.converterVirgulaParaPonto(df.format(pValor))); } /** * arredonda um valor com ponto string formatada * * @param pValor * @return */ public String arredondamentoComPontoDuasCasasString(float pValor) { DecimalFormat df = new DecimalFormat("#.00"); return this.converterVirgulaParaPonto(df.format(pValor)); } /** * arredonda um valor com ponto * * @param pValor * @return */ public float arredondamentoComPontoTresCasas(float pValor) { DecimalFormat df = new DecimalFormat("#.000"); return Float.parseFloat(this.converterVirgulaParaPonto(df.format(pValor))); } /** * arredonda um valor com ponto * * @param pValor * @return */ public String arredondamentoDoubleComPontoDuasCasasString(Double pValor) { DecimalFormat df = new DecimalFormat("#.00"); return this.converterVirgulaParaPonto(df.format(pValor)); } public String TiraAcentos(String passa) { passa = passa.replaceAll("[ÂÀÁÄÃ]", "A"); passa = passa.replaceAll("[âãàáä]", "a"); passa = passa.replaceAll("[ÊÈÉË]", "E"); passa = passa.replaceAll("[êèéë]", "e"); passa = passa.replaceAll("ÎÍÌÏ", "I"); passa = passa.replaceAll("îíìï", "i"); passa = passa.replaceAll("[ÔÕÒÓÖ]", "O"); passa = passa.replaceAll("[ôõòóö]", "o"); passa = passa.replaceAll("[ÛÙÚÜ]", "U"); passa = passa.replaceAll("[ûúùü]", "u"); passa = passa.replaceAll("Ç", "C"); passa = passa.replaceAll("ç", "c"); passa = passa.replaceAll("[ýÿ]", "y"); passa = passa.replaceAll("Ý", "Y"); passa = passa.replaceAll("ñ", "n"); passa = passa.replaceAll("Ñ", "N"); passa = passa.replaceAll("['<>\\|]", ""); return passa; } /** * retorna uma String quando o parametro recebido é uma string no formato * yyyy-MM-dd * * @param pString * @return String */ public String addBarras(String pString) { String dataRetorno = new String(); //substitui o '-' por '\' if (pString != null) { dataRetorno += pString.charAt(8); dataRetorno += pString.charAt(9); dataRetorno += '/'; dataRetorno += pString.charAt(5); dataRetorno += pString.charAt(6); dataRetorno += '/'; dataRetorno += pString.charAt(0); dataRetorno += pString.charAt(1); dataRetorno += pString.charAt(2); dataRetorno += pString.charAt(3); } return dataRetorno; } public String trocarTracos(String pString) { String retorno = new String(); if (pString != null) { for (int i = 0; i < pString.length(); i++) { if (pString.charAt(i) == '-') { retorno += '/'; } else { retorno += pString.charAt(i); } } } return retorno; } public String inverteBarra(String pString) { String retorno = new String(); if (pString != null) { for (int i = 0; i < pString.length(); i++) { if (pString.charAt(i) == '\\') { retorno += '/'; } else { retorno += pString.charAt(i); } } } return retorno; } /** * adiciona uma quantidade de dias a data * * @param pQteDias * @return Date */ public Date addDias(int pQteDias, Date pDate) { Calendar c = Calendar.getInstance(); c.setTime(pDate); c.add(Calendar.DATE, pQteDias); return c.getTime(); } /** * adicionar mês a data * * @param totalParcelas * @return */ public Date adddMes(Date dataAtual, int quantidadeMes) { Calendar c = Calendar.getInstance(); c.setTime(dataAtual); c.add(Calendar.MONTH, quantidadeMes); return c.getTime(); } public int diasEntreDatas(Date pDataInicio, Date pDataFim) { GregorianCalendar ini = new GregorianCalendar(); GregorianCalendar fim = new GregorianCalendar(); ini.setTime(pDataInicio); fim.setTime(pDataFim); long dt1 = ini.getTimeInMillis(); long dt2 = fim.getTimeInMillis(); return (int) (((dt2 - dt1) / 86400000) + 1); } /** *retornar hora tempo real * @return */ public String retornarHora(){ Date date = new Date(); SimpleDateFormat teste = new SimpleDateFormat("hh:mm:ss"); return teste.format(date); } /** * retornar data e hora tempo real * * @return */ public String retornarDataHora() { Date date = new Date(); SimpleDateFormat teste = new SimpleDateFormat("dd/MM/yyyy hh:mm"); return teste.format(date); } /** * Converte uma String para um objeto Date. Caso a String seja vazia ou * nula, retorna null - para facilitar em casos onde formulários podem ter * campos de datas vazios. * * @param data String no formato dd/MM/yyyy a ser formatada * @return Date Objeto Date ou null caso receba uma String vazia ou nula * @throws Exception Caso a String esteja no formato errado */ public java.sql.Date converterDataStringParaDate(String data) throws Exception { if (data == null || data.equals("")) { return null; } java.sql.Date date = null; try { DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); date = new java.sql.Date(((java.util.Date) formatter.parse(data)).getTime()); } catch (ParseException e) { throw e; } return date; } public String converteTimeEmDataHora(long pDataLong) { Date dt = new Date (pDataLong); DateFormat df = new SimpleDateFormat ("dd/MM/yyyy HH:mm:ss.SSS"); df.setTimeZone (TimeZone.getTimeZone ("BRT")); return df.format (dt); } /** * Converte data tipo string para o formato americano yyyy/MM/dd no tipo * date String para Date * * @param data * @return * @throws Exception */ public java.sql.Date converterDataStringParaDateUS(String data) throws Exception { if (data == null || data.equals("")) { return null; } java.sql.Date date = null; try { DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); date = new java.sql.Date(((java.util.Date) formatter.parse(data)).getTime()); } catch (ParseException e) { throw e; } return date; } /** * Converte data tipo date para o formato americano yyyy/MM/dd também tipo * date Date para Date * * @param pData * @return * @throws Exception */ public java.sql.Date converterDataParaDateUS(Date pData) throws Exception { SimpleDateFormat formatarDate = new SimpleDateFormat("yyyy/MM/dd"); String dataString = formatarDate.format(pData); if (pData == null || pData.equals("")) { return null; } java.sql.Date date = null; try { DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); date = new java.sql.Date(((java.util.Date) formatter.parse(dataString)).getTime()); } catch (ParseException e) { throw e; } return date; } /** * Recebe qualquer data em tipo date e retorna a data formatada no tipo * string ex. dd/MM/yyyy Date para String * * @param pData * @return String */ public String formatarData(Date pData) { SimpleDateFormat formatarDate = new SimpleDateFormat("dd/MM/yyyy"); return formatarDate.format(pData); } }
923ea6de51b6bef0eed8febf240868b719babdbb
10,805
java
Java
fhir/src/test/java/org/dhis2/fhir/adapter/fhir/metadata/repository/FhirClientResourceRepositoryRestDocsTest.java
opensrp/dhis2-fhir-adapter
e29d531f311d87089a32fbfaedde3456dbb6da6e
[ "BSD-3-Clause" ]
13
2018-12-31T21:08:46.000Z
2020-11-30T08:14:33.000Z
fhir/src/test/java/org/dhis2/fhir/adapter/fhir/metadata/repository/FhirClientResourceRepositoryRestDocsTest.java
opensrp/dhis2-fhir-adapter
e29d531f311d87089a32fbfaedde3456dbb6da6e
[ "BSD-3-Clause" ]
null
null
null
fhir/src/test/java/org/dhis2/fhir/adapter/fhir/metadata/repository/FhirClientResourceRepositoryRestDocsTest.java
opensrp/dhis2-fhir-adapter
e29d531f311d87089a32fbfaedde3456dbb6da6e
[ "BSD-3-Clause" ]
13
2018-10-25T12:03:18.000Z
2022-03-21T10:25:19.000Z
69.709677
239
0.725775
1,000,852
package org.dhis2.fhir.adapter.fhir.metadata.repository; /* * Copyright (c) 2004-2019, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.apache.commons.io.IOUtils; import org.dhis2.fhir.adapter.fhir.AbstractJpaRepositoryRestDocsTest; import org.dhis2.fhir.adapter.fhir.ConstrainedFields; import org.dhis2.fhir.adapter.fhir.metadata.model.FhirClient; import org.dhis2.fhir.adapter.fhir.metadata.model.FhirClientResource; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.http.MediaType; import org.springframework.restdocs.payload.JsonFieldType; import javax.annotation.Nonnull; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.UUID; import static org.hamcrest.Matchers.is; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; import static org.springframework.restdocs.payload.PayloadDocumentation.*; import static org.springframework.restdocs.snippet.Attributes.attributes; import static org.springframework.restdocs.snippet.Attributes.key; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Tests for {@link FhirClientResourceRepository}. * * @author volsch */ public class FhirClientResourceRepositoryRestDocsTest extends AbstractJpaRepositoryRestDocsTest { @Autowired private SystemRepository systemRepository; @Autowired private FhirClientRepository fhirClientRepository; @Autowired private FhirClientResourceRepository fhirClientResourceRepository; @Test public void createFhirClientResource() throws Exception { final String fhirClientId = loadFhirClient( "DEFAULT_SUBSCRIPTION" ).getId().toString(); final ConstrainedFields fields = new ConstrainedFields( FhirClientResource.class, constraintDescriptionResolver ); final String request = IOUtils.resourceToString( "/org/dhis2/fhir/adapter/fhir/metadata/repository/createFhirClientResource.json", StandardCharsets.UTF_8 ) .replace( "$fhirClientId", API_BASE_URI + "/fhirClients/" + fhirClientId ); final String location = docMockMvc.perform( post( "/api/fhirClientResources" ).header( AUTHORIZATION_HEADER_NAME, ADMINISTRATION_AUTHORIZATION_HEADER_VALUE ) .contentType( MediaType.APPLICATION_JSON ).content( request ) ) .andExpect( status().isCreated() ) .andExpect( header().exists( "Location" ) ) .andDo( documentationHandler.document( requestFields( attributes( key( "title" ).value( "Fields for script source creation" ) ), fields.withPath( "fhirClient" ).description( "The reference to the FHIR client to which this resource belongs to." ).type( JsonFieldType.STRING ), fields.withPath( "fhirResourceType" ).description( "The type of the subscribed FHIR resource." ).type( JsonFieldType.STRING ), fields.withPath( "description" ).description( "The detailed description of the purpose of the subscribed FHIR resource." ).type( JsonFieldType.STRING ).optional(), fields.withPath( "fhirCriteriaParameters" ).description( "The prefix that should be added to the codes when mapping them to DHIS2." ).type( JsonFieldType.STRING ).optional(), fields.withPath( "expOnly" ).description( "Specifies that this is only used for exporting FHIR resources. Subscription requests are not accepted." ) .type( JsonFieldType.BOOLEAN ).optional(), fields.withPath( "preferred" ).description( "Specifies if this resource definition is the preferred resource definition for the resource type when no resource definition can be determined otherwise." ) .type( JsonFieldType.BOOLEAN ).optional(), fields.withPath( "impTransformScript" ).description( "Link to the executable transformation script that transform incoming FHIR resources." ) .type( JsonFieldType.STRING ).optional() ) ) ).andReturn().getResponse().getHeader( "Location" ); mockMvc .perform( get( Objects.requireNonNull( location ) ).header( AUTHORIZATION_HEADER_NAME, ADMINISTRATION_AUTHORIZATION_HEADER_VALUE ) ) .andExpect( status().isOk() ) .andExpect( jsonPath( "lastUpdatedBy", is( "2h2maqu827d" ) ) ) .andExpect( jsonPath( "fhirResourceType", is( "IMMUNIZATION" ) ) ) .andExpect( jsonPath( "description", is( "Subscription for all immunizations." ) ) ) .andExpect( jsonPath( "fhirCriteriaParameters" ).doesNotExist() ) .andExpect( jsonPath( "fhirSubscriptionId" ).doesNotExist() ) .andExpect( jsonPath( "expOnly", is( false ) ) ) .andExpect( jsonPath( "_links.self.href", is( location ) ) ); } @Test public void readFhirClientResource() throws Exception { final ConstrainedFields fields = new ConstrainedFields( FhirClientResource.class, constraintDescriptionResolver ); final String fhirClientResourceId = loadFhirClientResource( "667bfa41-867c-4796-86b6-eb9f9ed4dc94" ).getId().toString(); docMockMvc.perform( get( "/api/fhirClientResources/{fhirClientResourceId}", fhirClientResourceId ).header( AUTHORIZATION_HEADER_NAME, ADMINISTRATION_AUTHORIZATION_HEADER_VALUE ) ) .andExpect( status().isOk() ) .andDo( documentationHandler.document( links( linkWithRel( "self" ).description( "Link to this resource itself." ), linkWithRel( "fhirClientResource" ).description( "Link to this resource itself." ), linkWithRel( "fhirClient" ).description( "The reference to the FHIR client to which this resource belongs to." ), linkWithRel( "impTransformScript" ).description( "Link to the executable transformation script that transform incoming FHIR resources." ).optional() ), responseFields( attributes( key( "title" ).value( "Fields for FHIR client resource reading" ) ), fields.withPath( "createdAt" ).description( "The timestamp when the resource has been created." ).type( JsonFieldType.STRING ), fields.withPath( "lastUpdatedBy" ).description( "The ID of the user that has updated the user the last time or null if the data has been imported to the database directly." ).type( JsonFieldType.STRING ).optional(), fields.withPath( "lastUpdatedAt" ).description( "The timestamp when the resource has been updated the last time." ).type( JsonFieldType.STRING ), fields.withPath( "fhirResourceType" ).description( "The type of the subscribed FHIR resource." ).type( JsonFieldType.STRING ), fields.withPath( "description" ).description( "The detailed description of the purpose of the subscribed FHIR resource." ).type( JsonFieldType.STRING ).optional(), fields.withPath( "fhirCriteriaParameters" ).description( "The prefix that should be added to the codes when mapping them to DHIS2." ).type( JsonFieldType.STRING ).optional(), fields.withPath( "expOnly" ).description( "Specifies that this is only used for exporting FHIR resources. Subscription requests are not accepted." ) .type( JsonFieldType.BOOLEAN ).optional(), fields.withPath( "virtual" ).description( "Specifies that there is no subscription for this FHIR resource since the FHIR service may not accept subscription for this resource type (just available as contained resources)." ) .type( JsonFieldType.BOOLEAN ).optional(), fields.withPath( "preferred" ).description( "Specifies if this resource definition is the preferred resource definition for the resource type when no resource definition can be determined otherwise." ) .type( JsonFieldType.BOOLEAN ).optional(), fields.withPath( "hirSubscriptionId" ).description( "The ID of the automatically created FHIR subscription on the FHIR service." ).type( JsonFieldType.STRING ).optional(), subsectionWithPath( "_links" ).description( "Links to other resources" ) ) ) ); } @Nonnull protected FhirClient loadFhirClient( @Nonnull String code ) { final FhirClient fhirClient = new FhirClient(); fhirClient.setCode( code ); return fhirClientRepository.findOne( Example.of( fhirClient, ExampleMatcher.matching().withIgnorePaths( "toleranceMillis", "logging", "verboseLogging", "enabled", "locked" ) ) ).orElseThrow( () -> new AssertionError( "FHIR client does not exist: " + code ) ); } @Nonnull protected FhirClientResource loadFhirClientResource( @Nonnull String id ) { return fhirClientResourceRepository.findById( UUID.fromString( id ) ).orElseThrow( () -> new AssertionError( "FHIR client resource does not exist: " + id ) ); } }
923ea6f2ef3e09d931327752f34fba3c656b64d0
27,153
java
Java
GTM data converter/src/Gtm/impl/PassengerConstraintImpl.java
UnionInternationalCheminsdeFer/OSDM-Converter
0935e2da609e7a158815fc3a593786d5b61e83ba
[ "Apache-2.0" ]
1
2021-10-05T15:07:06.000Z
2021-10-05T15:07:06.000Z
GTM data converter/src/Gtm/impl/PassengerConstraintImpl.java
UnionInternationalCheminsdeFer/OSDM-Converter
0935e2da609e7a158815fc3a593786d5b61e83ba
[ "Apache-2.0" ]
null
null
null
GTM data converter/src/Gtm/impl/PassengerConstraintImpl.java
UnionInternationalCheminsdeFer/OSDM-Converter
0935e2da609e7a158815fc3a593786d5b61e83ba
[ "Apache-2.0" ]
null
null
null
31.5
205
0.71517
1,000,853
/** */ package Gtm.impl; import Gtm.GtmPackage; import Gtm.IncludedFreePassengerLimit; import Gtm.PassengerCombinationConstraint; import Gtm.PassengerConstraint; import Gtm.Text; import Gtm.TravelerType; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Passenger Constraint</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link Gtm.impl.PassengerConstraintImpl#getId <em>Id</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getTravelerType <em>Traveler Type</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getText <em>Text</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getUpperAgeLimit <em>Upper Age Limit</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getLowerAgeLimit <em>Lower Age Limit</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getTravelAloneAgeLimit <em>Travel Alone Age Limit</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getReservationAgeLimit <em>Reservation Age Limit</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#isIsAncilliary <em>Is Ancilliary</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getPassengerWeight <em>Passenger Weight</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getMaxTotalPassengerWeight <em>Max Total Passenger Weight</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getMinTotalPassengerWeight <em>Min Total Passenger Weight</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getIncludedFreePassengers <em>Included Free Passengers</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getExcludedPassengerCombinations <em>Excluded Passenger Combinations</em>}</li> * <li>{@link Gtm.impl.PassengerConstraintImpl#getDataDescription <em>Data Description</em>}</li> * </ul> * * @generated */ public class PassengerConstraintImpl extends MinimalEObjectImpl.Container implements PassengerConstraint { /** * The default value of the '{@link #getId() <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getId() * @generated * @ordered */ protected static final String ID_EDEFAULT = null; /** * The cached value of the '{@link #getId() <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getId() * @generated * @ordered */ protected String id = ID_EDEFAULT; /** * The default value of the '{@link #getTravelerType() <em>Traveler Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTravelerType() * @generated * @ordered */ protected static final TravelerType TRAVELER_TYPE_EDEFAULT = TravelerType.ADULT; /** * The cached value of the '{@link #getTravelerType() <em>Traveler Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTravelerType() * @generated * @ordered */ protected TravelerType travelerType = TRAVELER_TYPE_EDEFAULT; /** * The cached value of the '{@link #getText() <em>Text</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getText() * @generated * @ordered */ protected Text text; /** * The default value of the '{@link #getUpperAgeLimit() <em>Upper Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUpperAgeLimit() * @generated * @ordered */ protected static final int UPPER_AGE_LIMIT_EDEFAULT = 0; /** * The cached value of the '{@link #getUpperAgeLimit() <em>Upper Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUpperAgeLimit() * @generated * @ordered */ protected int upperAgeLimit = UPPER_AGE_LIMIT_EDEFAULT; /** * The default value of the '{@link #getLowerAgeLimit() <em>Lower Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLowerAgeLimit() * @generated * @ordered */ protected static final int LOWER_AGE_LIMIT_EDEFAULT = 0; /** * The cached value of the '{@link #getLowerAgeLimit() <em>Lower Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLowerAgeLimit() * @generated * @ordered */ protected int lowerAgeLimit = LOWER_AGE_LIMIT_EDEFAULT; /** * The default value of the '{@link #getTravelAloneAgeLimit() <em>Travel Alone Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTravelAloneAgeLimit() * @generated * @ordered */ protected static final int TRAVEL_ALONE_AGE_LIMIT_EDEFAULT = 0; /** * The cached value of the '{@link #getTravelAloneAgeLimit() <em>Travel Alone Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTravelAloneAgeLimit() * @generated * @ordered */ protected int travelAloneAgeLimit = TRAVEL_ALONE_AGE_LIMIT_EDEFAULT; /** * The default value of the '{@link #getReservationAgeLimit() <em>Reservation Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReservationAgeLimit() * @generated * @ordered */ protected static final int RESERVATION_AGE_LIMIT_EDEFAULT = 0; /** * The cached value of the '{@link #getReservationAgeLimit() <em>Reservation Age Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReservationAgeLimit() * @generated * @ordered */ protected int reservationAgeLimit = RESERVATION_AGE_LIMIT_EDEFAULT; /** * The default value of the '{@link #isIsAncilliary() <em>Is Ancilliary</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isIsAncilliary() * @generated * @ordered */ protected static final boolean IS_ANCILLIARY_EDEFAULT = false; /** * The cached value of the '{@link #isIsAncilliary() <em>Is Ancilliary</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isIsAncilliary() * @generated * @ordered */ protected boolean isAncilliary = IS_ANCILLIARY_EDEFAULT; /** * The default value of the '{@link #getPassengerWeight() <em>Passenger Weight</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPassengerWeight() * @generated * @ordered */ protected static final float PASSENGER_WEIGHT_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getPassengerWeight() <em>Passenger Weight</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPassengerWeight() * @generated * @ordered */ protected float passengerWeight = PASSENGER_WEIGHT_EDEFAULT; /** * The default value of the '{@link #getMaxTotalPassengerWeight() <em>Max Total Passenger Weight</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaxTotalPassengerWeight() * @generated * @ordered */ protected static final float MAX_TOTAL_PASSENGER_WEIGHT_EDEFAULT = 999.0F; /** * The cached value of the '{@link #getMaxTotalPassengerWeight() <em>Max Total Passenger Weight</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaxTotalPassengerWeight() * @generated * @ordered */ protected float maxTotalPassengerWeight = MAX_TOTAL_PASSENGER_WEIGHT_EDEFAULT; /** * The default value of the '{@link #getMinTotalPassengerWeight() <em>Min Total Passenger Weight</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMinTotalPassengerWeight() * @generated * @ordered */ protected static final float MIN_TOTAL_PASSENGER_WEIGHT_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getMinTotalPassengerWeight() <em>Min Total Passenger Weight</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMinTotalPassengerWeight() * @generated * @ordered */ protected float minTotalPassengerWeight = MIN_TOTAL_PASSENGER_WEIGHT_EDEFAULT; /** * The cached value of the '{@link #getIncludedFreePassengers() <em>Included Free Passengers</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getIncludedFreePassengers() * @generated * @ordered */ protected EList<IncludedFreePassengerLimit> includedFreePassengers; /** * The cached value of the '{@link #getExcludedPassengerCombinations() <em>Excluded Passenger Combinations</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExcludedPassengerCombinations() * @generated * @ordered */ protected EList<PassengerCombinationConstraint> excludedPassengerCombinations; /** * The default value of the '{@link #getDataDescription() <em>Data Description</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDataDescription() * @generated * @ordered */ protected static final String DATA_DESCRIPTION_EDEFAULT = null; /** * The cached value of the '{@link #getDataDescription() <em>Data Description</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDataDescription() * @generated * @ordered */ protected String dataDescription = DATA_DESCRIPTION_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PassengerConstraintImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return GtmPackage.Literals.PASSENGER_CONSTRAINT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getId() { return id; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setId(String newId) { String oldId = id; id = newId; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__ID, oldId, id)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TravelerType getTravelerType() { return travelerType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTravelerType(TravelerType newTravelerType) { TravelerType oldTravelerType = travelerType; travelerType = newTravelerType == null ? TRAVELER_TYPE_EDEFAULT : newTravelerType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__TRAVELER_TYPE, oldTravelerType, travelerType)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Text getText() { if (text != null && text.eIsProxy()) { InternalEObject oldText = (InternalEObject)text; text = (Text)eResolveProxy(oldText); if (text != oldText) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, GtmPackage.PASSENGER_CONSTRAINT__TEXT, oldText, text)); } } return text; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Text basicGetText() { return text; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setText(Text newText) { Text oldText = text; text = newText; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__TEXT, oldText, text)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getUpperAgeLimit() { return upperAgeLimit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUpperAgeLimit(int newUpperAgeLimit) { int oldUpperAgeLimit = upperAgeLimit; upperAgeLimit = newUpperAgeLimit; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__UPPER_AGE_LIMIT, oldUpperAgeLimit, upperAgeLimit)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getLowerAgeLimit() { return lowerAgeLimit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLowerAgeLimit(int newLowerAgeLimit) { int oldLowerAgeLimit = lowerAgeLimit; lowerAgeLimit = newLowerAgeLimit; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__LOWER_AGE_LIMIT, oldLowerAgeLimit, lowerAgeLimit)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getTravelAloneAgeLimit() { return travelAloneAgeLimit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTravelAloneAgeLimit(int newTravelAloneAgeLimit) { int oldTravelAloneAgeLimit = travelAloneAgeLimit; travelAloneAgeLimit = newTravelAloneAgeLimit; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__TRAVEL_ALONE_AGE_LIMIT, oldTravelAloneAgeLimit, travelAloneAgeLimit)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getReservationAgeLimit() { return reservationAgeLimit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setReservationAgeLimit(int newReservationAgeLimit) { int oldReservationAgeLimit = reservationAgeLimit; reservationAgeLimit = newReservationAgeLimit; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__RESERVATION_AGE_LIMIT, oldReservationAgeLimit, reservationAgeLimit)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isIsAncilliary() { return isAncilliary; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setIsAncilliary(boolean newIsAncilliary) { boolean oldIsAncilliary = isAncilliary; isAncilliary = newIsAncilliary; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__IS_ANCILLIARY, oldIsAncilliary, isAncilliary)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getPassengerWeight() { return passengerWeight; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPassengerWeight(float newPassengerWeight) { float oldPassengerWeight = passengerWeight; passengerWeight = newPassengerWeight; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__PASSENGER_WEIGHT, oldPassengerWeight, passengerWeight)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getMaxTotalPassengerWeight() { return maxTotalPassengerWeight; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMaxTotalPassengerWeight(float newMaxTotalPassengerWeight) { float oldMaxTotalPassengerWeight = maxTotalPassengerWeight; maxTotalPassengerWeight = newMaxTotalPassengerWeight; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__MAX_TOTAL_PASSENGER_WEIGHT, oldMaxTotalPassengerWeight, maxTotalPassengerWeight)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getMinTotalPassengerWeight() { return minTotalPassengerWeight; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMinTotalPassengerWeight(float newMinTotalPassengerWeight) { float oldMinTotalPassengerWeight = minTotalPassengerWeight; minTotalPassengerWeight = newMinTotalPassengerWeight; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__MIN_TOTAL_PASSENGER_WEIGHT, oldMinTotalPassengerWeight, minTotalPassengerWeight)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<IncludedFreePassengerLimit> getIncludedFreePassengers() { if (includedFreePassengers == null) { includedFreePassengers = new EObjectContainmentEList<IncludedFreePassengerLimit>(IncludedFreePassengerLimit.class, this, GtmPackage.PASSENGER_CONSTRAINT__INCLUDED_FREE_PASSENGERS); } return includedFreePassengers; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<PassengerCombinationConstraint> getExcludedPassengerCombinations() { if (excludedPassengerCombinations == null) { excludedPassengerCombinations = new EObjectContainmentEList<PassengerCombinationConstraint>(PassengerCombinationConstraint.class, this, GtmPackage.PASSENGER_CONSTRAINT__EXCLUDED_PASSENGER_COMBINATIONS); } return excludedPassengerCombinations; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getDataDescription() { return dataDescription; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDataDescription(String newDataDescription) { String oldDataDescription = dataDescription; dataDescription = newDataDescription; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GtmPackage.PASSENGER_CONSTRAINT__DATA_DESCRIPTION, oldDataDescription, dataDescription)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case GtmPackage.PASSENGER_CONSTRAINT__INCLUDED_FREE_PASSENGERS: return ((InternalEList<?>)getIncludedFreePassengers()).basicRemove(otherEnd, msgs); case GtmPackage.PASSENGER_CONSTRAINT__EXCLUDED_PASSENGER_COMBINATIONS: return ((InternalEList<?>)getExcludedPassengerCombinations()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case GtmPackage.PASSENGER_CONSTRAINT__ID: return getId(); case GtmPackage.PASSENGER_CONSTRAINT__TRAVELER_TYPE: return getTravelerType(); case GtmPackage.PASSENGER_CONSTRAINT__TEXT: if (resolve) return getText(); return basicGetText(); case GtmPackage.PASSENGER_CONSTRAINT__UPPER_AGE_LIMIT: return getUpperAgeLimit(); case GtmPackage.PASSENGER_CONSTRAINT__LOWER_AGE_LIMIT: return getLowerAgeLimit(); case GtmPackage.PASSENGER_CONSTRAINT__TRAVEL_ALONE_AGE_LIMIT: return getTravelAloneAgeLimit(); case GtmPackage.PASSENGER_CONSTRAINT__RESERVATION_AGE_LIMIT: return getReservationAgeLimit(); case GtmPackage.PASSENGER_CONSTRAINT__IS_ANCILLIARY: return isIsAncilliary(); case GtmPackage.PASSENGER_CONSTRAINT__PASSENGER_WEIGHT: return getPassengerWeight(); case GtmPackage.PASSENGER_CONSTRAINT__MAX_TOTAL_PASSENGER_WEIGHT: return getMaxTotalPassengerWeight(); case GtmPackage.PASSENGER_CONSTRAINT__MIN_TOTAL_PASSENGER_WEIGHT: return getMinTotalPassengerWeight(); case GtmPackage.PASSENGER_CONSTRAINT__INCLUDED_FREE_PASSENGERS: return getIncludedFreePassengers(); case GtmPackage.PASSENGER_CONSTRAINT__EXCLUDED_PASSENGER_COMBINATIONS: return getExcludedPassengerCombinations(); case GtmPackage.PASSENGER_CONSTRAINT__DATA_DESCRIPTION: return getDataDescription(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case GtmPackage.PASSENGER_CONSTRAINT__ID: setId((String)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__TRAVELER_TYPE: setTravelerType((TravelerType)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__TEXT: setText((Text)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__UPPER_AGE_LIMIT: setUpperAgeLimit((Integer)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__LOWER_AGE_LIMIT: setLowerAgeLimit((Integer)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__TRAVEL_ALONE_AGE_LIMIT: setTravelAloneAgeLimit((Integer)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__RESERVATION_AGE_LIMIT: setReservationAgeLimit((Integer)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__IS_ANCILLIARY: setIsAncilliary((Boolean)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__PASSENGER_WEIGHT: setPassengerWeight((Float)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__MAX_TOTAL_PASSENGER_WEIGHT: setMaxTotalPassengerWeight((Float)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__MIN_TOTAL_PASSENGER_WEIGHT: setMinTotalPassengerWeight((Float)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__INCLUDED_FREE_PASSENGERS: getIncludedFreePassengers().clear(); getIncludedFreePassengers().addAll((Collection<? extends IncludedFreePassengerLimit>)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__EXCLUDED_PASSENGER_COMBINATIONS: getExcludedPassengerCombinations().clear(); getExcludedPassengerCombinations().addAll((Collection<? extends PassengerCombinationConstraint>)newValue); return; case GtmPackage.PASSENGER_CONSTRAINT__DATA_DESCRIPTION: setDataDescription((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case GtmPackage.PASSENGER_CONSTRAINT__ID: setId(ID_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__TRAVELER_TYPE: setTravelerType(TRAVELER_TYPE_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__TEXT: setText((Text)null); return; case GtmPackage.PASSENGER_CONSTRAINT__UPPER_AGE_LIMIT: setUpperAgeLimit(UPPER_AGE_LIMIT_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__LOWER_AGE_LIMIT: setLowerAgeLimit(LOWER_AGE_LIMIT_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__TRAVEL_ALONE_AGE_LIMIT: setTravelAloneAgeLimit(TRAVEL_ALONE_AGE_LIMIT_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__RESERVATION_AGE_LIMIT: setReservationAgeLimit(RESERVATION_AGE_LIMIT_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__IS_ANCILLIARY: setIsAncilliary(IS_ANCILLIARY_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__PASSENGER_WEIGHT: setPassengerWeight(PASSENGER_WEIGHT_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__MAX_TOTAL_PASSENGER_WEIGHT: setMaxTotalPassengerWeight(MAX_TOTAL_PASSENGER_WEIGHT_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__MIN_TOTAL_PASSENGER_WEIGHT: setMinTotalPassengerWeight(MIN_TOTAL_PASSENGER_WEIGHT_EDEFAULT); return; case GtmPackage.PASSENGER_CONSTRAINT__INCLUDED_FREE_PASSENGERS: getIncludedFreePassengers().clear(); return; case GtmPackage.PASSENGER_CONSTRAINT__EXCLUDED_PASSENGER_COMBINATIONS: getExcludedPassengerCombinations().clear(); return; case GtmPackage.PASSENGER_CONSTRAINT__DATA_DESCRIPTION: setDataDescription(DATA_DESCRIPTION_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case GtmPackage.PASSENGER_CONSTRAINT__ID: return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id); case GtmPackage.PASSENGER_CONSTRAINT__TRAVELER_TYPE: return travelerType != TRAVELER_TYPE_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__TEXT: return text != null; case GtmPackage.PASSENGER_CONSTRAINT__UPPER_AGE_LIMIT: return upperAgeLimit != UPPER_AGE_LIMIT_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__LOWER_AGE_LIMIT: return lowerAgeLimit != LOWER_AGE_LIMIT_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__TRAVEL_ALONE_AGE_LIMIT: return travelAloneAgeLimit != TRAVEL_ALONE_AGE_LIMIT_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__RESERVATION_AGE_LIMIT: return reservationAgeLimit != RESERVATION_AGE_LIMIT_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__IS_ANCILLIARY: return isAncilliary != IS_ANCILLIARY_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__PASSENGER_WEIGHT: return passengerWeight != PASSENGER_WEIGHT_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__MAX_TOTAL_PASSENGER_WEIGHT: return maxTotalPassengerWeight != MAX_TOTAL_PASSENGER_WEIGHT_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__MIN_TOTAL_PASSENGER_WEIGHT: return minTotalPassengerWeight != MIN_TOTAL_PASSENGER_WEIGHT_EDEFAULT; case GtmPackage.PASSENGER_CONSTRAINT__INCLUDED_FREE_PASSENGERS: return includedFreePassengers != null && !includedFreePassengers.isEmpty(); case GtmPackage.PASSENGER_CONSTRAINT__EXCLUDED_PASSENGER_COMBINATIONS: return excludedPassengerCombinations != null && !excludedPassengerCombinations.isEmpty(); case GtmPackage.PASSENGER_CONSTRAINT__DATA_DESCRIPTION: return DATA_DESCRIPTION_EDEFAULT == null ? dataDescription != null : !DATA_DESCRIPTION_EDEFAULT.equals(dataDescription); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (id: "); result.append(id); result.append(", travelerType: "); result.append(travelerType); result.append(", upperAgeLimit: "); result.append(upperAgeLimit); result.append(", lowerAgeLimit: "); result.append(lowerAgeLimit); result.append(", travelAloneAgeLimit: "); result.append(travelAloneAgeLimit); result.append(", reservationAgeLimit: "); result.append(reservationAgeLimit); result.append(", isAncilliary: "); result.append(isAncilliary); result.append(", passengerWeight: "); result.append(passengerWeight); result.append(", maxTotalPassengerWeight: "); result.append(maxTotalPassengerWeight); result.append(", minTotalPassengerWeight: "); result.append(minTotalPassengerWeight); result.append(", dataDescription: "); result.append(dataDescription); result.append(')'); return result.toString(); } } //PassengerConstraintImpl
923ea70a1f1926ae0ac3a00407eb42344b25011c
4,897
java
Java
dagger2/producers/src/test/java/dagger/producers/internal/AbstractProducerTest.java
OpenSource-Infinix/android_external_crcalc
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
1
2020-09-08T11:20:56.000Z
2020-09-08T11:20:56.000Z
dagger2/producers/src/test/java/dagger/producers/internal/AbstractProducerTest.java
OpenSource-Infinix/android_external_crcalc
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
null
null
null
dagger2/producers/src/test/java/dagger/producers/internal/AbstractProducerTest.java
OpenSource-Infinix/android_external_crcalc
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
null
null
null
33.772414
98
0.734736
1,000,854
/* * Copyright (C) 2014 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.producers.internal; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import dagger.producers.Producer; import dagger.producers.monitoring.ProducerMonitor; import dagger.producers.monitoring.ProducerToken; import dagger.producers.monitoring.ProductionComponentMonitor; import java.util.concurrent.ExecutionException; import javax.inject.Provider; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; /** * Tests {@link AbstractProducer}. */ @RunWith(JUnit4.class) public class AbstractProducerTest { @Mock private ProductionComponentMonitor componentMonitor; private ProducerMonitor monitor; private Provider<ProductionComponentMonitor> componentMonitorProvider; @Before public void initMocks() { MockitoAnnotations.initMocks(this); monitor = Mockito.mock(ProducerMonitor.class, Mockito.CALLS_REAL_METHODS); when(componentMonitor.producerMonitorFor(any(ProducerToken.class))).thenReturn(monitor); componentMonitorProvider = new Provider<ProductionComponentMonitor>() { @Override public ProductionComponentMonitor get() { return componentMonitor; } }; } @Test public void get_nullPointerException() { Producer<Object> producer = new DelegateProducer<>(componentMonitorProvider, null); try { producer.get(); fail(); } catch (NullPointerException expected) { } } @Test public void get() throws Exception { Producer<Integer> producer = new AbstractProducer<Integer>(componentMonitorProvider, null) { int i = 0; @Override public ListenableFuture<Integer> compute(ProducerMonitor unusedMonitor) { return Futures.immediateFuture(i++); } }; assertThat(producer.get().get()).isEqualTo(0); assertThat(producer.get().get()).isEqualTo(0); assertThat(producer.get().get()).isEqualTo(0); } @Test public void monitor_success() throws Exception { SettableFuture<Integer> delegateFuture = SettableFuture.create(); Producer<Integer> producer = new DelegateProducer<>(componentMonitorProvider, delegateFuture); ListenableFuture<Integer> future = producer.get(); assertThat(future.isDone()).isFalse(); verify(monitor).addCallbackTo(any(ListenableFuture.class)); delegateFuture.set(-42); assertThat(future.get()).isEqualTo(-42); verify(monitor).succeeded(-42); verifyNoMoreInteractions(monitor); } @Test public void monitor_failure() throws Exception { SettableFuture<Integer> delegateFuture = SettableFuture.create(); Producer<Integer> producer = new DelegateProducer<>(componentMonitorProvider, delegateFuture); ListenableFuture<Integer> future = producer.get(); assertThat(future.isDone()).isFalse(); verify(monitor).addCallbackTo(any(ListenableFuture.class)); Throwable t = new RuntimeException("monkey"); delegateFuture.setException(t); try { future.get(); fail(); } catch (ExecutionException e) { assertThat(e.getCause()).isSameAs(t); } verify(monitor).failed(t); verifyNoMoreInteractions(monitor); } @Test(expected = NullPointerException.class) public void monitor_null() throws Exception { new DelegateProducer<>(null, Futures.immediateFuture(42)); } static final class DelegateProducer<T> extends AbstractProducer<T> { private final ListenableFuture<T> delegate; DelegateProducer( Provider<ProductionComponentMonitor> componentMonitorProvider, ListenableFuture<T> delegate) { super(componentMonitorProvider, null); this.delegate = delegate; } @Override public ListenableFuture<T> compute(ProducerMonitor unusedMonitor) { return delegate; } } }
923ea741c690db513ee2fb0ad1e97d981f597724
7,600
java
Java
aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/RemoveTagsRequest.java
iterate-ch/aws-sdk-java
ef20f951d59a5412e0b483729f81722e4ad2bf53
[ "Apache-2.0" ]
1
2019-02-08T15:23:02.000Z
2019-02-08T15:23:02.000Z
aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/RemoveTagsRequest.java
iterate-ch/aws-sdk-java
ef20f951d59a5412e0b483729f81722e4ad2bf53
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/RemoveTagsRequest.java
iterate-ch/aws-sdk-java
ef20f951d59a5412e0b483729f81722e4ad2bf53
[ "Apache-2.0" ]
1
2022-03-22T05:35:12.000Z
2022-03-22T05:35:12.000Z
31.799163
126
0.609868
1,000,855
/* * Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.elasticloadbalancing.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Contains the parameters for RemoveTags. * </p> */ public class RemoveTagsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the load balancer. You can specify a maximum of one load balancer name. * </p> */ private com.amazonaws.internal.SdkInternalList<String> loadBalancerNames; /** * <p> * The list of tag keys to remove. * </p> */ private com.amazonaws.internal.SdkInternalList<TagKeyOnly> tags; /** * <p> * The name of the load balancer. You can specify a maximum of one load balancer name. * </p> * * @return The name of the load balancer. You can specify a maximum of one load balancer name. */ public java.util.List<String> getLoadBalancerNames() { if (loadBalancerNames == null) { loadBalancerNames = new com.amazonaws.internal.SdkInternalList<String>(); } return loadBalancerNames; } /** * <p> * The name of the load balancer. You can specify a maximum of one load balancer name. * </p> * * @param loadBalancerNames * The name of the load balancer. You can specify a maximum of one load balancer name. */ public void setLoadBalancerNames(java.util.Collection<String> loadBalancerNames) { if (loadBalancerNames == null) { this.loadBalancerNames = null; return; } this.loadBalancerNames = new com.amazonaws.internal.SdkInternalList<String>(loadBalancerNames); } /** * <p> * The name of the load balancer. You can specify a maximum of one load balancer name. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setLoadBalancerNames(java.util.Collection)} or {@link #withLoadBalancerNames(java.util.Collection)} if * you want to override the existing values. * </p> * * @param loadBalancerNames * The name of the load balancer. You can specify a maximum of one load balancer name. * @return Returns a reference to this object so that method calls can be chained together. */ public RemoveTagsRequest withLoadBalancerNames(String... loadBalancerNames) { if (this.loadBalancerNames == null) { setLoadBalancerNames(new com.amazonaws.internal.SdkInternalList<String>(loadBalancerNames.length)); } for (String ele : loadBalancerNames) { this.loadBalancerNames.add(ele); } return this; } /** * <p> * The name of the load balancer. You can specify a maximum of one load balancer name. * </p> * * @param loadBalancerNames * The name of the load balancer. You can specify a maximum of one load balancer name. * @return Returns a reference to this object so that method calls can be chained together. */ public RemoveTagsRequest withLoadBalancerNames(java.util.Collection<String> loadBalancerNames) { setLoadBalancerNames(loadBalancerNames); return this; } /** * <p> * The list of tag keys to remove. * </p> * * @return The list of tag keys to remove. */ public java.util.List<TagKeyOnly> getTags() { if (tags == null) { tags = new com.amazonaws.internal.SdkInternalList<TagKeyOnly>(); } return tags; } /** * <p> * The list of tag keys to remove. * </p> * * @param tags * The list of tag keys to remove. */ public void setTags(java.util.Collection<TagKeyOnly> tags) { if (tags == null) { this.tags = null; return; } this.tags = new com.amazonaws.internal.SdkInternalList<TagKeyOnly>(tags); } /** * <p> * The list of tag keys to remove. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * The list of tag keys to remove. * @return Returns a reference to this object so that method calls can be chained together. */ public RemoveTagsRequest withTags(TagKeyOnly... tags) { if (this.tags == null) { setTags(new com.amazonaws.internal.SdkInternalList<TagKeyOnly>(tags.length)); } for (TagKeyOnly ele : tags) { this.tags.add(ele); } return this; } /** * <p> * The list of tag keys to remove. * </p> * * @param tags * The list of tag keys to remove. * @return Returns a reference to this object so that method calls can be chained together. */ public RemoveTagsRequest withTags(java.util.Collection<TagKeyOnly> tags) { setTags(tags); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getLoadBalancerNames() != null) sb.append("LoadBalancerNames: " + getLoadBalancerNames() + ","); if (getTags() != null) sb.append("Tags: " + getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RemoveTagsRequest == false) return false; RemoveTagsRequest other = (RemoveTagsRequest) obj; if (other.getLoadBalancerNames() == null ^ this.getLoadBalancerNames() == null) return false; if (other.getLoadBalancerNames() != null && other.getLoadBalancerNames().equals(this.getLoadBalancerNames()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getLoadBalancerNames() == null) ? 0 : getLoadBalancerNames().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public RemoveTagsRequest clone() { return (RemoveTagsRequest) super.clone(); } }
923ea7e8694e39762dccffe26abf79faa2c6796b
317
java
Java
backend/rdf4j/src/main/java/org/dotwebstack/framework/backend/rdf4j/model/Rdf4jObjectField.java
dotwebstack/dotwebstack-framework
1d324ee085bdfd5be7bf7a8d58959cb7b0349d55
[ "MIT" ]
15
2017-09-14T13:07:01.000Z
2021-12-17T08:30:52.000Z
backend/rdf4j/src/main/java/org/dotwebstack/framework/backend/rdf4j/model/Rdf4jObjectField.java
dotwebstack/dotwebstack-framework
1d324ee085bdfd5be7bf7a8d58959cb7b0349d55
[ "MIT" ]
381
2017-08-16T09:58:42.000Z
2022-03-31T15:17:30.000Z
backend/rdf4j/src/main/java/org/dotwebstack/framework/backend/rdf4j/model/Rdf4jObjectField.java
dotwebstack/dotwebstack-framework
1d324ee085bdfd5be7bf7a8d58959cb7b0349d55
[ "MIT" ]
10
2018-01-23T10:30:47.000Z
2021-06-17T14:21:18.000Z
24.384615
64
0.829653
1,000,856
package org.dotwebstack.framework.backend.rdf4j.model; import lombok.Data; import lombok.EqualsAndHashCode; import org.dotwebstack.framework.core.model.AbstractObjectField; @Data @EqualsAndHashCode(callSuper = true) public class Rdf4jObjectField extends AbstractObjectField { private boolean resource = false; }
923ea82da520e3b5562c988512fdf6770c691311
1,017
java
Java
integration-tests/messaging/common/src/main/java/org/apache/camel/quarkus/component/messaging/it/util/resolver/JmsMessageResolver.java
DenisIstomin/camel-quarkus
c8c39c0a3dea03a3724b5eb1c13136e05ce66e68
[ "Apache-2.0" ]
179
2019-06-21T09:00:21.000Z
2022-03-30T06:00:47.000Z
integration-tests/messaging/common/src/main/java/org/apache/camel/quarkus/component/messaging/it/util/resolver/JmsMessageResolver.java
DenisIstomin/camel-quarkus
c8c39c0a3dea03a3724b5eb1c13136e05ce66e68
[ "Apache-2.0" ]
2,658
2019-06-24T10:21:30.000Z
2022-03-31T16:51:12.000Z
integration-tests/messaging/common/src/main/java/org/apache/camel/quarkus/component/messaging/it/util/resolver/JmsMessageResolver.java
DenisIstomin/camel-quarkus
c8c39c0a3dea03a3724b5eb1c13136e05ce66e68
[ "Apache-2.0" ]
143
2019-06-21T09:41:07.000Z
2022-03-29T16:27:24.000Z
39.115385
75
0.765978
1,000,857
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.quarkus.component.messaging.it.util.resolver; import javax.jms.Message; import org.apache.camel.Exchange; public interface JmsMessageResolver { Message resolve(Exchange exchange); }
923ea847d5020813357278e2f2960bbb2412efcc
9,663
java
Java
portalpack.servers.websynergy/src/main/java/org/netbeans/modules/portalpack/servers/websynergy/config/LiferayPortletXMLListener.java
timboudreau/netbeans-contrib
e414495e8585df9911392d7e3b190153759ff6d3
[ "Apache-2.0" ]
2
2018-07-19T08:40:29.000Z
2019-12-07T19:37:03.000Z
portalpack.servers.websynergy/src/main/java/org/netbeans/modules/portalpack/servers/websynergy/config/LiferayPortletXMLListener.java
timboudreau/netbeans-contrib
e414495e8585df9911392d7e3b190153759ff6d3
[ "Apache-2.0" ]
4
2021-02-03T19:27:41.000Z
2021-08-02T17:04:13.000Z
portalpack.servers.websynergy/src/main/java/org/netbeans/modules/portalpack/servers/websynergy/config/LiferayPortletXMLListener.java
timboudreau/netbeans-contrib
e414495e8585df9911392d7e3b190153759ff6d3
[ "Apache-2.0" ]
2
2020-10-03T14:44:58.000Z
2022-01-13T22:03:24.000Z
37.746094
123
0.602608
1,000,858
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.netbeans.modules.portalpack.servers.websynergy.config; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectUtils; import org.netbeans.modules.portalpack.portlets.genericportlets.core.AppContext; import org.netbeans.modules.portalpack.portlets.genericportlets.core.PortletContext; import org.netbeans.modules.portalpack.portlets.genericportlets.core.listeners.PortletXMLChangeListener; import org.netbeans.modules.portalpack.portlets.genericportlets.core.util.CoreUtil; import org.netbeans.modules.portalpack.portlets.genericportlets.core.util.NetbeansUtil; import org.netbeans.modules.portalpack.servers.websynergy.common.WebSpacePropertiesUtil; import org.netbeans.modules.portalpack.servers.websynergy.dd.ld.impl400.Category; import org.netbeans.modules.portalpack.servers.websynergy.dd.ld.impl400.Display; import org.netbeans.modules.portalpack.servers.websynergy.dd.lp.impl440.LiferayPortletApp; import org.netbeans.modules.portalpack.servers.websynergy.dd.lp.impl440.Portlet; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.NbBundle; /** * * @author satyaranjan */ public class LiferayPortletXMLListener implements PortletXMLChangeListener { private static Logger logger = Logger.getLogger(CoreUtil.CORE_LOGGER); public static String SPRING_PORTLET = "org.springframework.web.portlet.DispatcherPortlet"; public static String JSF_PORTLET = "com.sun.faces.portlet.FacesPortlet"; public static String RUBY_PORTLET = "com.liferay.util.bridges.ruby.RubyPortlet"; public void addPortlet(PortletContext portletContext, AppContext appContext, String webInfDir) { addPortletToLifeRayPortletFile(portletContext, appContext, webInfDir); addPortletToLifeRayDisplayFile(portletContext, appContext, webInfDir); Properties pluginPackageProperties = getPluginPackageProperties(webInfDir); boolean addJars = addDependencyJars(pluginPackageProperties, portletContext, webInfDir); boolean addProps = addPluginPackageProperties(pluginPackageProperties, portletContext, webInfDir); if (addJars || addProps) { storePluginPackageProperties(pluginPackageProperties, webInfDir); } FileObject webInfFO = FileUtil.toFileObject(new File(webInfDir)); if(webInfFO != null) { Project prj = FileOwnerQuery.getOwner(webInfFO); if(prj != null) { //check if Liferay/WebSpace boolean isLiferay = WebSpacePropertiesUtil.isWebSynergyServer(prj); if(isLiferay) { String prjName = ProjectUtils.getInformation(prj).getName(); if(prjName != null && prjName.endsWith("-hook")) { NotifyDescriptor nd = new NotifyDescriptor.Message( NbBundle.getMessage(LiferayPortletXMLListener.class, "MSG_PORTLET_NOT_ALLOWED_IN_HOOK_PROJECT"),NotifyDescriptor.WARNING_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } } } } private void addPortletToLifeRayDisplayFile(PortletContext portletContext, AppContext appContext, String webInfDir) { File liferayDisplayXml = new File(webInfDir + File.separator + "liferay-display.xml"); //NOI18N if (!liferayDisplayXml.exists()) { return; } try { Display display = Display.createGraph(liferayDisplayXml); Category[] cats = display.getCategory(); Category cat = null; if (cats.length == 0) { cat = display.newCategory(); cat.setAttributeValue("name", LiferayModuleConfiguration.PORTLET_CATEGORY); //NOI18N display.setCategory(new Category[]{cat}); } else { cat = cats[0]; } cat.addPortlet(portletContext.getPortletName()); int index = cat.getPortlet().length; index--; if (index >= 0) { cat.setPortletId(index, portletContext.getPortletName()); } NetbeansUtil.saveBean(display, liferayDisplayXml); } catch (Exception e) { logger.info(e.getMessage()); //do nothing } } private void addPortletToLifeRayPortletFile(PortletContext portletContext, AppContext appContext, String webInfDir) { File liferayPortletXml = new File(webInfDir + File.separator + "liferay-portlet.xml"); if (!liferayPortletXml.exists()) { return; } try { LiferayPortletApp lpApp = LiferayPortletApp.createGraph(liferayPortletXml); String portletName = portletContext.getPortletName(); Portlet p = lpApp.newPortlet(); p.setPortletName(portletName); p.setInstanceable("true"); lpApp.addPortlet(p); NetbeansUtil.saveBean(lpApp, liferayPortletXml); } catch (IOException ex) { logger.severe(ex.getMessage()); } } private boolean addDependencyJars(Properties pluginPackageProp, PortletContext pc, String webInfDir) { String className = pc.getPortletClass(); if (className != null && className.equals(SPRING_PORTLET)) { try { String depJar = pluginPackageProp.getProperty("portal.dependency.jars"); if (depJar == null || depJar.trim().length() == 0) { pluginPackageProp.setProperty("portal.dependency.jars", "commons-fileupload.jar"); } else { if (depJar.indexOf("commons-fileupload.jar") != -1) { return false; } if (depJar.endsWith(",")) { depJar += "commons-fileupload.jar"; } else { depJar += "," + "commons-fileupload.jar"; } pluginPackageProp.setProperty("portal.dependency.jars", depJar); } } catch (Exception e) { } return true; } else if (className != null && className.equals(RUBY_PORTLET)) { try { String depJar = pluginPackageProp.getProperty("portal.dependency.jars"); if (depJar == null || depJar.trim().length() == 0) { pluginPackageProp.setProperty("portal.dependency.jars", "bsf.jar"); } else { if (depJar.indexOf("bsf.jar") != -1) { return false; } if (depJar.endsWith(",")) { depJar += "bsf.jar"; } else { depJar += "," + "bsf.jar"; } pluginPackageProp.setProperty("portal.dependency.jars", depJar); } } catch (Exception e) { } return true; } return false; } private boolean addPluginPackageProperties(Properties pluginPackage, PortletContext portletContext, String webInfDir) { String className = portletContext.getPortletClass(); if (className != null && className.equals(JSF_PORTLET)) { String speedFilterEnabled = pluginPackage.getProperty("speed-filters-enabled"); if (speedFilterEnabled == null || speedFilterEnabled.trim().length() == 0) { pluginPackage.setProperty("speed-filters-enabled", "false"); return true; } return false; } return false; } private Properties getPluginPackageProperties(String webInfDir) { InputStream in = null; try { File file = new File(webInfDir + File.separator + "liferay-plugin-package.properties"); if (!file.exists()) { return new Properties(); } in = new FileInputStream(file); Properties pluginPackageProp = new Properties(); pluginPackageProp.load(in); return pluginPackageProp; } catch (Exception e) { } finally { if (in != null) { try { in.close(); } catch (IOException ex) { //Exceptions.printStackTrace(ex); } } } return new Properties(); } private void storePluginPackageProperties(Properties pluginPackage, String webInfDir) { File file = new File(webInfDir + File.separator + "liferay-plugin-package.properties"); FileOutputStream out = null; try { out = new FileOutputStream(file); pluginPackage.store(out, ""); out.flush(); out.close(); } catch (Exception e) { logger.info(e.getMessage()); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { } } } } }
923ea9019600bc0b1ddecf6d1d10641896ad165c
766
java
Java
internal/src/main/java/com/github/ponclure/simplenpcframework/internal/NPCManager.java
Ponclure/Simple-NPC-Framework
9b8067b4bcd1a128a49eb26f0f843094966cd653
[ "MIT" ]
2
2020-11-14T00:23:38.000Z
2021-12-08T00:50:23.000Z
internal/src/main/java/com/github/ponclure/simplenpcframework/internal/NPCManager.java
Ponclure/Simple-NPC-Framework
9b8067b4bcd1a128a49eb26f0f843094966cd653
[ "MIT" ]
null
null
null
internal/src/main/java/com/github/ponclure/simplenpcframework/internal/NPCManager.java
Ponclure/Simple-NPC-Framework
9b8067b4bcd1a128a49eb26f0f843094966cd653
[ "MIT" ]
null
null
null
18.238095
60
0.693211
1,000,859
/* * Copyright (c) 2018 Jitse Boonstra */ package com.github.ponclure.simplenpcframework.internal; import org.bukkit.entity.Player; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * @author Ponclure */ public final class NPCManager { private final Set<NPCBase> NPCS = new HashSet<>(); public Set<NPCBase> getAllNPCs() { return NPCS; } public Set<NPCBase> getShownToPlayer(final Player player) { final Set<NPCBase> set = Collections.emptySet(); for (final NPCBase npc : getAllNPCs()) { if (npc.getShown().contains(player.getUniqueId())) { set.add(npc); } } return set; } public void add(final NPCBase npc) { NPCS.add(npc); } public void remove(final NPCBase npc) { NPCS.remove(npc); } }
923eaabcdb69e2e68f4fb02eab576f759e81c88e
5,877
java
Java
src/main/java/gregtech/common/tileentities/machines/multi/GT_MetaTileEntity_LargeTurbine_Plasma.java
draknyte1/Gregtech5Ver2
eeb7d7442f0587e2a0dc80ffbce4ee44fa3da5d5
[ "MIT" ]
1
2016-09-24T08:50:35.000Z
2016-09-24T08:50:35.000Z
src/main/java/gregtech/common/tileentities/machines/multi/GT_MetaTileEntity_LargeTurbine_Plasma.java
draknyte1/Gregtech5Ver2
eeb7d7442f0587e2a0dc80ffbce4ee44fa3da5d5
[ "MIT" ]
null
null
null
src/main/java/gregtech/common/tileentities/machines/multi/GT_MetaTileEntity_LargeTurbine_Plasma.java
draknyte1/Gregtech5Ver2
eeb7d7442f0587e2a0dc80ffbce4ee44fa3da5d5
[ "MIT" ]
null
null
null
40.253425
288
0.634507
1,000,860
package gregtech.common.tileentities.machines.multi; import gregtech.api.GregTech_API; import gregtech.api.enums.Textures; import gregtech.api.interfaces.ITexture; import gregtech.api.interfaces.metatileentity.IMetaTileEntity; import gregtech.api.interfaces.tileentity.IGregTechTileEntity; import gregtech.api.objects.GT_RenderedTexture; import gregtech.api.util.GT_Recipe; import gregtech.api.util.GT_Recipe.GT_Recipe_Map; import gregtech.api.util.GT_Utility; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidRegistry; import java.util.ArrayList; import java.util.Collection; public class GT_MetaTileEntity_LargeTurbine_Plasma extends GT_MetaTileEntity_LargeTurbine { public GT_MetaTileEntity_LargeTurbine_Plasma(int aID, String aName, String aNameRegional) { super(aID, aName, aNameRegional); } public GT_MetaTileEntity_LargeTurbine_Plasma(String aName) { super(aName); } @Override public ITexture[] getTexture(IGregTechTileEntity aBaseMetaTileEntity, byte aSide, byte aFacing, byte aColorIndex, boolean aActive, boolean aRedstone) { return new ITexture[]{Textures.BlockIcons.MACHINE_CASINGS[1][aColorIndex + 1], aFacing == aSide ? aActive ? new GT_RenderedTexture(Textures.BlockIcons.LARGETURBINE_TU_ACTIVE5) : new GT_RenderedTexture(Textures.BlockIcons.LARGETURBINE_TU5) : Textures.BlockIcons.CASING_BLOCKS[60]}; } public String[] getDescription() { return new String[]{ "Controller Block for the Large Plasma Generator", "Size(WxHxD): 3x3x4 (Hollow), Controller (Front centered)", "1x Input Hatch (Side centered)", "1x Maintenance Hatch (Side centered)", "1x Muffler Hatch (Side centered)", "1x Dynamo Hatch (Back centered)", "Tungstensteel Turbine Casings for the rest (24 at least!)", "Needs a Turbine Item (Inside controller GUI)"}; } public int getFuelValue(FluidStack aLiquid) { if (aLiquid == null || GT_Recipe_Map.sTurbineFuels == null) return 0; FluidStack tLiquid; Collection<GT_Recipe> tRecipeList = GT_Recipe_Map.sPlasmaFuels.mRecipeList; if (tRecipeList != null) for (GT_Recipe tFuel : tRecipeList) if ((tLiquid = GT_Utility.getFluidForFilledItem(tFuel.getRepresentativeInput(0), true)) != null) if (aLiquid.isFluidEqual(tLiquid)) return tFuel.mSpecialValue; return 0; } @Override public IMetaTileEntity newMetaEntity(IGregTechTileEntity aTileEntity) { return new GT_MetaTileEntity_LargeTurbine_Plasma(mName); } @Override public Block getCasingBlock() { return GregTech_API.sBlockCasings4; } @Override public byte getCasingMeta() { return 12; } @Override public byte getCasingTextureIndex() { return 60; } @Override public int getPollutionPerTick(ItemStack aStack) { return 0; } @Override int fluidIntoPower(ArrayList<FluidStack> aFluids, int aOptFlow, int aBaseEff) { aOptFlow *= 40; int tEU = 0; int actualOptimalFlow = 0; if (aFluids.size() >= 1) { FluidStack firstFuelType = new FluidStack(aFluids.get(0), 0); // Identify a SINGLE type of fluid to process. Doesn't matter which one. Ignore the rest! int fuelValue = getFuelValue(firstFuelType); actualOptimalFlow = (int) ((aOptFlow + fuelValue - 1) / fuelValue); this.realOptFlow = actualOptimalFlow; // For scanner info int remainingFlow = (int) (actualOptimalFlow * 1.25f); // Allowed to use up to 125% of optimal flow. Variable required outside of loop for multi-hatch scenarios. int flow = 0; int totalFlow = 0; for (int i = 0; i < aFluids.size(); i++) { if (aFluids.get(i).isFluidEqual(firstFuelType)) { flow = aFluids.get(i).amount; // Get all (steam) in hatch flow = Math.min(flow, Math.min(remainingFlow, (int) (actualOptimalFlow * 1.25f))); // try to use up to 125% of optimal flow w/o exceeding remainingFlow depleteInput(new FluidStack(aFluids.get(i), flow)); // deplete that amount this.storedFluid = aFluids.get(i).amount; remainingFlow -= flow; // track amount we're allowed to continue depleting from hatches totalFlow += flow; // track total input used } } String fn = FluidRegistry.getFluidName(firstFuelType); String[] nameSegments = fn.split("\\.",2); if (nameSegments.length==2){ String outputName=nameSegments[1]; FluidStack output = FluidRegistry.getFluidStack(outputName, totalFlow); if (output==null){ output = FluidRegistry.getFluidStack("molten."+outputName, totalFlow); } if (output!=null) { addOutput(output); } } tEU = (int) (Math.min((float) actualOptimalFlow, totalFlow) * fuelValue); if (totalFlow != actualOptimalFlow) { float efficiency = 1.0f - Math.abs(((totalFlow - (float) actualOptimalFlow) / actualOptimalFlow)); if(totalFlow>aOptFlow){efficiency = 1.0f;} if (efficiency < 0) efficiency = 0; // Can happen with really ludicrously poor inefficiency. tEU *= efficiency; tEU = Math.max(1, tEU * aBaseEff / 10000); } else { tEU = tEU * aBaseEff / 10000; } return tEU; } return 0; } }
923eac11f52bd4a5e8c02c4481ae449c9ae15d78
1,539
java
Java
snippets/springboot-config-batch/src/test/java/com/camunda/consulting/snippet/springboot_config_batch/ProcessTest.java
bernhardroth3/code
b5e5bfca3a5847a375829cdb9b814926008cb694
[ "Apache-2.0" ]
403
2017-10-26T11:20:17.000Z
2022-03-29T08:15:20.000Z
snippets/springboot-config-batch/src/test/java/com/camunda/consulting/snippet/springboot_config_batch/ProcessTest.java
bernhardroth3/code
b5e5bfca3a5847a375829cdb9b814926008cb694
[ "Apache-2.0" ]
121
2017-12-12T21:23:32.000Z
2022-03-30T14:22:49.000Z
snippets/springboot-config-batch/src/test/java/com/camunda/consulting/snippet/springboot_config_batch/ProcessTest.java
bernhardroth3/code
b5e5bfca3a5847a375829cdb9b814926008cb694
[ "Apache-2.0" ]
775
2017-10-26T19:53:52.000Z
2022-03-31T08:46:18.000Z
29.037736
81
0.781676
1,000,861
package com.camunda.consulting.snippet.springboot_config_batch; import org.apache.ibatis.logging.LogFactory; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.batch.Batch; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.*; import static org.junit.Assert.*; import java.util.Arrays; import java.util.List; /** * Test case starting an in-memory database-backed Process Engine. */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class ProcessTest { private static final String PROCESS_DEFINITION_KEY = "springboot-config-batch"; @Autowired private ProcessEngine processEngine; static { LogFactory.useSlf4jLogging(); // MyBatis } @Before public void setup() { init(processEngine); } @Test public void testHappyPath() { List<String> processInstanceIds = Arrays.asList("23", "42"); runtimeService().deleteProcessInstancesAsync( processInstanceIds, null, "Test"); Batch batch = managementService().createBatchQuery().singleResult(); assertEquals(100, batch.getInvocationsPerBatchJob()); } }
923ead3f6ca9f5f47b218be1065e6c3e4e2f9c97
3,451
java
Java
transfuse/src/main/java/org/androidtransfuse/experiment/generators/SuperGenerator.java
doniwinata0309/transfuse
a8ee2e9b7263f4c88d93f0f85113a5e99b2a9011
[ "Apache-2.0" ]
114
2015-01-04T09:46:29.000Z
2021-11-09T10:58:46.000Z
transfuse/src/main/java/org/androidtransfuse/experiment/generators/SuperGenerator.java
doniwinata0309/transfuse
a8ee2e9b7263f4c88d93f0f85113a5e99b2a9011
[ "Apache-2.0" ]
72
2015-01-23T20:13:05.000Z
2021-01-20T09:27:57.000Z
transfuse/src/main/java/org/androidtransfuse/experiment/generators/SuperGenerator.java
doniwinata0309/transfuse
a8ee2e9b7263f4c88d93f0f85113a5e99b2a9011
[ "Apache-2.0" ]
30
2015-04-05T22:21:05.000Z
2020-10-27T03:26:06.000Z
35.947917
149
0.692843
1,000,863
/** * Copyright 2011-2015 John Ericksen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidtransfuse.experiment.generators; import com.sun.codemodel.JBlock; import com.sun.codemodel.JExpr; import com.sun.codemodel.JInvocation; import org.androidtransfuse.adapter.ASTMethod; import org.androidtransfuse.adapter.ASTParameter; import org.androidtransfuse.adapter.MethodSignature; import org.androidtransfuse.analysis.astAnalyzer.ManualSuperAspect; import org.androidtransfuse.annotations.Factory; import org.androidtransfuse.experiment.*; import org.androidtransfuse.model.InjectionNode; import org.androidtransfuse.model.MethodDescriptor; import javax.inject.Inject; import java.util.List; import java.util.Set; /** * @author John Ericksen */ public class SuperGenerator implements Generation { public @Factory interface SuperGeneratorFactory { SuperGenerator build(ASTMethod method, boolean executeLast); } private final ASTMethod method; private final boolean executeLast; @Inject public SuperGenerator(ASTMethod method, boolean executeLast) { this.method = method; this.executeLast = executeLast; } @Override public String getName() { return "Super Generator for " + method; } @Override public void schedule(final ComponentBuilder builder, ComponentDescriptor descriptor) { builder.addLazy(method, executeLast? GenerationPhase.POST_SUPER : GenerationPhase.SUPER, new ComponentMethodGenerator() { @Override public void generate(MethodDescriptor methodDescriptor, JBlock block) { if(!isSuperCanceled(builder.getExpressionMap().keySet())) { JInvocation invocation = block.invoke(JExpr._super(), method.getName()); List<ASTParameter> parameters = methodDescriptor.getASTMethod().getParameters(); for (ASTParameter parameter : parameters) { invocation.arg(methodDescriptor.getParameter(parameter).getExpression()); } } } }); } private boolean isSuperCanceled(Set<InjectionNode> injectionNodes){ MethodSignature signature = new MethodSignature(method); for (InjectionNode injectionNode : injectionNodes) { if(injectionNode.containsAspect(ManualSuperAspect.class)){ ManualSuperAspect aspect = injectionNode.getAspect(ManualSuperAspect.class); for (ManualSuperAspect.Method manualSuperMethod : aspect.getMethods()) { MethodSignature manualSuperMethodSignature = new MethodSignature(manualSuperMethod.getName(), manualSuperMethod.getParameters()); if(signature.equals(manualSuperMethodSignature)){ return true; } } } } return false; } }
923ead5cfebda2f61c61eb28886778c309a7a228
452
java
Java
crux-sql/src/crux/CruxSchemaFactory.java
reducecombine/crux
254caf96bcea67992d673da9ab9dc09c7c439b35
[ "MIT" ]
null
null
null
crux-sql/src/crux/CruxSchemaFactory.java
reducecombine/crux
254caf96bcea67992d673da9ab9dc09c7c439b35
[ "MIT" ]
null
null
null
crux-sql/src/crux/CruxSchemaFactory.java
reducecombine/crux
254caf96bcea67992d673da9ab9dc09c7c439b35
[ "MIT" ]
null
null
null
34.769231
109
0.780973
1,000,864
package crux.calcite; import java.util.Map; import org.apache.calcite.schema.SchemaFactory; import org.apache.calcite.schema.Schema; import org.apache.calcite.schema.SchemaPlus; public class CruxSchemaFactory implements SchemaFactory { public Schema create (SchemaPlus parentSchema, String name, Map<String, Object> operands) { return (Schema) CruxUtils.resolve("crux.calcite/create-schema").invoke(parentSchema, name, operands); } }
923ead8ab17d67478ef386dcc5cf4299929a543f
889
java
Java
L06/src/main/java/com/jbtits/otus/lecture6/MoneyCell.java
gtjbtits/otus-java-2017-11-gt
547935cd96189d0b4bca3ae75a8d32e39d7b3b22
[ "MIT" ]
null
null
null
L06/src/main/java/com/jbtits/otus/lecture6/MoneyCell.java
gtjbtits/otus-java-2017-11-gt
547935cd96189d0b4bca3ae75a8d32e39d7b3b22
[ "MIT" ]
null
null
null
L06/src/main/java/com/jbtits/otus/lecture6/MoneyCell.java
gtjbtits/otus-java-2017-11-gt
547935cd96189d0b4bca3ae75a8d32e39d7b3b22
[ "MIT" ]
3
2018-08-26T09:53:47.000Z
2020-03-08T17:15:42.000Z
21.166667
72
0.609674
1,000,865
package com.jbtits.otus.lecture6; public class MoneyCell implements Comparable<MoneyCell> { private Denomination denomination; private int count; MoneyCell(Denomination denomination) { this.denomination = denomination; } public int getCount() { return count; } public Denomination getDenomination() { return denomination; } public int sum() { return count * denomination.getValue(); } public int delagatedSum(int amount) { return amount * denomination.getValue(); } public void put(int notes) { count += notes; } public void get(int notes) { if (count < notes) { throw new NotEnoughNotes(); } count -= notes; } public int compareTo(MoneyCell o) { return denomination.getValue() - o.getDenomination().getValue(); } }
923eae991a239bf7096eea5cd34c28d45e8531d1
2,665
java
Java
openjdk11/test/langtools/jdk/javadoc/doclet/testAuthor/TestAuthor.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
test/langtools/jdk/javadoc/doclet/testAuthor/TestAuthor.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
test/langtools/jdk/javadoc/doclet/testAuthor/TestAuthor.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
29.94382
76
0.609756
1,000,866
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8202947 * @summary test the at-author tag, and corresponding option * @library /tools/lib ../lib * @modules jdk.javadoc/jdk.javadoc.internal.tool * @build toolbox.ToolBox JavadocTester * @run main TestAuthor */ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import toolbox.ToolBox; public class TestAuthor extends JavadocTester { public static void main(String... args) throws Exception { TestAuthor tester = new TestAuthor(); tester.runTests(); } ToolBox tb = new ToolBox(); Path src; TestAuthor() throws Exception { src = Files.createDirectories(Paths.get("src")); tb.writeJavaFiles(src, "package pkg;\n" + "/** Introduction. \n" + " * @author anonymous\n" + " */\n" + "public class Test { }\n"); } @Test void testAuthor() { javadoc("-d", "out-author", "-sourcepath", src.toString(), "-author", "pkg"); checkExit(Exit.OK); checkAuthor(true); } @Test void testNoAuthor() { javadoc("-d", "out-noauthor", "-sourcepath", src.toString(), "pkg"); checkExit(Exit.OK); checkAuthor(false); } void checkAuthor(boolean on) { checkOutput("pkg/Test.html", on, "<dl>\n" + "<dt><span class=\"simpleTagLabel\">Author:</span></dt>\n" + "<dd>anonymous</dd>\n" + "</dl>"); } }
923eafbc8c0b00eaf129b99a49df01d062d0e8be
8,037
java
Java
unisa-tools/unisa-smsenquiry/src/java/za/ac/unisa/lms/tools/smsenquiry/forms/SmsEnquiryForm.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
unisa-tools/unisa-smsenquiry/src/java/za/ac/unisa/lms/tools/smsenquiry/forms/SmsEnquiryForm.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
unisa-tools/unisa-smsenquiry/src/java/za/ac/unisa/lms/tools/smsenquiry/forms/SmsEnquiryForm.java
sadupally/Dev
ead9de3993b7a805199ac254c6fa99d3dda48adf
[ "ECL-2.0" ]
null
null
null
29.01444
80
0.768446
1,000,867
package za.ac.unisa.lms.tools.smsenquiry.forms; import java.util.List; import java.util.Calendar; import java.util.HashMap; import org.apache.struts.validator.ValidatorForm; public class SmsEnquiryForm extends ValidatorForm { private static final long serialVersionUID = 1L; private String currentPage; private String novellUserId; private String batchNumber; private String studentNumber; private String cellNumber; private String dateSent; private String message; private List listSmsLog; private List listSmsRequest; private List listMessageStatus; private String selectedMessageStatus; private String searchBatchNumber; private String searchStudentNumber; private String searchCellNumber; private String searchFromDate; private String searchToDate; private String searchResponsibilityCode; private String searchPersonnelNumber; private String senderName; private String senderEmail; private String senderPhoneNumber; private String smsStatus; private String smsStatusDesc; private String pageUpFlag; private String pageDownFlag; private String lastSmsLogReferenceNumber; private String firstSmsLogReferenceNumber; private String action; private String receiverName; private String currentList; private HashMap logEntryMap; //SMS log list private Calendar firstSmsLogSentDate; private Calendar lastSmsLogSentDate; //SMS request list private Calendar firstSmsBatchReqDate; private Calendar lastSmsBatchReqDate; private Calendar smsBatchReqFromDate; private Calendar smsBatchReqToDate; public String getReceiverName() { return receiverName; } public void setReceiverName(String receiverName) { this.receiverName = receiverName; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getLastSmsLogReferenceNumber() { return lastSmsLogReferenceNumber; } public void setLastSmsLogReferenceNumber(String lastSmsLogReferenceNumber) { this.lastSmsLogReferenceNumber = lastSmsLogReferenceNumber; } public String getFirstSmsLogReferenceNumber() { return firstSmsLogReferenceNumber; } public void setFirstSmsLogReferenceNumber(String firstSmsLogReferenceNumber) { this.firstSmsLogReferenceNumber = firstSmsLogReferenceNumber; } public String getPageUpFlag() { return pageUpFlag; } public void setPageUpFlag(String pageUpFlag) { this.pageUpFlag = pageUpFlag; } public List getListSmsRequest() { return listSmsRequest; } public void setListSmsRequest(List listSmsRequest) { this.listSmsRequest = listSmsRequest; } public String getSearchFromDate() { return searchFromDate; } public void setSearchFromDate(String searchFromDate) { this.searchFromDate = searchFromDate; } public String getSearchToDate() { return searchToDate; } public void setSearchToDate(String searchToDate) { this.searchToDate = searchToDate; } public String getSearchResponsibilityCode() { return searchResponsibilityCode; } public void setSearchResponsibilityCode(String searchResponsibilityCode) { this.searchResponsibilityCode = searchResponsibilityCode; } public String getSearchPersonnelNumber() { return searchPersonnelNumber; } public void setSearchPersonnelNumber(String searchPersonnelNumber) { this.searchPersonnelNumber = searchPersonnelNumber; } public String getBatchNumber() { return batchNumber; } public void setBatchNumber(String batchNumber) { this.batchNumber = batchNumber; } public String getStudentNumber() { return studentNumber; } public void setStudentNumber(String studentNumber) { this.studentNumber = studentNumber; } public String getCurrentPage() { return currentPage; } public void setCurrentPage(String currentPage) { this.currentPage = currentPage; } public String getNovellUserId() { return novellUserId; } public void setNovellUserId(String novellUserId) { this.novellUserId = novellUserId; } public String getCellNumber() { return cellNumber; } public void setCellNumber(String cellNumber) { this.cellNumber = cellNumber; } public String getDateSent() { return dateSent; } public void setDateSent(String dateSent) { this.dateSent = dateSent; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List getListSmsLog() { return listSmsLog; } public void setListSmsLog(List listSmsLog) { this.listSmsLog = listSmsLog; } public List getListMessageStatus() { return listMessageStatus; } public void setListMessageStatus(List listMessageStatus) { this.listMessageStatus = listMessageStatus; } public String getSelectedMessageStatus() { return selectedMessageStatus; } public void setSelectedMessageStatus(String selectedMessageStatus) { this.selectedMessageStatus = selectedMessageStatus; } public String getSearchBatchNumber() { return searchBatchNumber; } public void setSearchBatchNumber(String searchBatchNumber) { this.searchBatchNumber = searchBatchNumber; } public String getSearchStudentNumber() { return searchStudentNumber; } public void setSearchStudentNumber(String searchStudentNumber) { this.searchStudentNumber = searchStudentNumber; } public String getSearchCellNumber() { return searchCellNumber; } public void setSearchCellNumber(String searchCellNumber) { this.searchCellNumber = searchCellNumber; } public String getSenderName() { return senderName; } public void setSenderName(String senderName) { this.senderName = senderName; } public String getSenderEmail() { return senderEmail; } public void setSenderEmail(String senderEmail) { this.senderEmail = senderEmail; } public String getSenderPhoneNumber() { return senderPhoneNumber; } public void setSenderPhoneNumber(String senderPhoneNumber) { this.senderPhoneNumber = senderPhoneNumber; } public String getSmsStatus() { return smsStatus; } public void setSmsStatus(String smsStatus) { this.smsStatus = smsStatus; } public String getSmsStatusDesc() { return smsStatusDesc; } public void setSmsStatusDesc(String smsStatusDesc) { this.smsStatusDesc = smsStatusDesc; } public String getPageDownFlag() { return pageDownFlag; } public void setPageDownFlag(String pageDownFlag) { this.pageDownFlag = pageDownFlag; } public Calendar getFirstSmsLogSentDate() { return firstSmsLogSentDate; } public void setFirstSmsLogSentDate(Calendar firstSmsLogSentDate) { this.firstSmsLogSentDate = firstSmsLogSentDate; } public Calendar getLastSmsLogSentDate() { return lastSmsLogSentDate; } public void setLastSmsLogSentDate(Calendar lastSmsLogSentDate) { this.lastSmsLogSentDate = lastSmsLogSentDate; } public Calendar getLastSmsBatchReqDate() { return lastSmsBatchReqDate; } public void setLastSmsBatchReqDate(Calendar lastSmsBatchReqDate) { this.lastSmsBatchReqDate = lastSmsBatchReqDate; } public Calendar getFirstSmsBatchReqDate() { return firstSmsBatchReqDate; } public void setFirstSmsBatchReqDate(Calendar firstSmsBatchReqDate) { this.firstSmsBatchReqDate = firstSmsBatchReqDate; } public Calendar getSmsBatchReqToDate() { return smsBatchReqToDate; } public void setSmsBatchReqToDate(Calendar smsBatchReqToDate) { this.smsBatchReqToDate = smsBatchReqToDate; } public Calendar getSmsBatchReqFromDate() { return smsBatchReqFromDate; } public void setSmsBatchReqFromDate(Calendar smsBatchReqFromDate) { this.smsBatchReqFromDate = smsBatchReqFromDate; } public HashMap getLogEntryMap() { return logEntryMap; } public void setLogEntryMap(HashMap logEntryMap) { this.logEntryMap = logEntryMap; } public String getCurrentList() { return currentList; } public void setCurrentList(String currentList) { this.currentList = currentList; } }
923eafbefeaa79953226f56ffb52ecb4d247b23b
712
java
Java
src/main/java/com/shivamrajput/finance/hw/shivamrajputhw/module/loan/controller/dto/PayDTO.java
Cyraz/4FIT_shivam_HW
e5e561ffe78d8d30b4f127bc812b8c9fe9fcdb07
[ "MIT" ]
null
null
null
src/main/java/com/shivamrajput/finance/hw/shivamrajputhw/module/loan/controller/dto/PayDTO.java
Cyraz/4FIT_shivam_HW
e5e561ffe78d8d30b4f127bc812b8c9fe9fcdb07
[ "MIT" ]
null
null
null
src/main/java/com/shivamrajput/finance/hw/shivamrajputhw/module/loan/controller/dto/PayDTO.java
Cyraz/4FIT_shivam_HW
e5e561ffe78d8d30b4f127bc812b8c9fe9fcdb07
[ "MIT" ]
null
null
null
20.342857
78
0.610955
1,000,868
package com.shivamrajput.finance.hw.shivamrajputhw.module.loan.controller.dto; import java.math.BigDecimal; public class PayDTO { BigDecimal amount; Long personalNumber; public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Long getPersonalNumber() { return personalNumber; } public void setPersonalNumber(Long personalNumber) { this.personalNumber = personalNumber; } @Override public String toString() { return "PayDTO{" + "amount=" + amount + ", personalNumber=" + personalNumber + '}'; } }
923eb05e79118bead84a28d999e111ab1707df7e
8,510
java
Java
src/main/java/com/libertymutualgroup/herman/aws/ecs/broker/sns/SnsBroker.java
tied/herman
6ecdad57950d75db7774ca68362bde42e265f03e
[ "Apache-2.0" ]
41
2018-06-06T13:21:51.000Z
2022-03-24T19:26:43.000Z
src/main/java/com/libertymutualgroup/herman/aws/ecs/broker/sns/SnsBroker.java
tied/herman
6ecdad57950d75db7774ca68362bde42e265f03e
[ "Apache-2.0" ]
57
2018-06-06T13:18:54.000Z
2021-08-15T02:04:02.000Z
src/main/java/com/libertymutualgroup/herman/aws/ecs/broker/sns/SnsBroker.java
tied/herman
6ecdad57950d75db7774ca68362bde42e265f03e
[ "Apache-2.0" ]
26
2018-06-16T15:11:52.000Z
2021-11-21T10:44:15.000Z
47.277778
123
0.674148
1,000,869
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.libertymutualgroup.herman.aws.ecs.broker.sns; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.model.CreateTopicRequest; import com.amazonaws.services.sns.model.CreateTopicResult; import com.amazonaws.services.sns.model.SetTopicAttributesRequest; import com.amazonaws.services.sns.model.SubscribeRequest; import com.amazonaws.services.sns.model.SubscribeResult; import com.amazonaws.services.sns.model.Subscription; import com.amazonaws.services.sns.model.UnsubscribeRequest; import com.amazonaws.util.StringUtils; import com.libertymutualgroup.herman.aws.ecs.PropertyHandler; import com.libertymutualgroup.herman.logging.HermanLogger; import org.apache.commons.collections4.CollectionUtils; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class SnsBroker { public static final String AND_ENDPOINT = " and endpoint: "; public static final String AND_RAW_MESSAGE_DELIVERY = " and RawMessageDelivery: "; public static final String RAW_MESSAGE_DELIVERY = "RawMessageDelivery"; public static final String DEFAULT_STATUS = "false"; private HermanLogger logger; private PropertyHandler handler; public SnsBroker(HermanLogger logger, PropertyHandler handler) { this.logger = logger; this.handler = handler; } /** * http://docs.aws.amazon.com/sns/latest/api/API_SetTopicAttributes.html * <p> * Valid Map Keys: Policy */ public void brokerTopic(AmazonSNS client, SnsTopic topic, String topicPolicy) { CreateTopicResult createTopicResult; logger.addLogEntry("Creating topic : " + topic.getName()); createTopicResult = client.createTopic(new CreateTopicRequest().withName(topic.getName())); String topicArn = createTopicResult.getTopicArn(); if (topicPolicy != null) { String fullPolicy = handler.mapInProperties(topicPolicy); SetTopicAttributesRequest setTopicAttributesRequest = new SetTopicAttributesRequest() .withAttributeName("Policy").withAttributeValue(fullPolicy); client.setTopicAttributes(setTopicAttributesRequest.withTopicArn(topicArn)); } updateDeliveryStatusAttributes(client, topic, topicArn); if (topic.getSubscriptions() != null) { //automatically remove subscriptions autoDeleteSubscriptions(client, topic, topicArn); addSubscriptions(client, topic, topicArn); } } private void addSubscriptions(AmazonSNS client, SnsTopic topic, String topicArn) { for (SnsSubscription subscription : topic.getSubscriptions()) { String protocol = subscription.getProtocol(); String endpoint = subscription.getEndpoint(); String rawMessageDelivery = subscription.getRawMessageDelivery(); if (!StringUtils.isNullOrEmpty(protocol) && !StringUtils.isNullOrEmpty(endpoint)) { Map<String,String> attributes = new HashMap<>(); if(!StringUtils.isNullOrEmpty(rawMessageDelivery)){ logger.addLogEntry("Update subscription with RawMessageDelivery: " + protocol + AND_ENDPOINT + endpoint + AND_RAW_MESSAGE_DELIVERY + rawMessageDelivery); attributes.put(RAW_MESSAGE_DELIVERY, rawMessageDelivery); } logger.addLogEntry("Adding subscription with protocol: " + protocol + AND_ENDPOINT + endpoint); SubscribeRequest subscribeRequest = new SubscribeRequest() .withTopicArn(topicArn) .withProtocol(protocol) .withEndpoint(endpoint) .withAttributes(attributes); SubscribeResult subscribeResult = client.subscribe(subscribeRequest); logger.addLogEntry("Subscription created successfully with ARN: " + subscribeResult.getSubscriptionArn()); } else { logger.addLogEntry("Skipping subscription with protocol: " + protocol + AND_ENDPOINT + endpoint); } } } private void autoDeleteSubscriptions(AmazonSNS client, SnsTopic topic, String topicArn) { if (topic.getAutoRemoveSubscriptions() != null && topic.getAutoRemoveSubscriptions()) { for (Subscription subscription : client.listSubscriptionsByTopic(topicArn).getSubscriptions()) { boolean subscriptionExists = topic.getSubscriptions().stream().anyMatch( sub -> equalsWithoutNonEndpointCharacters(sub.getEndpoint(), subscription.getEndpoint()) && equalsWithoutNonEndpointCharacters(sub.getProtocol(), subscription.getProtocol())); if (!subscriptionExists) { logger.addLogEntry( "Delete subscription with protocol: " + subscription.getProtocol() + AND_ENDPOINT + subscription .getEndpoint() + " as it is no longer in the subscription list"); client.unsubscribe(new UnsubscribeRequest(subscription.getSubscriptionArn())); } } } } private void updateDeliveryStatusAttributes(AmazonSNS client, SnsTopic topic, String topicArn) { Map<String, String> requestedTopicAttributeNameValueMap = new HashMap<>( CollectionUtils.isEmpty(topic.getDeliveryStatusAttributes()) ? 0 : topic.getDeliveryStatusAttributes().size()); if (CollectionUtils.isNotEmpty(topic.getDeliveryStatusAttributes())) { topic.getDeliveryStatusAttributes().forEach(i -> { logger.addLogEntry( "Updating topic delivery status attribute. Name: " + i.getName() + " and value: " + i.getValue()); requestedTopicAttributeNameValueMap.put(i.getName(), i.getValue()); }); } Map<String, String> possibleDeliveryAttributeNameValueMap = new HashMap<>( SnsDeliveryStatusAttribute.values().length); Arrays.asList(SnsDeliveryStatusAttribute.values()) .forEach(i -> possibleDeliveryAttributeNameValueMap.put(i.getName(), i.getValue())); Map<String, String> updatedDeliveryStatusTopicAttributeNameValueMap = new HashMap<>( requestedTopicAttributeNameValueMap); client.getTopicAttributes(topicArn).getAttributes().forEach((k, v) -> { if (possibleDeliveryAttributeNameValueMap.get(k) != null && !requestedTopicAttributeNameValueMap .containsKey(k)) { logger.addLogEntry("Defaulting topic delivery status attribute. Key: " + k + " and value: " + possibleDeliveryAttributeNameValueMap.get(k)); updatedDeliveryStatusTopicAttributeNameValueMap .put(k, SnsDeliveryStatusAttribute.valueOf(k).getValue()); } }); updatedDeliveryStatusTopicAttributeNameValueMap .forEach((k, v) -> logger.addLogEntry("Attributes to be updated - key : " + k + " value : " + v)); updatedDeliveryStatusTopicAttributeNameValueMap.forEach((k, v) -> { SetTopicAttributesRequest setTopicAttributesRequest = new SetTopicAttributesRequest().withAttributeName(k).withAttributeValue(v); client.setTopicAttributes(setTopicAttributesRequest.withTopicArn(topicArn)); }); } public boolean equalsWithoutNonEndpointCharacters(String s1, String s2) { String string1 = s1.replaceAll("[^a-zA-Z0-9@\\.]", ""); String string2 = s2.replaceAll("[^a-zA-Z0-9@\\.]", ""); return equalsIgnoreCaseWithNullChecking(string1, string2); } public boolean equalsIgnoreCaseWithNullChecking(String s1, String s2) { return s1 == s2 || (s1 != null && s1.equalsIgnoreCase(s2)); } }
923eb0daacd9ce8fa2649ef3bef6775b7c483617
3,393
java
Java
batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/ChainerSettings.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/ChainerSettings.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
306
2019-09-27T06:41:56.000Z
2019-10-14T08:19:57.000Z
batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/ChainerSettings.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1
2022-01-31T19:22:33.000Z
2022-01-31T19:22:33.000Z
27.585366
84
0.673151
1,000,870
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.batchai.v2018_03_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Specifies the settings for Chainer job. */ public class ChainerSettings { /** * The path and file name of the python script to execute the job. */ @JsonProperty(value = "pythonScriptFilePath", required = true) private String pythonScriptFilePath; /** * The path to python interpreter. */ @JsonProperty(value = "pythonInterpreterPath") private String pythonInterpreterPath; /** * Command line arguments that needs to be passed to the python script. */ @JsonProperty(value = "commandLineArgs") private String commandLineArgs; /** * Number of processes parameter that is passed to MPI runtime. * The default value for this property is equal to nodeCount property. */ @JsonProperty(value = "processCount") private Integer processCount; /** * Get the pythonScriptFilePath value. * * @return the pythonScriptFilePath value */ public String pythonScriptFilePath() { return this.pythonScriptFilePath; } /** * Set the pythonScriptFilePath value. * * @param pythonScriptFilePath the pythonScriptFilePath value to set * @return the ChainerSettings object itself. */ public ChainerSettings withPythonScriptFilePath(String pythonScriptFilePath) { this.pythonScriptFilePath = pythonScriptFilePath; return this; } /** * Get the pythonInterpreterPath value. * * @return the pythonInterpreterPath value */ public String pythonInterpreterPath() { return this.pythonInterpreterPath; } /** * Set the pythonInterpreterPath value. * * @param pythonInterpreterPath the pythonInterpreterPath value to set * @return the ChainerSettings object itself. */ public ChainerSettings withPythonInterpreterPath(String pythonInterpreterPath) { this.pythonInterpreterPath = pythonInterpreterPath; return this; } /** * Get the commandLineArgs value. * * @return the commandLineArgs value */ public String commandLineArgs() { return this.commandLineArgs; } /** * Set the commandLineArgs value. * * @param commandLineArgs the commandLineArgs value to set * @return the ChainerSettings object itself. */ public ChainerSettings withCommandLineArgs(String commandLineArgs) { this.commandLineArgs = commandLineArgs; return this; } /** * Get the default value for this property is equal to nodeCount property. * * @return the processCount value */ public Integer processCount() { return this.processCount; } /** * Set the default value for this property is equal to nodeCount property. * * @param processCount the processCount value to set * @return the ChainerSettings object itself. */ public ChainerSettings withProcessCount(Integer processCount) { this.processCount = processCount; return this; } }