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
9237efd0d9aeb173563b06197e897812f3d3de08
9,866
java
Java
src/main/java/org/b3log/solo/processor/IndexProcessor.java
DaDaDa12138/solo
7b93aa41fba2c5176fb2128c366af90db466e8fc
[ "MulanPSL-1.0" ]
1,537
2016-04-12T01:01:31.000Z
2022-03-30T09:06:40.000Z
src/main/java/org/b3log/solo/processor/IndexProcessor.java
melon-pie/solo
c6a13b6577fc91cffd8d233a2161b3af7582d8a7
[ "MulanPSL-1.0" ]
224
2019-11-29T07:56:49.000Z
2022-03-31T08:14:20.000Z
src/main/java/org/b3log/solo/processor/IndexProcessor.java
melon-pie/solo
c6a13b6577fc91cffd8d233a2161b3af7582d8a7
[ "MulanPSL-1.0" ]
473
2016-01-11T14:01:43.000Z
2022-03-25T13:37:34.000Z
38.539063
204
0.675958
998,258
/* * Solo - A small and beautiful blogging system written in Java. * Copyright (c) 2010-present, b3log.org * * Solo is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.b3log.solo.processor; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import jodd.http.HttpRequest; import jodd.http.HttpResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.http.Request; import org.b3log.latke.http.RequestContext; import org.b3log.latke.http.renderer.AbstractFreeMarkerRenderer; import org.b3log.latke.http.renderer.BinaryRenderer; import org.b3log.latke.ioc.Inject; import org.b3log.latke.ioc.Singleton; import org.b3log.latke.model.Pagination; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.ServiceException; import org.b3log.latke.util.Locales; import org.b3log.latke.util.Paginator; import org.b3log.latke.util.URLs; import org.b3log.solo.Server; import org.b3log.solo.model.Common; import org.b3log.solo.model.Option; import org.b3log.solo.service.DataModelService; import org.b3log.solo.service.InitService; import org.b3log.solo.service.OptionQueryService; import org.b3log.solo.util.Skins; import org.b3log.solo.util.Solos; import org.json.JSONObject; import java.io.InputStream; import java.util.Calendar; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Index processor. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="https://ld246.com/member/DASHU">DASHU</a> * @author <a href="http://vanessa.b3log.org">Vanessa</a> * @version 2.0.0.4, Jun 25, 2020 * @since 0.3.1 */ @Singleton public class IndexProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(IndexProcessor.class); /** * DataModelService. */ @Inject private DataModelService dataModelService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Initialization service. */ @Inject private InitService initService; /** * Shows index with the specified context. * * @param context the specified context */ public void showIndex(final RequestContext context) { final Request request = context.getRequest(); final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "index.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); try { final int currentPageNum = Paginator.getPage(request); final JSONObject preference = optionQueryService.getPreference(); Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) context.attr(Keys.TEMPLATE_DIR_NAME), dataModel); dataModelService.fillIndexArticles(context, dataModel, currentPageNum, preference); dataModelService.fillCommon(context, dataModel, preference); dataModelService.fillFaviconURL(dataModel, preference); dataModelService.fillUsite(dataModel); dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, currentPageNum); final int previousPageNum = currentPageNum > 1 ? currentPageNum - 1 : 0; dataModel.put(Pagination.PAGINATION_PREVIOUS_PAGE_NUM, previousPageNum); final Integer pageCount = (Integer) dataModel.get(Pagination.PAGINATION_PAGE_COUNT); final int nextPageNum = currentPageNum + 1 > pageCount ? pageCount : currentPageNum + 1; dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, nextPageNum); dataModel.put(Common.PATH, ""); } catch (final ServiceException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); context.sendError(404); } } /** * Favicon bytes cache. &lt;"/favicon.ico", bytes&gt; */ private static final Cache<String, Object> FAVICON_CACHE = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).build(); /** * Shows favicon with the specified context. * * @param context the specified context */ public void showFavicon(final RequestContext context) { final BinaryRenderer binaryRenderer = new BinaryRenderer("image/x-icon"); context.setRenderer(binaryRenderer); final String key = "/favicon.ico"; byte[] bytes = (byte[]) FAVICON_CACHE.getIfPresent(key); if (null != bytes) { binaryRenderer.setData(bytes); return; } final JSONObject preference = optionQueryService.getPreference(); String faviconURL; if (null == preference) { faviconURL = Option.DefaultPreference.DEFAULT_FAVICON_URL; } else { faviconURL = preference.optString(Option.ID_C_FAVICON_URL); } try { final HttpResponse response = HttpRequest.get(faviconURL).header("User-Agent", Solos.USER_AGENT).connectionTimeout(3000).timeout(7000).send(); if (200 == response.statusCode()) { bytes = response.bodyBytes(); } else { throw new Exception(); } binaryRenderer.setData(bytes); } catch (final Exception e) { try (final InputStream resourceAsStream = IndexProcessor.class.getResourceAsStream("/images/favicon.ico")) { bytes = IOUtils.toByteArray(resourceAsStream); binaryRenderer.setData(bytes); } catch (final Exception ex) { LOGGER.log(Level.ERROR, "Loads default favicon.ico failed", e); context.sendError(500); return; } } FAVICON_CACHE.put(key, bytes); } /** * Shows start page. * * @param context the specified context */ public void showStart(final RequestContext context) { if (initService.isInited() && null != Solos.getCurrentUser(context)) { context.sendRedirect(Latkes.getServePath()); return; } String referer = context.param("referer"); if (StringUtils.isBlank(referer)) { referer = context.header("referer"); } if (StringUtils.isBlank(referer) || !isInternalLinks(referer)) { referer = Latkes.getServePath(); } final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "common-template/start.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final Request request = context.getRequest(); final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request)); dataModel.putAll(langs); dataModel.put(Common.VERSION, Server.VERSION); dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion()); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); dataModel.put(Common.REFERER, URLs.encode(referer)); Keys.fillRuntime(dataModel); dataModelService.fillFaviconURL(dataModel, optionQueryService.getPreference()); dataModelService.fillUsite(dataModel); Solos.addGoogleNoIndex(context); } /** * Logout. * * @param context the specified context */ public void logout(final RequestContext context) { final Request request = context.getRequest(); Solos.logout(request, context.getResponse()); Solos.addGoogleNoIndex(context); context.sendRedirect(Latkes.getServePath()); } /** * Shows kill browser page with the specified context. * * @param context the specified context */ public void showKillBrowser(final RequestContext context) { final Request request = context.getRequest(); final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "common-template/kill-browser.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); try { final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request)); dataModel.putAll(langs); final JSONObject preference = optionQueryService.getPreference(); dataModelService.fillCommon(context, dataModel, preference); dataModelService.fillFaviconURL(dataModel, preference); dataModelService.fillUsite(dataModel); Keys.fillServer(dataModel); Keys.fillRuntime(dataModel); } catch (final ServiceException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); context.sendError(404); } } /** * Preventing unvalidated redirects and forwards. See more at: * <a href="https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet">https://www.owasp.org/index.php/ * Unvalidated_Redirects_and_Forwards_Cheat_Sheet</a>. * * @return whether the destinationURL is an internal link */ private boolean isInternalLinks(final String destinationURL) { return destinationURL.startsWith(Latkes.getServePath()); } }
9237f0acd0b3415dae10ea072eb196e95acc6206
11,098
java
Java
Projet1/src/main/java/fr/afcepf/al29/groupem/controller/AddUserController.java
Afcepf-GroupeM/ProjetCesium
eff7325cb0c977dc56dd9f35743a8aec2ecef160
[ "MIT" ]
null
null
null
Projet1/src/main/java/fr/afcepf/al29/groupem/controller/AddUserController.java
Afcepf-GroupeM/ProjetCesium
eff7325cb0c977dc56dd9f35743a8aec2ecef160
[ "MIT" ]
null
null
null
Projet1/src/main/java/fr/afcepf/al29/groupem/controller/AddUserController.java
Afcepf-GroupeM/ProjetCesium
eff7325cb0c977dc56dd9f35743a8aec2ecef160
[ "MIT" ]
null
null
null
29.994595
189
0.688322
998,259
package fr.afcepf.al29.groupem.controller; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import org.apache.commons.validator.routines.DateValidator; import org.apache.commons.validator.routines.EmailValidator; import org.apache.commons.validator.routines.RegexValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import fr.afcepf.al29.groupem.business.api.ItemBusApi; import fr.afcepf.al29.groupem.business.api.OrderBusApi; import fr.afcepf.al29.groupem.business.api.UserBusApi; import fr.afcepf.al29.groupem.dao.api.OrderLineDaoApi; import fr.afcepf.al29.groupem.entities.Civilite; import fr.afcepf.al29.groupem.entities.Item; import fr.afcepf.al29.groupem.entities.Order; import fr.afcepf.al29.groupem.entities.OrderLine; import fr.afcepf.al29.groupem.entities.User; @Component @ManagedBean public class AddUserController { private int id; private Civilite civilite; private Civilite[] listeCivilite; private String lastName; private String firstName; private String birthDay; private String birthMonth; private String birthYear; private String email; private String phone; private String password1; private String password2; private String message; private List<String> dayList; private List<String> monthList; private List<String> yearList; private DataGeneration dataGen = new DataGeneration(); private int nbUsersToGenerate; private String messageUsersGenerate; private List<User> listUsersGenerated; private int nbOrdersToGenerate; private String messageOrdersGenerate; private List<Order> listOrdersGenerated; @Autowired private ItemBusApi itemBus; @Autowired private UserBusApi userBus; @Autowired private OrderBusApi orderBus; @Autowired private OrderLineDaoApi orderLineBus; @PostConstruct public void init(){ message =""; listeCivilite = Civilite.class.getEnumConstants(); dayList = new ArrayList<>(); monthList = new ArrayList<>(); yearList = new ArrayList<>(); dayList.addAll(Arrays.asList("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31")); monthList.addAll(Arrays.asList("01","02","03","04","05","06","07","08","09","10","11","12")); yearList.addAll(Arrays.asList("2016","2015","2014","2013","2012","2011","2010","2009","2008","2007","2006","2005","2004","2003","2002","2001","2000","1999", "1998","1997","1996","1995","1994","1993","1992","1991","1990","1989","1988","1987","1986","1985","1984","1983","1982","1981", "1980","1979","1978","1977","1976","1975","1974","1973","1972","1971","1970","1969","1968","1967","1966","1965","1964","1963", "1962","1961","1960","1959","1958","1957","1956","1955","1954","1953","1952","1951","1950","1949","1948","1947","1946","1945", "1944","1943","1942","1941","1940","1939","1938","1937","1936","1935","1934","1933","1932","1931","1930","1929","1928","1927", "1926","1925","1924","1923","1922","1921","1920","1919","1918","1917","1916","1915","1914","1913","1912","1911","1910","1909", "1908","1907","1906","1905")); } public String action(){ String returnAddress = null; message =""; EmailValidator emailValidator = EmailValidator.getInstance(); RegexValidator nameValidator = new RegexValidator("^[a-zA-Z \\-\\.\\']*$",false); RegexValidator phoneValidator = new RegexValidator("^0[1-6]{1}(([0-9]{2}){4})|((\\s[0-9]{2}){4})|((-[0-9]{2}){4})$",false); DateValidator dateValidator = DateValidator.getInstance(); String birthDate = birthDay+birthMonth+birthYear; boolean civiliteValid =false; for (Civilite civi : listeCivilite) { if(civi.equals(civilite)){ civiliteValid = true; } } boolean lastNameValid = nameValidator.isValid(lastName) && (!lastName.isEmpty()); boolean firstNameValid = nameValidator.isValid(firstName) && (!firstName.isEmpty()); boolean passwordValid = password1.equals(password2) && (!password1.isEmpty()); boolean emailValid = emailValidator.isValid(email); boolean emailNotAlreadySubcribed = true; boolean birthDateValid = dateValidator.isValid(birthDate, "ddMMyyy"); boolean phoneValid = phoneValidator.isValid(phone); if(!civiliteValid){message += "Civilité invalide<br/>";} if(!lastNameValid){message += "Nom invalide<br/>";} if(!firstNameValid){message += "Prénom invalide<br/>";} if(!emailValid){message += "Email invalide<br/>"; } else{ if(userBus.getUserByLogin(email) != null){ emailNotAlreadySubcribed = false; message += "Email déja utilisé<br/>"; } } if(!birthDateValid){message += "Date de naissance invalide<br/>";} if(!phoneValid){message += "Téléphone invalide<br/>";} if(!passwordValid){message += "Les mots de passe ne correspondent pas ou sont vides.<br/>";} if(lastNameValid && firstNameValid && passwordValid && emailValid && emailNotAlreadySubcribed && birthDateValid && phoneValid){ DateFormat dateFormater = new SimpleDateFormat("ddMMyyyy"); Date formattedDate = null; try { formattedDate = dateFormater.parse(birthDate); } catch (ParseException e) { System.out.println("ERREUR - Parsing birthDate in AddUserController - action()" + e.getMessage()); } User user = userBus.createUser(civilite, lastName, firstName, email, phone, password1,formattedDate ); resetFields(); returnAddress = "inscription-ok"; message = "Utilisateur créé avec succes!" +" " + "Id du nouvel utilisateur: " + user.getId(); } return returnAddress; } public void resetFields(){ civilite = null; lastName = ""; firstName = ""; birthDay = ""; birthMonth = ""; birthYear = ""; email = ""; phone = ""; } public String generateUsers(){ Date dateDebut = new Date(); listUsersGenerated = dataGen.generateUsers(nbUsersToGenerate); listUsersGenerated = userBus.generateUsers(listUsersGenerated); Date dateFin = new Date(); long totalTime = dateFin.getTime() - dateDebut.getTime(); messageUsersGenerate = "Succes - "+ nbUsersToGenerate + " utilisateurs ajoutés à la base! - Effectué en " + totalTime + " millisecondes."; return null; } public String generateOrders(){ Date dateDebut = new Date(); List<User> allUsers = userBus.getAllUsers(); List<Item> allItems = itemBus.getAllItems(); listOrdersGenerated = dataGen.gernerateOrder(allUsers, allItems, nbOrdersToGenerate); for (Order order : listOrdersGenerated) { order = orderBus.createOrder(order); for (OrderLine orderLine : order.getOrderLines()) { orderLine.setOrder(order); orderLineBus.createOrderLine(orderLine); } } Date dateFin = new Date(); long totalTime = dateFin.getTime() - dateDebut.getTime(); messageOrdersGenerate = "Succes - "+ nbOrdersToGenerate + " orders ajoutées à la base! - Effectué en " + totalTime + " millisecondes."; return null; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Civilite getCivilite() { return civilite; } public void setCivilite(Civilite civilite) { this.civilite = civilite; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getBirthDay() { return birthDay; } public void setBirthDay(String birthDay) { this.birthDay = birthDay; } public String getBirthMonth() { return birthMonth; } public void setBirthMonth(String birthMonth) { this.birthMonth = birthMonth; } public String getBirthYear() { return birthYear; } public void setBirthYear(String birthYear) { this.birthYear = birthYear; } public List<String> getDayList() { return dayList; } public void setDayList(List<String> dayList) { this.dayList = dayList; } public List<String> getMonthList() { return monthList; } public void setMonthList(List<String> monthList) { this.monthList = monthList; } public List<String> getYearList() { return yearList; } public void setYearList(List<String> yearList) { this.yearList = yearList; } public String getPassword1() { return password1; } public void setPassword1(String password1) { this.password1 = password1; } public String getPassword2() { return password2; } public void setPassword2(String password2) { this.password2 = password2; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Civilite[] getListeCivilite() { return listeCivilite; } public void setListeCivilite(Civilite[] listeCivilite) { this.listeCivilite = listeCivilite; } public DataGeneration getDataGen() { return dataGen; } public void setDataGen(DataGeneration dataGen) { this.dataGen = dataGen; } public int getNbUsersToGenerate() { return nbUsersToGenerate; } public void setNbUsersToGenerate(int nbUsersToGenerate) { this.nbUsersToGenerate = nbUsersToGenerate; } public String getMessageUsersGenerate() { return messageUsersGenerate; } public void setMessageUsersGenerate(String messageUsersGenerate) { this.messageUsersGenerate = messageUsersGenerate; } public UserBusApi getUserBus() { return userBus; } public void setUserBus(UserBusApi userBus) { this.userBus = userBus; } public List<User> getListUsersGenerated() { return listUsersGenerated; } public void setListUsersGenerated(List<User> listUsersGenerated) { this.listUsersGenerated = listUsersGenerated; } public int getNbOrdedsToGenerate() { return nbOrdersToGenerate; } public void setNbOrdedsToGenerate(int nbOrdedsToGenerate) { this.nbOrdersToGenerate = nbOrdedsToGenerate; } public String getMessageOrdersGenerate() { return messageOrdersGenerate; } public void setMessageOrdersGenerate(String messageOrdersGenerate) { this.messageOrdersGenerate = messageOrdersGenerate; } public List<Order> getListOrdersGenerated() { return listOrdersGenerated; } public void setListOrdersGenerated(List<Order> listOrdersGenerated) { this.listOrdersGenerated = listOrdersGenerated; } }
9237f3265fcfe0cd538cb3079d84655b79375f75
2,415
java
Java
app/src/main/java/com/blongho/countrydata/utils/AppUtils.java
blongho/CountryDataLibrary-Demo
cce1135dc0a0e928d4557dcc85d3745f5f117216
[ "MIT" ]
null
null
null
app/src/main/java/com/blongho/countrydata/utils/AppUtils.java
blongho/CountryDataLibrary-Demo
cce1135dc0a0e928d4557dcc85d3745f5f117216
[ "MIT" ]
null
null
null
app/src/main/java/com/blongho/countrydata/utils/AppUtils.java
blongho/CountryDataLibrary-Demo
cce1135dc0a0e928d4557dcc85d3745f5f117216
[ "MIT" ]
null
null
null
35.514706
84
0.718427
998,260
/* * MIT License * * Copyright (c) 2020 - 2022 Bernard Che Longho * * 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 NON-INFRINGEMENT. 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 com.blongho.countrydata.utils; import android.util.Log; import java.text.NumberFormat; import java.util.List; import java.util.Locale; public final class AppUtils { private static final String TAG = "AppUtils"; public static String formatNumber(final double number) { NumberFormat numberFormat = NumberFormat.getNumberInstance(); numberFormat.setMaximumFractionDigits(2); numberFormat.setGroupingUsed(true); return numberFormat.format(number); } public static String formatNumber(final long number) { NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault()); numberFormat.setMaximumFractionDigits(2); numberFormat.setGroupingUsed(true); return numberFormat.format(number); } public static String listToString(final List<String> items) { Log.d(TAG, "listToString: items are " + items); if (items == null || items.size() == 0) { return ""; } else if (items.size() == 1) { return items.get(0); } else { final StringBuilder builder = new StringBuilder(); int idx = 1; for (final String item : items) { builder.append(idx).append(". ").append(item).append("\n"); idx += 1; } return builder.toString(); } } }
9237f4211cbda978393d5eeab4b8f1ddf5c13420
1,497
java
Java
office/src/main/java/com/wxiwei/office/fc/hssf/formula/eval/NotImplementedException.java
sonnguyenxcii/PdfViewer
cd4f7a82a7118adff663079b1b9e976cca37b9ba
[ "MIT" ]
null
null
null
office/src/main/java/com/wxiwei/office/fc/hssf/formula/eval/NotImplementedException.java
sonnguyenxcii/PdfViewer
cd4f7a82a7118adff663079b1b9e976cca37b9ba
[ "MIT" ]
null
null
null
office/src/main/java/com/wxiwei/office/fc/hssf/formula/eval/NotImplementedException.java
sonnguyenxcii/PdfViewer
cd4f7a82a7118adff663079b1b9e976cca37b9ba
[ "MIT" ]
null
null
null
40.459459
94
0.698063
998,261
/* ==================================================================== 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 com.wxiwei.office.fc.hssf.formula.eval; import com.wxiwei.office.fc.ss.usermodel.FormulaEvaluator; /** * An exception thrown by implementors of {@link FormulaEvaluator} when attempting to evaluate * a formula which requires features that POI does not (yet) support. * * @author Josh Micich */ public final class NotImplementedException extends RuntimeException { public NotImplementedException(String message) { super(message); } public NotImplementedException(String message, NotImplementedException cause) { super(message, cause); } }
9237f5a7be13ced99e23d154256dd0ec81de1a39
506
java
Java
flow-tests/test-root-ui-context/src/test/java/com/vaadin/flow/uitest/ui/NoRouterIT.java
hichem-fazai/flow
7d262b54fa5eadde911bacf11b6145849c7db514
[ "Apache-2.0" ]
402
2017-10-02T09:00:34.000Z
2022-03-30T06:09:40.000Z
flow-tests/test-root-ui-context/src/test/java/com/vaadin/flow/uitest/ui/NoRouterIT.java
hichem-fazai/flow
7d262b54fa5eadde911bacf11b6145849c7db514
[ "Apache-2.0" ]
9,144
2017-10-02T07:12:23.000Z
2022-03-31T19:16:56.000Z
flow-tests/test-root-ui-context/src/test/java/com/vaadin/flow/uitest/ui/NoRouterIT.java
flyzoner/flow
3f00a72127a2191eb9b9d884370ca6c1cb2f80bf
[ "Apache-2.0" ]
167
2017-10-11T13:07:29.000Z
2022-03-22T09:02:42.000Z
22
78
0.711462
998,262
package com.vaadin.flow.uitest.ui; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.vaadin.flow.testutil.ChromeBrowserTest; public class NoRouterIT extends ChromeBrowserTest { @Test public void applicationShouldStart() { open(); WebElement button = findElement(By.tagName("button")); button.click(); Assert.assertEquals(1, findElements(By.className("response")).size()); } }
9237f69991ca73426e2e1c25167b41f8904aaa9e
6,881
java
Java
app/src/main/java/com/codepath/apps/restclienttemplate/TimelineActivity.java
rohit-menon1/SimpleTweet
3ad5a22f65367edce9ed383c52cf36a8edfb0bd5
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/restclienttemplate/TimelineActivity.java
rohit-menon1/SimpleTweet
3ad5a22f65367edce9ed383c52cf36a8edfb0bd5
[ "MIT" ]
3
2021-03-03T08:07:43.000Z
2021-03-10T08:14:55.000Z
app/src/main/java/com/codepath/apps/restclienttemplate/TimelineActivity.java
rohit-menon1/SimpleTweet
3ad5a22f65367edce9ed383c52cf36a8edfb0bd5
[ "MIT" ]
null
null
null
35.107143
108
0.639006
998,263
package com.codepath.apps.restclienttemplate; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.codepath.apps.restclienttemplate.models.Tweet; import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler; import com.google.android.material.floatingactionbutton.FloatingActionButton; import org.json.JSONArray; import org.json.JSONException; import org.parceler.Parcels; import java.util.ArrayList; import java.util.List; import okhttp3.Headers; public class TimelineActivity extends AppCompatActivity { TwitterClient client; RecyclerView rvTweets; List<Tweet> tweets; TweetsAdapter adapter; SwipeRefreshLayout swipeContainer; EndlessRecyclerViewScrollListener scrollListener; public static final String TAG="Timeline Activity"; private final int REQUEST_CODE = 20; //FLOATING COMPOSE BUTTON IN ACTIVITY_TIMELINE.XML /*FloatingActionButton flCompose = findViewById(R.id.flCompose); flCompose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Compose icon has been selected //Navigate to compose activity Intent intent=new Intent(this,ComposeActivity.class); startActivityForResult(intent,REQUEST_CODE); } });*/ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==R.id.compose); { //Compose icon has been selected //Navigate to compose activity Intent intent=new Intent(this,ComposeActivity.class); startActivityForResult(intent,REQUEST_CODE); return true; } //return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if(requestCode==REQUEST_CODE && resultCode==RESULT_OK){ //GET DATA FROM INTENT IE TWEET OBJECT Tweet tweet=Parcels.unwrap(data.getParcelableExtra("tweet")); ///Update recycler view with the new tweet //Modify data Source tweets.add(0,tweet); //Update Adapter adapter.notifyItemInserted(0); rvTweets.smoothScrollToPosition(0); } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); client = TwitterApp.getRestClient(this); swipeContainer=findViewById(R.id.swipeContainer); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Log.i(TAG,"Fetching new Data"); populateHomeTimeline(); } }); //Find the recycler View rvTweets=findViewById(R.id.rvTweets); //Initialize the list of tweets tweets=new ArrayList<>(); adapter=new TweetsAdapter(this,tweets); LinearLayoutManager layoutManager = new LinearLayoutManager(this); //Recycler view setup:layout manager and the adapter rvTweets.setLayoutManager(layoutManager); rvTweets.setAdapter(adapter); scrollListener=new EndlessRecyclerViewScrollListener(layoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { Log.i(TAG,"onLoadMore:"+page); loadMoreData(); } }; // Adds the scroll listener to RecyclerView rvTweets.addOnScrollListener(scrollListener); populateHomeTimeline(); } private void loadMoreData() { // 1. Send an API request to retrieve appropriate paginated data client.getNextPageOfTweets(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.i(TAG,"onSuccess for loadMoreData!"+json.toString()); // 2. Deserialize and construct new model objects from the API response JSONArray jsonArray=json.jsonArray; try { List<Tweet>tweets= Tweet.fromJsonArray(jsonArray); // 3. Append the new data objects to the existing set of items inside the array of items // 4. Notify the adapter of the new items made with `notifyItemRangeInserted()` adapter.addAll(tweets); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.e(TAG,"onFailure for loadMoreData!",throwable); } },tweets.get(tweets.size()-1).id); } private void populateHomeTimeline() { client.getHomeTimeline(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Headers headers, JSON json) { Log.i(TAG,"onSuccess!"+json.toString()); JSONArray jsonArray=json.jsonArray; try { adapter.clear(); adapter.addAll(Tweet.fromJsonArray(jsonArray)); // Now we call setRefreshing(false) to signal refresh has finished swipeContainer.setRefreshing(false); } catch (JSONException e) { Log.e(TAG,"Json exception",e); e.printStackTrace(); } } @Override public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) { Log.e(TAG,"onFailure",throwable); } }); } }
9237f7a97e32b17f209437de380149ddec51dd38
35,518
java
Java
Common/src/main/java/vazkii/botania/common/entity/EntityDoppleganger.java
Siuolthepic/Botania
cd3af2db2d6ba59d34ec5d4df88093395d2c596b
[ "MIT" ]
128
2021-08-04T18:07:55.000Z
2022-03-31T00:16:14.000Z
Common/src/main/java/vazkii/botania/common/entity/EntityDoppleganger.java
Siuolthepic/Botania
cd3af2db2d6ba59d34ec5d4df88093395d2c596b
[ "MIT" ]
213
2021-08-04T07:02:42.000Z
2022-03-31T17:46:18.000Z
Common/src/main/java/vazkii/botania/common/entity/EntityDoppleganger.java
Siuolthepic/Botania
cd3af2db2d6ba59d34ec5d4df88093395d2c596b
[ "MIT" ]
47
2021-08-05T18:24:19.000Z
2022-03-31T11:26:54.000Z
32.142986
212
0.687708
998,264
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.common.entity; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.sounds.AbstractTickableSoundInstance; import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientboundAddMobPacket; import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerBossEvent; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundSource; import net.minecraft.tags.BlockTags; import net.minecraft.tags.Tag; import net.minecraft.util.*; import net.minecraft.world.BossEvent; import net.minecraft.world.Difficulty; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectCategory; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.FloatGoal; import net.minecraft.world.entity.ai.goal.LookAtPlayerGoal; import net.minecraft.world.entity.monster.WitherSkeleton; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BeaconBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.BuiltInLootTables; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import vazkii.botania.client.fx.WispParticleData; import vazkii.botania.common.advancements.DopplegangerNoArmorTrigger; import vazkii.botania.common.block.ModBlocks; import vazkii.botania.common.handler.ModSounds; import vazkii.botania.common.helper.MathHelper; import vazkii.botania.common.helper.VecHelper; import vazkii.botania.common.item.ModItems; import vazkii.botania.common.lib.ModTags; import vazkii.botania.common.proxy.IProxy; import vazkii.botania.mixin.AccessorMobEffect; import vazkii.botania.network.EffectType; import vazkii.botania.network.clientbound.PacketBotaniaEffect; import vazkii.botania.network.clientbound.PacketSpawnDoppleganger; import vazkii.botania.xplat.IXplatAbstractions; import vazkii.patchouli.api.IMultiblock; import vazkii.patchouli.api.PatchouliAPI; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; import static vazkii.botania.common.lib.ResourceLocationHelper.prefix; public class EntityDoppleganger extends Mob { public static final float ARENA_RANGE = 12F; public static final int ARENA_HEIGHT = 5; private static final int SPAWN_TICKS = 160; public static final float MAX_HP = 320F; public static final Supplier<IMultiblock> ARENA_MULTIBLOCK = Suppliers.memoize(() -> { var beaconBase = PatchouliAPI.get().predicateMatcher(Blocks.IRON_BLOCK, state -> state.is(BlockTags.BEACON_BASE_BLOCKS)); return PatchouliAPI.get().makeMultiblock( new String[][] { { "P_______P", "_________", "_________", "_________", "_________", "_________", "_________", "_________", "P_______P", }, { "_________", "_________", "_________", "_________", "____B____", "_________", "_________", "_________", "_________", }, { "_________", "_________", "_________", "___III___", "___I0I___", "___III___", "_________", "_________", "_________", } }, 'P', ModBlocks.gaiaPylon, 'B', Blocks.BEACON, 'I', beaconBase, '0', beaconBase ); }); private static final int MOB_SPAWN_START_TICKS = 20; private static final int MOB_SPAWN_END_TICKS = 80; private static final int MOB_SPAWN_BASE_TICKS = 800; private static final int MOB_SPAWN_TICKS = MOB_SPAWN_BASE_TICKS + MOB_SPAWN_START_TICKS + MOB_SPAWN_END_TICKS; private static final int MOB_SPAWN_WAVES = 10; private static final int MOB_SPAWN_WAVE_TIME = MOB_SPAWN_BASE_TICKS / MOB_SPAWN_WAVES; private static final int DAMAGE_CAP = 32; private static final String TAG_INVUL_TIME = "invulTime"; private static final String TAG_AGGRO = "aggro"; private static final String TAG_SOURCE_X = "sourceX"; private static final String TAG_SOURCE_Y = "sourceY"; private static final String TAG_SOURCE_Z = "sourcesZ"; private static final String TAG_MOB_SPAWN_TICKS = "mobSpawnTicks"; private static final String TAG_HARD_MODE = "hardMode"; private static final String TAG_PLAYER_COUNT = "playerCount"; private static final Tag.Named<Block> BLACKLIST = ModTags.Blocks.GAIA_BREAK_BLACKLIST; private static final EntityDataAccessor<Integer> INVUL_TIME = SynchedEntityData.defineId(EntityDoppleganger.class, EntityDataSerializers.INT); private static final List<BlockPos> PYLON_LOCATIONS = ImmutableList.of( new BlockPos(4, 1, 4), new BlockPos(4, 1, -4), new BlockPos(-4, 1, 4), new BlockPos(-4, 1, -4) ); private static final List<ResourceLocation> CHEATY_BLOCKS = Arrays.asList( new ResourceLocation("openblocks", "beartrap"), new ResourceLocation("thaumictinkerer", "magnet") ); private boolean spawnLandmines = false; private boolean spawnPixies = false; private boolean anyWithArmor = false; private boolean aggro = false; private int tpDelay = 0; private int mobSpawnTicks = 0; private int playerCount = 0; private boolean hardMode = false; private BlockPos source = BlockPos.ZERO; private final List<UUID> playersWhoAttacked = new ArrayList<>(); private final ServerBossEvent bossInfo = (ServerBossEvent) new ServerBossEvent(ModEntities.DOPPLEGANGER.getDescription(), BossEvent.BossBarColor.PINK, BossEvent.BossBarOverlay.PROGRESS).setCreateWorldFog(true);; private UUID bossInfoUUID = bossInfo.getId(); public Player trueKiller = null; public EntityDoppleganger(EntityType<EntityDoppleganger> type, Level world) { super(type, world); xpReward = 825; if (world.isClientSide) { IProxy.INSTANCE.addBoss(this); } } public static boolean spawn(Player player, ItemStack stack, Level world, BlockPos pos, boolean hard) { //initial checks if (!(world.getBlockEntity(pos) instanceof BeaconBlockEntity) || !isTruePlayer(player) || countGaiaGuardiansAround(world, pos) > 0) { return false; } //check difficulty if (world.getDifficulty() == Difficulty.PEACEFUL) { if (!world.isClientSide) { player.sendMessage(new TranslatableComponent("botaniamisc.peacefulNoob").withStyle(ChatFormatting.RED), Util.NIL_UUID); } return false; } //check pylons List<BlockPos> invalidPylonBlocks = checkPylons(world, pos); if (!invalidPylonBlocks.isEmpty()) { if (world.isClientSide) { warnInvalidBlocks(world, invalidPylonBlocks); } else { player.sendMessage(new TranslatableComponent("botaniamisc.needsCatalysts").withStyle(ChatFormatting.RED), Util.NIL_UUID); } return false; } //check arena shape List<BlockPos> invalidArenaBlocks = checkArena(world, pos); if (!invalidArenaBlocks.isEmpty()) { if (world.isClientSide) { warnInvalidBlocks(world, invalidArenaBlocks); } else { IXplatAbstractions.INSTANCE.sendToPlayer(player, new PacketBotaniaEffect(EffectType.ARENA_INDICATOR, pos.getX(), pos.getY(), pos.getZ())); player.sendMessage(new TranslatableComponent("botaniamisc.badArena").withStyle(ChatFormatting.RED), Util.NIL_UUID); } return false; } //all checks ok, spawn the boss if (!world.isClientSide) { stack.shrink(1); EntityDoppleganger e = ModEntities.DOPPLEGANGER.create(world); e.setPos(pos.getX() + 0.5, pos.getY() + 3, pos.getZ() + 0.5); e.setInvulTime(SPAWN_TICKS); e.setHealth(1F); e.source = pos; e.mobSpawnTicks = MOB_SPAWN_TICKS; e.hardMode = hard; int playerCount = e.getPlayersAround().size(); e.playerCount = playerCount; float healthMultiplier = 1; if (playerCount > 1) { healthMultiplier += playerCount * 0.25F; } e.getAttribute(Attributes.MAX_HEALTH).setBaseValue(MAX_HP * healthMultiplier); if (hard) { e.getAttribute(Attributes.ARMOR).setBaseValue(15); } e.playSound(ModSounds.gaiaSummon, 1F, 1F); e.finalizeSpawn((ServerLevelAccessor) world, world.getCurrentDifficultyAt(e.blockPosition()), MobSpawnType.EVENT, null, null); world.addFreshEntity(e); } return true; } private static List<BlockPos> checkPylons(Level world, BlockPos beaconPos) { List<BlockPos> invalidPylonBlocks = new ArrayList<>(); for (BlockPos coords : PYLON_LOCATIONS) { BlockPos pos_ = beaconPos.offset(coords); BlockState state = world.getBlockState(pos_); if (!state.is(ModBlocks.gaiaPylon)) { invalidPylonBlocks.add(pos_); } } return invalidPylonBlocks; } private static List<BlockPos> checkArena(Level world, BlockPos beaconPos) { List<BlockPos> trippedPositions = new ArrayList<>(); int range = (int) Math.ceil(ARENA_RANGE); BlockPos pos; for (int x = -range; x <= range; x++) { for (int z = -range; z <= range; z++) { if (Math.abs(x) == 4 && Math.abs(z) == 4 || MathHelper.pointDistancePlane(x, z, 0, 0) > ARENA_RANGE) { continue; // Ignore pylons and out of circle } boolean hasFloor = false; for (int y = -2; y <= ARENA_HEIGHT; y++) { if (x == 0 && y == 0 && z == 0) { continue; //the beacon } pos = beaconPos.offset(x, y, z); BlockState state = world.getBlockState(pos); boolean allowBlockHere = y < 0; boolean isBlockHere = !state.getCollisionShape(world, pos).isEmpty(); if (allowBlockHere && isBlockHere) //floor is here! good { hasFloor = true; } if (y == 0 && !hasFloor) //column is entirely missing floor { trippedPositions.add(pos.below()); } if (!allowBlockHere && isBlockHere && !BLACKLIST.contains(state.getBlock())) //ceiling is obstructed in this column { trippedPositions.add(pos); } } } } return trippedPositions; } private static void warnInvalidBlocks(Level world, Iterable<BlockPos> invalidPositions) { WispParticleData data = WispParticleData.wisp(0.5F, 1, 0.2F, 0.2F, 8, false); for (BlockPos pos_ : invalidPositions) { world.addParticle(data, pos_.getX() + 0.5, pos_.getY() + 0.5, pos_.getZ() + 0.5, 0, 0, 0); } } @Override protected void registerGoals() { goalSelector.addGoal(0, new FloatGoal(this)); goalSelector.addGoal(1, new LookAtPlayerGoal(this, Player.class, ARENA_RANGE * 1.5F)); } @Override protected void defineSynchedData() { super.defineSynchedData(); entityData.define(INVUL_TIME, 0); } public int getInvulTime() { return entityData.get(INVUL_TIME); } public BlockPos getSource() { return source; } public void setInvulTime(int time) { entityData.set(INVUL_TIME, time); } @Override public void addAdditionalSaveData(CompoundTag cmp) { super.addAdditionalSaveData(cmp); cmp.putInt(TAG_INVUL_TIME, getInvulTime()); cmp.putBoolean(TAG_AGGRO, aggro); cmp.putInt(TAG_MOB_SPAWN_TICKS, mobSpawnTicks); cmp.putInt(TAG_SOURCE_X, source.getX()); cmp.putInt(TAG_SOURCE_Y, source.getY()); cmp.putInt(TAG_SOURCE_Z, source.getZ()); cmp.putBoolean(TAG_HARD_MODE, hardMode); cmp.putInt(TAG_PLAYER_COUNT, playerCount); } @Override public void readAdditionalSaveData(CompoundTag cmp) { super.readAdditionalSaveData(cmp); setInvulTime(cmp.getInt(TAG_INVUL_TIME)); aggro = cmp.getBoolean(TAG_AGGRO); mobSpawnTicks = cmp.getInt(TAG_MOB_SPAWN_TICKS); int x = cmp.getInt(TAG_SOURCE_X); int y = cmp.getInt(TAG_SOURCE_Y); int z = cmp.getInt(TAG_SOURCE_Z); source = new BlockPos(x, y, z); hardMode = cmp.getBoolean(TAG_HARD_MODE); if (cmp.contains(TAG_PLAYER_COUNT)) { playerCount = cmp.getInt(TAG_PLAYER_COUNT); } else { playerCount = 1; } if (this.hasCustomName()) { this.bossInfo.setName(this.getDisplayName()); } } @Override public void setCustomName(@Nullable Component name) { super.setCustomName(name); this.bossInfo.setName(this.getDisplayName()); } @Override public void heal(float amount) { if (getInvulTime() == 0) { super.heal(amount); } } @Override public void kill() { this.setHealth(0.0F); } @Override public boolean hurt(@Nonnull DamageSource source, float amount) { Entity e = source.getEntity(); if (e instanceof Player player && isTruePlayer(e) && getInvulTime() == 0) { if (!playersWhoAttacked.contains(player.getUUID())) { playersWhoAttacked.add(player.getUUID()); } return super.hurt(source, Math.min(DAMAGE_CAP, amount)); } return false; } private static final Pattern FAKE_PLAYER_PATTERN = Pattern.compile("^(?:\\[.*]|ComputerCraft)$"); public static boolean isTruePlayer(Entity e) { if (!(e instanceof Player player)) { return false; } String name = player.getName().getString(); return !FAKE_PLAYER_PATTERN.matcher(name).matches(); } @Override protected void actuallyHurt(@Nonnull DamageSource source, float amount) { super.actuallyHurt(source, Math.min(DAMAGE_CAP, amount)); Entity attacker = source.getDirectEntity(); if (attacker != null) { Vec3 thisVector = VecHelper.fromEntityCenter(this); Vec3 playerVector = VecHelper.fromEntityCenter(attacker); Vec3 motionVector = thisVector.subtract(playerVector).normalize().scale(0.75); if (getHealth() > 0) { setDeltaMovement(-motionVector.x, 0.5, -motionVector.z); tpDelay = 4; spawnPixies = true; } } invulnerableTime = Math.max(invulnerableTime, 20); } @Override protected float getDamageAfterArmorAbsorb(DamageSource source, float damage) { return super.getDamageAfterArmorAbsorb(source, Math.min(DAMAGE_CAP, damage)); } @Override public void die(@Nonnull DamageSource source) { super.die(source); LivingEntity lastAttacker = getKillCredit(); if (!level.isClientSide) { for (UUID u : playersWhoAttacked) { Player player = level.getPlayerByUUID(u); if (!isTruePlayer(player)) { continue; } DamageSource currSource = player == lastAttacker ? source : DamageSource.playerAttack(player); if (player != lastAttacker) { // Vanilla handles this in attack code, but only for the killer CriteriaTriggers.PLAYER_KILLED_ENTITY.trigger((ServerPlayer) player, this, currSource); } if (!anyWithArmor) { DopplegangerNoArmorTrigger.INSTANCE.trigger((ServerPlayer) player, this, currSource); } } // Clear wither from nearby players for (Player player : getPlayersAround()) { if (player.getEffect(MobEffects.WITHER) != null) { player.removeEffect(MobEffects.WITHER); } } // Stop all the pixies leftover from the fight for (EntityPixie pixie : level.getEntitiesOfClass(EntityPixie.class, getArenaBB(getSource()), p -> p.isAlive() && p.getPixieType() == 1)) { pixie.spawnAnim(); pixie.discard(); } for (EntityMagicLandmine landmine : level.getEntitiesOfClass(EntityMagicLandmine.class, getArenaBB(getSource()))) { landmine.discard(); } } playSound(ModSounds.gaiaDeath, 1F, (1F + (level.random.nextFloat() - level.random.nextFloat()) * 0.2F) * 0.7F); level.addParticle(ParticleTypes.EXPLOSION_EMITTER, getX(), getY(), getZ(), 1D, 0D, 0D); } @Override public boolean removeWhenFarAway(double dist) { return false; } @Override public ResourceLocation getDefaultLootTable() { if (mobSpawnTicks > 0) { return BuiltInLootTables.EMPTY; } return prefix(hardMode ? "gaia_guardian_2" : "gaia_guardian"); } @Override protected void dropFromLootTable(@Nonnull DamageSource source, boolean wasRecentlyHit) { // Save true killer, they get extra loot if (wasRecentlyHit && isTruePlayer(source.getEntity())) { trueKiller = (Player) source.getEntity(); } // Generate loot table for every single attacking player for (UUID u : playersWhoAttacked) { Player player = level.getPlayerByUUID(u); if (!isTruePlayer(player)) { continue; } Player saveLastAttacker = lastHurtByPlayer; Vec3 savePos = position(); lastHurtByPlayer = player; // Fake attacking player as the killer // Spoof pos so drops spawn at the player setPos(player.getX(), player.getY(), player.getZ()); super.dropFromLootTable(DamageSource.playerAttack(player), wasRecentlyHit); setPos(savePos.x(), savePos.y(), savePos.z()); lastHurtByPlayer = saveLastAttacker; } trueKiller = null; } @Override public void remove(RemovalReason reason) { if (level.isClientSide) { IProxy.INSTANCE.removeBoss(this); } super.remove(reason); } public List<Player> getPlayersAround() { return level.getEntitiesOfClass(Player.class, getArenaBB(source), player -> isTruePlayer(player) && !player.isSpectator()); } private static int countGaiaGuardiansAround(Level world, BlockPos source) { List<EntityDoppleganger> l = world.getEntitiesOfClass(EntityDoppleganger.class, getArenaBB(source)); return l.size(); } @Nonnull private static AABB getArenaBB(@Nonnull BlockPos source) { double range = 15.0; return new AABB(source.getX() + 0.5 - range, source.getY() + 0.5 - range, source.getZ() + 0.5 - range, source.getX() + 0.5 + range, source.getY() + 0.5 + range, source.getZ() + 0.5 + range); } private void particles() { for (int i = 0; i < 360; i += 8) { float r = 0.6F; float g = 0F; float b = 0.2F; float m = 0.15F; float mv = 0.35F; float rad = i * (float) Math.PI / 180F; double x = source.getX() + 0.5 - Math.cos(rad) * ARENA_RANGE; double y = source.getY() + 0.5; double z = source.getZ() + 0.5 - Math.sin(rad) * ARENA_RANGE; WispParticleData data = WispParticleData.wisp(0.5F, r, g, b); level.addParticle(data, x, y, z, (float) (Math.random() - 0.5F) * m, (float) (Math.random() - 0.5F) * mv, (float) (Math.random() - 0.5F) * m); } if (getInvulTime() > 10) { Vec3 pos = VecHelper.fromEntityCenter(this).subtract(0, 0.2, 0); for (BlockPos arr : PYLON_LOCATIONS) { Vec3 pylonPos = new Vec3(source.getX() + arr.getX(), source.getY() + arr.getY(), source.getZ() + arr.getZ()); double worldTime = tickCount; worldTime /= 5; float rad = 0.75F + (float) Math.random() * 0.05F; double xp = pylonPos.x + 0.5 + Math.cos(worldTime) * rad; double zp = pylonPos.z + 0.5 + Math.sin(worldTime) * rad; Vec3 partPos = new Vec3(xp, pylonPos.y, zp); Vec3 mot = pos.subtract(partPos).scale(0.04); float r = 0.7F + (float) Math.random() * 0.3F; float g = (float) Math.random() * 0.3F; float b = 0.7F + (float) Math.random() * 0.3F; WispParticleData data = WispParticleData.wisp(0.25F + (float) Math.random() * 0.1F, r, g, b, 1); level.addParticle(data, partPos.x, partPos.y, partPos.z, 0, -(-0.075F - (float) Math.random() * 0.015F), 0); WispParticleData data1 = WispParticleData.wisp(0.4F, r, g, b); level.addParticle(data1, partPos.x, partPos.y, partPos.z, (float) mot.x, (float) mot.y, (float) mot.z); } } } private void smashBlocksAround(int centerX, int centerY, int centerZ, int radius) { for (int dx = -radius; dx <= radius; dx++) { for (int dy = -radius; dy <= radius + 1; dy++) { for (int dz = -radius; dz <= radius; dz++) { int x = centerX + dx; int y = centerY + dy; int z = centerZ + dz; BlockPos pos = new BlockPos(x, y, z); BlockState state = level.getBlockState(pos); Block block = state.getBlock(); if (state.getDestroySpeed(level, pos) == -1) { continue; } if (CHEATY_BLOCKS.contains(Registry.BLOCK.getKey(block))) { level.destroyBlock(pos, true); } else { //don't break blacklisted blocks if (BLACKLIST.contains(block)) { continue; } //don't break the floor if (y < source.getY()) { continue; } //don't break blocks in pylon columns if (Math.abs(source.getX() - x) == 4 && Math.abs(source.getZ() - z) == 4) { continue; } level.destroyBlock(pos, true); } } } } } private void clearPotions(Player player) { List<MobEffect> potionsToRemove = player.getActiveEffects().stream() .filter(effect -> effect.getDuration() < 160 && effect.isAmbient() && ((AccessorMobEffect) effect.getEffect()).getType() != MobEffectCategory.HARMFUL) .map(MobEffectInstance::getEffect) .distinct() .collect(Collectors.toList()); potionsToRemove.forEach(potion -> { player.removeEffect(potion); ((ServerLevel) level).getChunkSource().broadcastAndSend(player, new ClientboundRemoveMobEffectPacket(player.getId(), potion)); }); } private void keepInsideArena(Player player) { if (MathHelper.pointDistanceSpace(player.getX(), player.getY(), player.getZ(), source.getX() + 0.5, source.getY() + 0.5, source.getZ() + 0.5) >= ARENA_RANGE) { Vec3 sourceVector = new Vec3(source.getX() + 0.5, source.getY() + 0.5, source.getZ() + 0.5); Vec3 playerVector = VecHelper.fromEntityCenter(player); Vec3 motion = sourceVector.subtract(playerVector).normalize(); player.setDeltaMovement(motion.x, 0.2, motion.z); player.hurtMarked = true; } } private void spawnMobs(List<Player> players) { for (int pl = 0; pl < playerCount; pl++) { for (int i = 0; i < 3 + level.random.nextInt(2); i++) { Mob entity = switch (level.random.nextInt(3)) { case 0 -> { if (level.random.nextInt(hardMode ? 3 : 12) == 0) { yield EntityType.WITCH.create(level); } yield EntityType.ZOMBIE.create(level); } case 1 -> { if (level.random.nextInt(8) == 0) { yield EntityType.WITHER_SKELETON.create(level); } yield EntityType.SKELETON.create(level); } case 2 -> { if (!players.isEmpty()) { for (int j = 0; j < 1 + level.random.nextInt(hardMode ? 8 : 5); j++) { EntityPixie pixie = new EntityPixie(level); pixie.setProps(players.get(random.nextInt(players.size())), this, 1, 8); pixie.setPos(getX() + getBbWidth() / 2, getY() + 2, getZ() + getBbWidth() / 2); pixie.finalizeSpawn((ServerLevelAccessor) level, level.getCurrentDifficultyAt(pixie.blockPosition()), MobSpawnType.MOB_SUMMONED, null, null); level.addFreshEntity(pixie); } } yield null; } default -> null; }; if (entity != null) { if (!entity.fireImmune()) { entity.addEffect(new MobEffectInstance(MobEffects.FIRE_RESISTANCE, 600, 0)); } float range = 6F; entity.setPos(getX() + 0.5 + Math.random() * range - range / 2, getY() - 1, getZ() + 0.5 + Math.random() * range - range / 2); entity.finalizeSpawn((ServerLevelAccessor) level, level.getCurrentDifficultyAt(entity.blockPosition()), MobSpawnType.MOB_SUMMONED, null, null); if (entity instanceof WitherSkeleton && hardMode) { entity.setItemSlot(EquipmentSlot.MAINHAND, new ItemStack(ModItems.elementiumSword)); } level.addFreshEntity(entity); } } } } @Override public void aiStep() { super.aiStep(); int invul = getInvulTime(); if (level.isClientSide) { particles(); Player player = IProxy.INSTANCE.getClientPlayer(); if (getPlayersAround().contains(player)) { player.getAbilities().flying &= player.getAbilities().instabuild; } return; } bossInfo.setProgress(getHealth() / getMaxHealth()); if (isPassenger()) { stopRiding(); } if (level.getDifficulty() == Difficulty.PEACEFUL) { discard(); } smashBlocksAround(Mth.floor(getX()), Mth.floor(getY()), Mth.floor(getZ()), 1); List<Player> players = getPlayersAround(); if (players.isEmpty() && !level.players().isEmpty()) { discard(); } else { for (Player player : players) { for (EquipmentSlot e : EquipmentSlot.values()) { if (e.getType() == EquipmentSlot.Type.ARMOR && !player.getItemBySlot(e).isEmpty()) { anyWithArmor = true; break; } } //also see SleepingHandler if (player.isSleeping()) { player.stopSleeping(); } clearPotions(player); keepInsideArena(player); player.getAbilities().flying &= player.getAbilities().instabuild; } } if (!isAlive() || players.isEmpty()) { return; } boolean spawnMissiles = hardMode && tickCount % 15 < 4; if (invul > 0 && mobSpawnTicks == MOB_SPAWN_TICKS) { if (invul < SPAWN_TICKS) { if (invul > SPAWN_TICKS / 2 && level.random.nextInt(SPAWN_TICKS - invul + 1) == 0) { for (int i = 0; i < 2; i++) { spawnAnim(); } } } setHealth(getHealth() + (getMaxHealth() - 1F) / SPAWN_TICKS); setInvulTime(invul - 1); setDeltaMovement(getDeltaMovement().x(), 0, getDeltaMovement().z()); } else { if (aggro) { boolean dying = getHealth() / getMaxHealth() < 0.2; if (dying && mobSpawnTicks > 0) { setDeltaMovement(Vec3.ZERO); int reverseTicks = MOB_SPAWN_TICKS - mobSpawnTicks; if (reverseTicks < MOB_SPAWN_START_TICKS) { setDeltaMovement(getDeltaMovement().x(), 0.2, getDeltaMovement().z()); setInvulTime(invul + 1); } if (reverseTicks > MOB_SPAWN_START_TICKS * 2 && mobSpawnTicks > MOB_SPAWN_END_TICKS && mobSpawnTicks % MOB_SPAWN_WAVE_TIME == 0) { spawnMobs(players); if (hardMode && tickCount % 3 < 2) { for (int i = 0; i < playerCount; i++) { spawnMissile(); } spawnMissiles = false; } } mobSpawnTicks--; tpDelay = 10; } else if (tpDelay > 0) { if (invul > 0) { setInvulTime(invul - 1); } tpDelay--; if (tpDelay == 0 && getHealth() > 0) { teleportRandomly(); if (spawnLandmines) { int count = dying && hardMode ? 7 : 6; for (int i = 0; i < count; i++) { int x = source.getX() - 10 + random.nextInt(20); int y = (int) players.get(random.nextInt(players.size())).getY(); int z = source.getZ() - 10 + random.nextInt(20); EntityMagicLandmine landmine = ModEntities.MAGIC_LANDMINE.create(level); landmine.setPos(x + 0.5, y, z + 0.5); landmine.summoner = this; level.addFreshEntity(landmine); } } for (int pl = 0; pl < playerCount; pl++) { for (int i = 0; i < (spawnPixies ? level.random.nextInt(hardMode ? 6 : 3) : 1); i++) { EntityPixie pixie = new EntityPixie(level); pixie.setProps(players.get(random.nextInt(players.size())), this, 1, 8); pixie.setPos(getX() + getBbWidth() / 2, getY() + 2, getZ() + getBbWidth() / 2); pixie.finalizeSpawn((ServerLevelAccessor) level, level.getCurrentDifficultyAt(pixie.blockPosition()), MobSpawnType.MOB_SUMMONED, null, null); level.addFreshEntity(pixie); } } tpDelay = hardMode ? dying ? 35 : 45 : dying ? 40 : 60; spawnLandmines = true; spawnPixies = false; } } if (spawnMissiles) { spawnMissile(); } } else { tpDelay = 30; // Trigger first teleport aggro = true; } } } @Override public boolean canChangeDimensions() { return false; } @Override public void startSeenByPlayer(ServerPlayer player) { super.startSeenByPlayer(player); bossInfo.addPlayer(player); } @Override public void stopSeenByPlayer(ServerPlayer player) { super.stopSeenByPlayer(player); bossInfo.removePlayer(player); } @Override protected void pushEntities() { if (getInvulTime() == 0) { super.pushEntities(); } } @Override public boolean isPushable() { return super.isPushable() && getInvulTime() == 0; } private void spawnMissile() { EntityMagicMissile missile = new EntityMagicMissile(this, true); missile.setPos(getX() + (Math.random() - 0.5 * 0.1), getY() + 2.4 + (Math.random() - 0.5 * 0.1), getZ() + (Math.random() - 0.5 * 0.1)); if (missile.findTarget()) { playSound(ModSounds.missile, 1F, 0.8F + (float) Math.random() * 0.2F); level.addFreshEntity(missile); } } private void teleportRandomly() { //choose a location to teleport to double oldX = getX(), oldY = getY(), oldZ = getZ(); double newX, newY = source.getY(), newZ; int tries = 0; do { newX = source.getX() + (random.nextDouble() - .5) * ARENA_RANGE; newZ = source.getZ() + (random.nextDouble() - .5) * ARENA_RANGE; tries++; //ensure it's inside the arena ring, and not just its bounding square } while (tries < 50 && MathHelper.pointDistanceSpace(newX, newY, newZ, source.getX(), source.getY(), source.getZ()) > 12); if (tries == 50) { //failsafe: teleport to the beacon newX = source.getX() + .5; newY = source.getY() + 1.6; newZ = source.getZ() + .5; } //for low-floor arenas, ensure landing on the ground BlockPos tentativeFloorPos = new BlockPos(newX, newY - 1, newZ); if (level.getBlockState(tentativeFloorPos).getCollisionShape(level, tentativeFloorPos).isEmpty()) { newY--; } //teleport there teleportTo(newX, newY, newZ); //play sound level.playSound(null, oldX, oldY, oldZ, ModSounds.gaiaTeleport, this.getSoundSource(), 1F, 1F); this.playSound(ModSounds.gaiaTeleport, 1F, 1F); Random random = getRandom(); //spawn particles along the path int particleCount = 128; for (int i = 0; i < particleCount; ++i) { double progress = i / (double) (particleCount - 1); float vx = (random.nextFloat() - 0.5F) * 0.2F; float vy = (random.nextFloat() - 0.5F) * 0.2F; float vz = (random.nextFloat() - 0.5F) * 0.2F; double px = oldX + (newX - oldX) * progress + (random.nextDouble() - 0.5D) * getBbWidth() * 2.0D; double py = oldY + (newY - oldY) * progress + random.nextDouble() * getBbHeight(); double pz = oldZ + (newZ - oldZ) * progress + (random.nextDouble() - 0.5D) * getBbWidth() * 2.0D; level.addParticle(ParticleTypes.PORTAL, px, py, pz, vx, vy, vz); } Vec3 oldPosVec = new Vec3(oldX, oldY + getBbHeight() / 2, oldZ); Vec3 newPosVec = new Vec3(newX, newY + getBbHeight() / 2, newZ); if (oldPosVec.distanceToSqr(newPosVec) > 1) { //damage players in the path of the teleport for (Player player : getPlayersAround()) { boolean hit = player.getBoundingBox().inflate(0.25).clip(oldPosVec, newPosVec) .isPresent(); if (hit) { player.hurt(DamageSource.mobAttack(this), 6); } } //break blocks in the path of the teleport int breakSteps = (int) oldPosVec.distanceTo(newPosVec); if (breakSteps >= 2) { for (int i = 0; i < breakSteps; i++) { float progress = i / (float) (breakSteps - 1); int breakX = Mth.floor(oldX + (newX - oldX) * progress); int breakY = Mth.floor(oldY + (newY - oldY) * progress); int breakZ = Mth.floor(oldZ + (newZ - oldZ) * progress); smashBlocksAround(breakX, breakY, breakZ, 1); } } } } /* TODO 1.18 custom boss bar public ResourceLocation getBossBarTexture() { return BossBarHandler.defaultBossBar; } public Rect2i getBossBarTextureRect() { return new Rect2i(0, 0, 185, 15); } public Rect2i getBossBarHPTextureRect() { Rect2i barRect = getBossBarTextureRect(); return new Rect2i(0, barRect.getY() + barRect.getHeight(), 181, 7); } public int bossBarRenderCallback(PoseStack ms, int x, int y) { ms.pushPose(); int px = x + 160; int py = y + 12; Minecraft mc = Minecraft.getInstance(); ItemStack stack = new ItemStack(Items.PLAYER_HEAD); mc.getItemRenderer().renderGuiItem(stack, px, py); mc.font.drawShadow(ms, Integer.toString(playerCount), px + 15, py + 4, 0xFFFFFF); ms.popPose(); return 5; } public UUID getBossInfoUuid() { return bossInfoUUID; } @Nullable public ShaderHelper.BotaniaShader getBossBarShaderProgram(boolean background) { return background ? null : ShaderHelper.BotaniaShader.DOPPLEGANGER_BAR; } private ShaderCallback shaderCallback; public ShaderCallback getBossBarShaderCallback(boolean background) { if (shaderCallback == null) { shaderCallback = shader1 -> { int grainIntensityUniform = GlStateManager._glGetUniformLocation(shader1, "grainIntensity"); int hpFractUniform = GlStateManager._glGetUniformLocation(shader1, "hpFract"); float time = getInvulTime(); float grainIntensity = time > 20 ? 1F : Math.max(hardMode ? 0.5F : 0F, time / 20F); ShaderHelper.FLOAT_BUF.position(0); ShaderHelper.FLOAT_BUF.put(0, grainIntensity); RenderSystem.glUniform1(grainIntensityUniform, ShaderHelper.FLOAT_BUF); ShaderHelper.FLOAT_BUF.position(0); ShaderHelper.FLOAT_BUF.put(0, getHealth() / getMaxHealth()); RenderSystem.glUniform1(hpFractUniform, ShaderHelper.FLOAT_BUF); }; } return background ? null : shaderCallback; } */ public void readSpawnData(int playerCount, boolean hardMode, BlockPos source, UUID bossInfoUUID) { this.playerCount = playerCount; this.hardMode = hardMode; this.source = source; this.bossInfoUUID = bossInfoUUID; IProxy.INSTANCE.runOnClient(() -> () -> DopplegangerMusic.play(this)); } @Nonnull @Override public Packet<?> getAddEntityPacket() { return IXplatAbstractions.INSTANCE.toVanillaClientboundPacket( new PacketSpawnDoppleganger(new ClientboundAddMobPacket(this), playerCount, hardMode, source, bossInfoUUID)); } @Override public boolean canBeLeashed(Player player) { return false; } private static class DopplegangerMusic extends AbstractTickableSoundInstance { private final EntityDoppleganger guardian; private DopplegangerMusic(EntityDoppleganger guardian) { super(guardian.hardMode ? ModSounds.gaiaMusic2 : ModSounds.gaiaMusic1, SoundSource.RECORDS); this.guardian = guardian; this.x = guardian.getSource().getX(); this.y = guardian.getSource().getY(); this.z = guardian.getSource().getZ(); // this.repeat = true; disabled due to unknown vanilla/LWJGL bug where track glitches and repeats early } public static void play(EntityDoppleganger guardian) { Minecraft.getInstance().getSoundManager().play(new DopplegangerMusic(guardian)); } @Override public void tick() { if (!guardian.isAlive()) { stop(); } } } }
9237f7c21b2a84264dec411b794984c4f865d656
1,095
java
Java
src/main/java/io/okami101/realworld/application/user/DuplicatedEmailValidator.java
adr1enbe4udou1n/spring-boot-realworld-example-app
26fa529aad599f85e753315dae7cbee943eb81aa
[ "MIT" ]
null
null
null
src/main/java/io/okami101/realworld/application/user/DuplicatedEmailValidator.java
adr1enbe4udou1n/spring-boot-realworld-example-app
26fa529aad599f85e753315dae7cbee943eb81aa
[ "MIT" ]
null
null
null
src/main/java/io/okami101/realworld/application/user/DuplicatedEmailValidator.java
adr1enbe4udou1n/spring-boot-realworld-example-app
26fa529aad599f85e753315dae7cbee943eb81aa
[ "MIT" ]
null
null
null
32.205882
88
0.690411
998,265
package io.okami101.realworld.application.user; import io.okami101.realworld.core.user.User; import io.okami101.realworld.core.user.UserRepository; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; public class DuplicatedEmailValidator implements ConstraintValidator<DuplicatedEmailConstraint, String> { @Autowired private UserRepository userRepository; @Override public boolean isValid(String value, ConstraintValidatorContext context) { return userRepository .findByEmail(value) .map( u -> { User user = null; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof User) { user = (User) principal; } return user != null && u.getId().equals(user.getId()); }) .orElse(true); } }
9237f7de30287052235de3ee38fefca363b7ce2d
590
java
Java
hw04-logging/src/main/java/aop/ExecutorProxy.java
LoopKarma/otusDZ
6ab081724323e152f9d82e0d64ffdf6066e4b7ee
[ "Apache-2.0" ]
null
null
null
hw04-logging/src/main/java/aop/ExecutorProxy.java
LoopKarma/otusDZ
6ab081724323e152f9d82e0d64ffdf6066e4b7ee
[ "Apache-2.0" ]
6
2019-08-30T14:25:02.000Z
2022-03-31T20:35:56.000Z
hw04-logging/src/main/java/aop/ExecutorProxy.java
LoopKarma/otusDZ
6ab081724323e152f9d82e0d64ffdf6066e4b7ee
[ "Apache-2.0" ]
1
2020-05-02T13:27:16.000Z
2020-05-02T13:27:16.000Z
28.095238
72
0.69322
998,266
package aop; import annotated.TestLogging; import processor.ProxyHandler; public class ExecutorProxy { public static void main(String[] args) { executeProxyCalls(); } private static void executeProxyCalls() { TestLogging testLogging = ProxyHandler.createTestLoggingProxy(); testLogging.calculation(5, 6); testLogging.calculation(32, 0); testLogging.calculation(700, -28); testLogging.calculationWithoutLogs(5, 6); testLogging.calculationWithoutLogs(32, 0); testLogging.calculationWithoutLogs(700, -28); } }
9237f8e1d7572be78829e820c24b880cb8c9c9ca
1,896
java
Java
src/main/java/com/blakebr0/ironjetpacks/init/ModItems.java
dracnis/IronJetpacks
e724ad407b4e19a8a88593121d5a8406605576f0
[ "MIT" ]
12
2018-08-19T15:30:29.000Z
2022-02-27T09:23:42.000Z
src/main/java/com/blakebr0/ironjetpacks/init/ModItems.java
dracnis/IronJetpacks
e724ad407b4e19a8a88593121d5a8406605576f0
[ "MIT" ]
46
2018-06-12T07:36:16.000Z
2022-03-28T20:09:59.000Z
src/main/java/com/blakebr0/ironjetpacks/init/ModItems.java
dracnis/IronJetpacks
e724ad407b4e19a8a88593121d5a8406605576f0
[ "MIT" ]
9
2020-05-04T12:05:31.000Z
2022-03-20T16:33:19.000Z
49.894737
140
0.78481
998,267
package com.blakebr0.ironjetpacks.init; import com.blakebr0.cucumber.item.BaseItem; import com.blakebr0.ironjetpacks.IronJetpacks; import com.blakebr0.ironjetpacks.item.ComponentItem; import com.blakebr0.ironjetpacks.item.JetpackItem; import net.minecraft.world.item.Item; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.function.Supplier; import static com.blakebr0.ironjetpacks.IronJetpacks.CREATIVE_TAB; public final class ModItems { public static final DeferredRegister<Item> REGISTRY = DeferredRegister.create(ForgeRegistries.ITEMS, IronJetpacks.MOD_ID); public static final RegistryObject<Item> STRAP = register("strap"); public static final RegistryObject<Item> BASIC_COIL = register("basic_coil"); public static final RegistryObject<Item> ADVANCED_COIL = register("advanced_coil"); public static final RegistryObject<Item> ELITE_COIL = register("elite_coil"); public static final RegistryObject<Item> ULTIMATE_COIL = register("ultimate_coil"); public static final RegistryObject<Item> CELL = register("cell", () -> new ComponentItem("cell", p -> p.tab(CREATIVE_TAB))); public static final RegistryObject<Item> THRUSTER = register("thruster", () -> new ComponentItem("thruster", p -> p.tab(CREATIVE_TAB))); public static final RegistryObject<Item> CAPACITOR = register("capacitor", () -> new ComponentItem("capacitor", p -> p.tab(CREATIVE_TAB))); public static final RegistryObject<Item> JETPACK = register("jetpack", () -> new JetpackItem(p -> p.tab(CREATIVE_TAB))); private static RegistryObject<Item> register(String name) { return register(name, () -> new BaseItem(p -> p.tab(CREATIVE_TAB))); } private static RegistryObject<Item> register(String name, Supplier<? extends Item> item) { return REGISTRY.register(name, item); } }
9237f8fc80cd24a5fee5e514f8845fd92bd50d6b
964
java
Java
src/main/java/com/github/angelndevil2/dsee/servlet/MBeanServers.java
angelndevil2/dsee
3af9cf9dceb5618eb1691fa858d36aae48c63b1a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/angelndevil2/dsee/servlet/MBeanServers.java
angelndevil2/dsee
3af9cf9dceb5618eb1691fa858d36aae48c63b1a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/angelndevil2/dsee/servlet/MBeanServers.java
angelndevil2/dsee
3af9cf9dceb5618eb1691fa858d36aae48c63b1a
[ "Apache-2.0" ]
null
null
null
24.1
74
0.691909
998,268
package com.github.angelndevil2.dsee.servlet; import com.github.angelndevil2.dsee.Agent; import org.json.simple.JSONArray; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; /** * @since 0.0.3 * @author k, Created on 16. 2. 24. */ @Path("/mbean-servers/") public class MBeanServers { @Context private HttpServletRequest httpRequest; /** * * @return mbean server id */ @GET @Produces(MediaType.APPLICATION_JSON) @SuppressWarnings("unchecked") public Response getIds() { ArrayList<String> list = Agent.getFactory().getAllMBeanServerId(); JSONArray ret = new JSONArray(); for (String id : list) ret.add(id); return Response.status(200).entity(ret.toJSONString()).build(); } }
9237f9156c18aada9263955eddddf305fcdece5b
2,097
java
Java
OpenCVFace/app/src/main/java/com/wuqingsen/opencvface/MainActivity.java
wuqingsen/-FFmpegDemo
e0fb56d5939bc399582e590a7d87204b2625fad6
[ "MIT" ]
1
2021-12-08T14:08:33.000Z
2021-12-08T14:08:33.000Z
OpenCVFace/app/src/main/java/com/wuqingsen/opencvface/MainActivity.java
wuqingsen/-FFmpegDemo
e0fb56d5939bc399582e590a7d87204b2625fad6
[ "MIT" ]
null
null
null
OpenCVFace/app/src/main/java/com/wuqingsen/opencvface/MainActivity.java
wuqingsen/-FFmpegDemo
e0fb56d5939bc399582e590a7d87204b2625fad6
[ "MIT" ]
null
null
null
28.337838
122
0.731044
998,269
package com.wuqingsen.opencvface; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.hardware.Camera; import android.media.FaceDetector; import android.os.Bundle; import android.os.Environment; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.TextView; import com.wuqingsen.opencvface.util.CameraHelper; import com.wuqingsen.opencvface.util.Utils; import java.io.File; //wqs public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback { private OpencvJni openCvJni; private CameraHelper cameraHelper; int cameraId = Camera.CameraInfo.CAMERA_FACING_FRONT; //人脸识别 // FaceDetector faceDetector = @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); openCvJni = new OpencvJni(); SurfaceView surfaceView = findViewById(R.id.surfaceView); surfaceView.getHolder().addCallback(this); cameraHelper = new CameraHelper(cameraId); cameraHelper.setPreviewCallback(this); Utils.copyAssets(this, "lbpcascade_frontalface.xml"); } @Override protected void onResume() { super.onResume(); String path = new File(Environment.getExternalStorageDirectory(), "lbpcascade_frontalface.xml").getAbsolutePath(); cameraHelper.startPreview(); openCvJni.init(path); } public void switchCamera(View view) { } @Override public void surfaceCreated(@NonNull SurfaceHolder holder) { } @Override public void surfaceChanged(@NonNull SurfaceHolder holder, int i, int i1, int i2) { openCvJni.setSurface(holder.getSurface()); } @Override public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) { } @Override public void onPreviewFrame(byte[] data, Camera camera) { openCvJni.postData(data, CameraHelper.WIDTH, CameraHelper.HEIGHT, cameraId); } }
9237f95d3ff1cd91c18215cc2d8fb0793604750d
6,308
java
Java
openjdk11/test/langtools/tools/javadoc/6958836/Test.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
test/langtools/tools/javadoc/6958836/Test.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
test/langtools/tools/javadoc/6958836/Test.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
35.438202
91
0.554058
998,270
/* * Copyright (c) 2010, 2017, 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 6958836 8002168 * @summary javadoc should support -Xmaxerrs and -Xmaxwarns * @modules jdk.javadoc */ import java.io.*; import java.util.*; import com.sun.javadoc.DocErrorReporter; import com.sun.javadoc.RootDoc; public class Test { private static final String ERROR_MARKER = "Error-count"; private static final String WARNING_MARKER = "Warning-count"; public static void main(String... args) throws Exception { new Test().run(); } void run() throws Exception { javadoc("Errors", list(), 10, 0); javadoc("Errors", list("-Xmaxerrs", "0"), 10, 0); javadoc("Errors", list("-Xmaxerrs", "2"), 2, 0); javadoc("Errors", list("-Xmaxerrs", "4"), 4, 0); javadoc("Errors", list("-Xmaxerrs", "20"), 10, 0); javadoc("Warnings", list(), 0, 10); javadoc("Warnings", list("-Xmaxwarns", "0"), 0, 10); javadoc("Warnings", list("-Xmaxwarns", "2"), 0, 2); javadoc("Warnings", list("-Xmaxwarns", "4"), 0, 4); javadoc("Warnings", list("-Xmaxwarns", "20"), 0, 10); if (errors > 0) throw new Exception(errors + " errors occurred."); } void javadoc(String selector, List<String> testOpts, int expectErrs, int expectWarns) { System.err.println("Test " + (++count) + ": " + selector + " " + testOpts); File testOutDir = new File("test" + count); List<String> opts = new ArrayList<String>(); // Force en_US locale in lieu of something like -XDrawDiagnostics. // For some reason, this must be the first option when used. opts.addAll(list("-locale", "en_US")); opts.add(new File(System.getProperty("test.src"), Test.class.getSimpleName() + ".java").getPath()); opts.addAll(testOpts); opts.add("-gen" + selector); StringWriter errSW = new StringWriter(); PrintWriter errPW = new PrintWriter(errSW); StringWriter warnSW = new StringWriter(); PrintWriter warnPW = new PrintWriter(warnSW); StringWriter noteSW = new StringWriter(); PrintWriter notePW = new PrintWriter(noteSW); int rc = com.sun.tools.javadoc.Main.execute("javadoc", errPW, warnPW, notePW, "Test$TestDoclet", getClass().getClassLoader(), opts.toArray(new String[opts.size()])); System.err.println("rc: " + rc); errPW.close(); String errOut = errSW.toString(); System.err.println("Errors:\n" + errOut); warnPW.close(); String warnOut = warnSW.toString(); System.err.println("Warnings:\n" + warnOut); notePW.close(); String noteOut = noteSW.toString(); System.err.println("Notes:\n" + noteOut); check(errOut, ERROR_MARKER, expectErrs); check(warnOut, WARNING_MARKER, expectWarns); // requires -locale en_US } void check(String text, String expectText, int expectCount) { int foundCount = 0; for (String line: text.split("[\r\n]+")) { if (line.contains(expectText)) foundCount++; } if (foundCount != expectCount) { error("incorrect number of matches found: " + foundCount + ", expected: " + expectCount); } } private List<String> list(String... args) { return Arrays.asList(args); } void error(String msg) { System.err.println(msg); errors++; } int count; int errors; public static class TestDoclet { static boolean genErrors = false; static boolean genWarnings = false; public static boolean start(RootDoc root) { // generate 10 errors or warnings for (int i = 1 ; i <= 10 ; i++) { if (genErrors) root.printError(ERROR_MARKER + " " + i); if (genWarnings) root.printWarning(WARNING_MARKER + " " + i); } return true; } public static int optionLength(String option) { if (option == null) { throw new Error("invalid usage: "); } System.out.println("option: " + option); switch (option.trim()) { case "-genErrors": return 1; case "-genWarnings": return 1; default: return 0; } } public static boolean validOptions(String[][] options, DocErrorReporter reporter) { for (int i = 0 ; i < options.length; i++) { String opt = options[i][0].trim(); switch (opt) { case "-genErrors": genErrors = true; genWarnings = false; break; case "-genWarnings": genErrors = false; genWarnings = true; break; } } return true; } } }
9237f9a052610a5abed2257df752473a695e762f
15,620
java
Java
wtuapplication/src/main/java/com/example/wtuapplication/activity/OpenFileActivity.java
DragonCaat/shared-file
fd728a9de42ef6426c0f52c3fcb5b768dbda29c3
[ "Apache-2.0" ]
1
2020-02-20T05:56:49.000Z
2020-02-20T05:56:49.000Z
wtuapplication/src/main/java/com/example/wtuapplication/activity/OpenFileActivity.java
DragonCaat/shared-file
fd728a9de42ef6426c0f52c3fcb5b768dbda29c3
[ "Apache-2.0" ]
null
null
null
wtuapplication/src/main/java/com/example/wtuapplication/activity/OpenFileActivity.java
DragonCaat/shared-file
fd728a9de42ef6426c0f52c3fcb5b768dbda29c3
[ "Apache-2.0" ]
null
null
null
40.154242
143
0.554545
998,271
package com.example.wtuapplication.activity; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.nfc.Tag; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ListAdapter; import android.widget.Toast; import com.example.wtuapplication.R; import com.example.wtuapplication.adapter.GridViewOpenFileAdapter; import com.example.wtuapplication.adapter.GridViewShowFileAdapter; import com.example.wtuapplication.bean.Constant; import com.example.wtuapplication.utils.*; import java.io.File; import java.net.MalformedURLException; import java.util.ArrayList; import jcifs.smb.SmbException; import jcifs.smb.SmbFile; import static android.R.id.list; import static com.example.wtuapplication.R.id.btn_sendFile; public class OpenFileActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener{ private String TAG = "OpenFileActivity"; private String own_urlPath;//点击后进入下一级文件夹路径 private String fa_urlpath;//当前进入文件夹路径 private GridView mGridView_OpenFile; private Toolbar toolbar; private Context mContext; private Button mBtn_sendFile; private String mFilePath; private String fileName;//准备点击的文件夹名字 private ArrayList<String> listDir; private AlertDialog mBuilder; private ProgressDialog mDialog; private boolean flag = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_open_file); Intent intent = getIntent(); mContext = this; fa_urlpath =intent.getStringExtra("urlpath");//当前路径 mGridView_OpenFile = (GridView) findViewById(R.id.gridView_showopenFile); mGridView_OpenFile.setOnItemClickListener(this); mGridView_OpenFile.setOnItemLongClickListener(this); mBtn_sendFile = (Button) findViewById(R.id.btn_sendFile); //"smb://cj:cj@192.168.16.100/cj share"; //urlPath = "smb://cj:cj@" + mStrIp + "/cj share"; toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitleMarginStart(250); //设置toolbar栏 setSupportActionBar(toolbar); //actionBar添加按钮 ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.mipmap.back); new Thread() { @Override public void run() { try { listDir = SamFile.listDir_(fa_urlpath);//遍历当前路径 runOnUiThread(new Runnable() { @Override public void run() { GridViewOpenFileAdapter gridViewOpenFileAdapter = new GridViewOpenFileAdapter(OpenFileActivity.this, listDir); mGridView_OpenFile.setAdapter(gridViewOpenFileAdapter); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } }.start(); } mBtn_sendFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。 //intent.setType(“image/*”);//选择图片 //intent.setType(“audio/*”); //选择音频 //intent.setType("video/*"); //选择视频 (mp4 3gp 是android支持的视频格式) //intent.setType("video/*;image/*");//同时选择视频和图片 intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, Constant.REQUEST_CODE); } }); } /** * 接收来自文件activity的文件路径信息,并共享视屏 */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == Constant.REQUEST_CODE) { Uri uri = data.getData(); if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开 mFilePath = uri.getPath(); return; } if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后 mFilePath = getPath(this, uri); } else {//4.4以下下系统调用方法 mFilePath = getRealPathFromURI(uri); } //安卓6.0以上要用这个判断进行获取读取手机文件权限 if (Build.VERSION.SDK_INT >= 23) { int REQUEST_CODE_CONTACT = 101; String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; //验证是否许可权限 for (String str : permissions) { if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) { //申请权限 this.requestPermissions(permissions, REQUEST_CODE_CONTACT); return; } } } mDialog = new ProgressDialog(OpenFileActivity.this); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条 mDialog.setCancelable(true);// 设置是否可以通过点击Back键取消 mDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条 mDialog.setIcon(R.mipmap.error);// mDialog.setTitle("提示"); mDialog.setMessage("正在上传..."); // dismiss监听 mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mDialog.isShowing()) { dialog.dismiss(); } return; } }); mDialog.show(); new Thread(new Runnable() { @Override public void run() { SamFile.fileUpload(fa_urlpath, mFilePath);//在当前的路径与当前的文件夹上传文件 Log.v("dsss", "上传成功"); //刷新界面 runOnUiThread(new Runnable() { @Override public void run() { try { GridViewOpenFileAdapter gridViewOpenFileAdapter = null; gridViewOpenFileAdapter = new GridViewOpenFileAdapter(OpenFileActivity.this, SamFile.listDir_(fa_urlpath)); mGridView_OpenFile.setAdapter(gridViewOpenFileAdapter); Toast.makeText(getApplicationContext(),"上传成功",Toast.LENGTH_SHORT).show(); mDialog.dismiss(); } catch (MalformedURLException e) { e.printStackTrace(); } } }); } }) { }.start(); } } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (listDir.get(i)!=null) { fileName=listDir.get(i); if (fileName.contains(".")) { view.setClickable(false); //Toast.makeText(this,"非文件夹不能被打开",Toast.LENGTH_SHORT).show(); } else { startToOpenFileActivity(); } } } public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { if (listDir.get(i)!=null) { fileName=listDir.get(i); } DeleteDialog(); return false; } private void DeleteDialog() { mBuilder = new AlertDialog.Builder(this) .setTitle("请确认是否删除") .setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { runOnUiThread(new Runnable() { @Override public void run() { try { new SmbFile(SamFile.returnUrl_(fa_urlpath, fileName)).delete(); GridViewOpenFileAdapter gridViewOpenFileAdapter = null; gridViewOpenFileAdapter = new GridViewOpenFileAdapter(OpenFileActivity.this, SamFile.listDir_(fa_urlpath)); mGridView_OpenFile.setAdapter(gridViewOpenFileAdapter); Toast.makeText(getApplicationContext(),"删除成功",Toast.LENGTH_SHORT).show(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (SmbException e) { e.printStackTrace(); } } }); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { mBuilder.dismiss(); } }) .create(); mBuilder.show(); } private void startToOpenFileActivity() { Intent intent = new Intent(mContext, OpenFileActivity.class); own_urlPath = SamFile.returnUrl_(fa_urlpath,fileName);//已经点击了的文件夹路径 intent.putExtra("urlpath",own_urlPath); startActivity(intent); } public String getRealPathFromURI(Uri contentUri) { String res = null; String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null); if (null != cursor && cursor.moveToFirst()) { ; int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); res = cursor.getString(column_index); cursor.close(); } return res; } /* 以下代码是由于安卓版本不一样而需要添加的获得手机的文件的的路径所需要的 */ public String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[]{split[1]}; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } public String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = {column}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } public boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } /** * menu中控件的点击事件 */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); break; } return true; } }
9237fa0552137e1fba5ee33e417689b9d84a6520
4,780
java
Java
DataTier-APIs/Java-APIs/src/main/java/com/redhat/idaas/datasynthesis/models/PlatformDataStructuresEntity.java
jayfray12/DataSynthesis
878355d11e99aeb4cdcae093240a8772ca2bdf44
[ "Apache-2.0" ]
4
2021-11-20T11:12:19.000Z
2022-01-19T17:01:05.000Z
DataTier-APIs/Java-APIs/src/main/java/com/redhat/idaas/datasynthesis/models/PlatformDataStructuresEntity.java
jayfray12/DataSynthesis
878355d11e99aeb4cdcae093240a8772ca2bdf44
[ "Apache-2.0" ]
10
2021-05-17T07:29:36.000Z
2022-03-01T04:39:28.000Z
DataTier-APIs/Java-APIs/src/main/java/com/redhat/idaas/datasynthesis/models/PlatformDataStructuresEntity.java
jayfray12/DataSynthesis
878355d11e99aeb4cdcae093240a8772ca2bdf44
[ "Apache-2.0" ]
8
2021-02-05T17:28:33.000Z
2021-09-06T10:31:16.000Z
34.388489
227
0.743515
998,272
package com.redhat.idaas.datasynthesis.models; import java.sql.Timestamp; import java.util.List; import java.util.Optional; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "platform_datastructures", schema = "datasynthesis", catalog = "") public class PlatformDataStructuresEntity extends io.quarkus.hibernate.orm.panache.PanacheEntityBase { private short platformDataStructuresId; private String dataStructureName; private Timestamp createdDate; private String createdUser; private String platformDataStructuresGuid; private RefDataStatusEntity status; private RefDataApplicationEntity registeredApp; private RefDataSensitivityFlagEntity sensitivityFlag; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "PlatformDataStructuresID", nullable = false) public short getPlatformDataStructuresId() { return platformDataStructuresId; } public void setPlatformDataStructuresId(short platformDataStructuresId) { this.platformDataStructuresId = platformDataStructuresId; } @Basic @Column(name = "DataStructureName", nullable = true, length = 50) public String getDataStructureName() { return dataStructureName; } public void setDataStructureName(String dataStructureName) { this.dataStructureName = dataStructureName; } @Basic @Column(name = "CreatedDate", nullable = true) public Timestamp getCreatedDate() { return createdDate; } public void setCreatedDate(Timestamp createdDate) { this.createdDate = createdDate; } @Basic @Column(name = "CreatedUser", nullable = true, length = 20) public String getCreatedUser() { return createdUser; } public void setCreatedUser(String createdUser) { this.createdUser = createdUser; } @Basic @Column(name = "PlatformDataStructuresGUID", nullable = true, length = 38) public String getPlatformDataStructuresGuid() { return platformDataStructuresGuid; } public void setPlatformDataStructuresGuid(String platformDataStructuresGuid) { this.platformDataStructuresGuid = platformDataStructuresGuid; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; PlatformDataStructuresEntity other = (PlatformDataStructuresEntity) o; return java.util.Objects.equals(platformDataStructuresId, other.platformDataStructuresId) && java.util.Objects.equals(dataStructureName, other.dataStructureName) && java.util.Objects.equals(createdDate, other.createdDate) && java.util.Objects.equals(createdUser, other.createdUser) && java.util.Objects.equals(platformDataStructuresGuid, other.platformDataStructuresGuid) && java.util.Objects.equals(status, other.status) && java.util.Objects.equals(registeredApp, other.registeredApp) && java.util.Objects.equals(sensitivityFlag, other.sensitivityFlag); } @Override public int hashCode() { return java.util.Objects.hash(platformDataStructuresId, dataStructureName, createdDate, createdUser, platformDataStructuresGuid, status, registeredApp, sensitivityFlag); } @ManyToOne @JoinColumn(name = "SensitivityFlagID", referencedColumnName = "SensitiveFlagID") public RefDataSensitivityFlagEntity getSensitivityFlag() { return sensitivityFlag; } public void setSensitivityFlag(RefDataSensitivityFlagEntity sensitivityFlag) { this.sensitivityFlag = sensitivityFlag; } @ManyToOne @JoinColumn(name = "StatusID", referencedColumnName = "StatusID") public RefDataStatusEntity getStatus() { return status; } public void setStatus(RefDataStatusEntity status) { this.status = status; } @ManyToOne @JoinColumn(name = "RegisteredApp", referencedColumnName = "AppGUID") public RefDataApplicationEntity getRegisteredApp() { return registeredApp; } public void setRegisteredApp(RefDataApplicationEntity registeredApp) { this.registeredApp = registeredApp; } public static List<PlatformDataStructuresEntity> findByStatusId(Short statusId) { return find("status", new RefDataStatusEntity(statusId)).list(); } public static Optional<PlatformDataStructuresEntity> findByName(String dataStructureName) { return find("dataStructureName", dataStructureName).firstResultOptional(); } }
9237fb6cd1302f3586e0e9bca878865e1cf2346d
1,155
java
Java
sample/src/main/java/com/urbanairship/sample/preference/NamedUserPreference.java
urbanairship/android-library
1d33d5d07730827d3a59afc473aac1ebf1061e5f
[ "Apache-2.0" ]
96
2016-06-08T12:52:47.000Z
2022-02-05T20:24:55.000Z
sample/src/main/java/com/urbanairship/sample/preference/NamedUserPreference.java
urbanairship/android-library
1d33d5d07730827d3a59afc473aac1ebf1061e5f
[ "Apache-2.0" ]
202
2016-08-11T18:17:28.000Z
2022-03-18T12:28:38.000Z
sample/src/main/java/com/urbanairship/sample/preference/NamedUserPreference.java
urbanairship/android-library
1d33d5d07730827d3a59afc473aac1ebf1061e5f
[ "Apache-2.0" ]
119
2016-06-06T15:54:24.000Z
2022-02-21T06:58:36.000Z
23.1
69
0.670996
998,273
/* Copyright Airship and Contributors */ package com.urbanairship.sample.preference; import android.content.Context; import android.util.AttributeSet; import com.urbanairship.UAirship; import com.urbanairship.util.UAStringUtil; import androidx.preference.EditTextPreference; /** * DialogPreference to set the named user. */ public class NamedUserPreference extends EditTextPreference { public NamedUserPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setText(String text) { String namedUser = UAStringUtil.isEmpty(text) ? null : text; if (UAStringUtil.isEmpty(text)) { UAirship.shared().getContact().reset(); } else { UAirship.shared().getContact().identify(text); } notifyChanged(); } @Override public String getText() { return UAirship.shared().getContact().getNamedUserId(); } @Override public String getSummary() { return UAirship.shared().getContact().getNamedUserId(); } @Override protected boolean shouldPersist() { return false; } }
9237fc2bdc7ac630475f65ac884f99b2ff0ef933
477
java
Java
src/main/java/everyos.browser.spec/everyos/browser/spec/javadom/imp/JDCustomEvent.java
JasonTheKitten/Webicity-Java
2795293fd81d50da0708071fa97ff73a7fedbe79
[ "MIT" ]
27
2020-12-06T00:46:10.000Z
2022-02-28T18:34:55.000Z
src/main/java/everyos.browser.spec/everyos/browser/spec/javadom/imp/JDCustomEvent.java
JasonTheKitten/Webicity-Java
2795293fd81d50da0708071fa97ff73a7fedbe79
[ "MIT" ]
1
2021-07-13T17:42:02.000Z
2021-07-14T04:49:01.000Z
src/main/java/everyos.browser.spec/everyos/browser/spec/javadom/imp/JDCustomEvent.java
JasonTheKitten/Webicity-Java
2795293fd81d50da0708071fa97ff73a7fedbe79
[ "MIT" ]
3
2021-07-01T16:03:31.000Z
2021-07-13T05:37:58.000Z
23.85
96
0.737945
998,274
package everyos.browser.spec.javadom.imp; import everyos.browser.spec.javadom.intf.CustomEvent; public class JDCustomEvent extends JDEvent implements CustomEvent { private Object detail; @Override public Object getDetail() { return detail; } @Override public void initCustomEvent(String type, boolean bubbles, boolean cancelable, Object detail) { if (getDispatch()) return; initialize(type, bubbles, cancelable); this.detail = detail; } }
9237fd5e0c95c753f3c69963e6f3ac659da14495
862
java
Java
src/main/java/net/fabricmc/loader/game/GameProviders.java
OverlordsIII/fabric-loader
337994c489966654315c86b2af5b7f3affe64a99
[ "Apache-2.0" ]
2
2020-11-19T01:50:49.000Z
2020-12-16T20:50:42.000Z
src/main/java/net/fabricmc/loader/game/GameProviders.java
OverlordsIII/fabric-loader
337994c489966654315c86b2af5b7f3affe64a99
[ "Apache-2.0" ]
null
null
null
src/main/java/net/fabricmc/loader/game/GameProviders.java
OverlordsIII/fabric-loader
337994c489966654315c86b2af5b7f3affe64a99
[ "Apache-2.0" ]
1
2021-04-26T09:59:03.000Z
2021-04-26T09:59:03.000Z
29.724138
75
0.74826
998,275
/* * Copyright 2016 FabricMC * * 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 net.fabricmc.loader.game; import java.util.Collections; import java.util.List; public final class GameProviders { private GameProviders() { } public static List<GameProvider> create() { return Collections.singletonList(new MinecraftGameProvider()); } }
9237fd8cedfecab39c4f150d7618fd6a3bb54b40
3,919
java
Java
common/src/main/java/us/myles/ViaVersion/util/ListWrapper.java
akemin-dayo/ViaVersion
16c929050df1b025c6ad9ba0f4e78ea09ca3d76e
[ "MIT" ]
3
2020-02-08T14:26:52.000Z
2020-08-07T17:11:34.000Z
common/src/main/java/us/myles/ViaVersion/util/ListWrapper.java
akemin-dayo/ViaVersion
16c929050df1b025c6ad9ba0f4e78ea09ca3d76e
[ "MIT" ]
1
2020-07-09T19:34:28.000Z
2020-07-09T19:34:30.000Z
common/src/main/java/us/myles/ViaVersion/util/ListWrapper.java
akemin-dayo/ViaVersion
16c929050df1b025c6ad9ba0f4e78ea09ca3d76e
[ "MIT" ]
2
2019-02-06T21:50:06.000Z
2020-07-21T07:28:18.000Z
20.201031
57
0.536106
998,276
package us.myles.ViaVersion.util; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * @deprecated scary */ @Deprecated public abstract class ListWrapper implements List { private final List list; public ListWrapper(List inputList) { this.list = inputList; } public abstract void handleAdd(Object o); public List getOriginalList() { return list; } @Override public int size() { synchronized (this) { return this.list.size(); } } @Override public boolean isEmpty() { synchronized (this) { return this.list.isEmpty(); } } @Override public boolean contains(Object o) { synchronized (this) { return this.list.contains(o); } } @Override public Iterator iterator() { synchronized (this) { return listIterator(); } } @Override public Object[] toArray() { synchronized (this) { return this.list.toArray(); } } @Override public boolean add(Object o) { handleAdd(o); synchronized (this) { return this.list.add(o); } } @Override public boolean remove(Object o) { synchronized (this) { return this.list.remove(o); } } @Override public boolean addAll(Collection c) { for (Object o : c) { handleAdd(o); } synchronized (this) { return this.list.addAll(c); } } @Override public boolean addAll(int index, Collection c) { for (Object o : c) { handleAdd(o); } synchronized (this) { return this.list.addAll(index, c); } } @Override public void clear() { synchronized (this) { this.list.clear(); } } @Override public Object get(int index) { synchronized (this) { return this.list.get(index); } } @Override public Object set(int index, Object element) { synchronized (this) { return this.list.set(index, element); } } @Override public void add(int index, Object element) { synchronized (this) { this.list.add(index, element); } } @Override public Object remove(int index) { synchronized (this) { return this.list.remove(index); } } @Override public int indexOf(Object o) { synchronized (this) { return this.list.indexOf(o); } } @Override public int lastIndexOf(Object o) { synchronized (this) { return this.list.lastIndexOf(o); } } @Override public ListIterator listIterator() { synchronized (this) { return this.list.listIterator(); } } @Override public ListIterator listIterator(int index) { synchronized (this) { return this.list.listIterator(index); } } @Override public List subList(int fromIndex, int toIndex) { synchronized (this) { return this.list.subList(fromIndex, toIndex); } } @Override public boolean retainAll(Collection c) { synchronized (this) { return this.list.retainAll(c); } } @Override public boolean removeAll(Collection c) { synchronized (this) { return this.list.removeAll(c); } } @Override public boolean containsAll(Collection c) { synchronized (this) { return this.list.containsAll(c); } } @Override public Object[] toArray(Object[] a) { synchronized (this) { return this.list.toArray(a); } } }
9237fff3751925638742f6a091328343468f6cd4
2,819
java
Java
src/main/java/com/hierynomus/msfscc/fsctl/FsCtlPipeWaitRequest.java
kardashov/smbj
5c42b8fe64c371f50a5c56a3c521db6e06292fd7
[ "Apache-2.0" ]
509
2016-02-22T19:37:58.000Z
2022-03-25T07:12:39.000Z
src/main/java/com/hierynomus/msfscc/fsctl/FsCtlPipeWaitRequest.java
kardashov/smbj
5c42b8fe64c371f50a5c56a3c521db6e06292fd7
[ "Apache-2.0" ]
646
2016-04-15T08:07:40.000Z
2022-03-29T09:31:01.000Z
src/main/java/com/hierynomus/msfscc/fsctl/FsCtlPipeWaitRequest.java
kardashov/smbj
5c42b8fe64c371f50a5c56a3c521db6e06292fd7
[ "Apache-2.0" ]
180
2016-04-13T02:47:41.000Z
2022-03-18T05:53:24.000Z
34.802469
116
0.684995
998,277
/* * Copyright (C)2016 - SMBJ Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hierynomus.msfscc.fsctl; import com.hierynomus.protocol.commons.Charsets; import com.hierynomus.protocol.commons.buffer.Buffer; import java.util.concurrent.TimeUnit; /** * [MS-FSCC] 2.3.29 FSCTL_PIPE_WAIT Request */ public class FsCtlPipeWaitRequest { private final TimeUnit timeoutUnit; private String name; private long timeout; private boolean timeoutSpecified; public FsCtlPipeWaitRequest(String name, long timeout, TimeUnit timeoutUnit, boolean timeoutSpecified) { this.name = name; this.timeout = timeout; this.timeoutUnit = timeoutUnit; this.timeoutSpecified = timeoutSpecified; } public String getName() { return name; } public long getTimeout() { return timeout; } public TimeUnit getTimeoutUnit() { return timeoutUnit; } public void write(Buffer<?> buffer) { // Timeout (8 bytes): A 64-bit signed integer that specifies the maximum amount of time, in units of // 100 milliseconds, that the function can wait for an instance of the named pipe to be available. buffer.putUInt64(timeoutSpecified ? timeoutUnit.toMillis(timeout) / 100L : 0L); // NameLength (4 bytes): A 32-bit unsigned integer that specifies the size, in bytes, of the named pipe Name // field. int nameLengthPos = buffer.wpos(); buffer.putUInt32(0); // TimeoutSpecified (1 byte): A Boolean (section 2.1.8) value that specifies whether or not the Timeout // parameter will be ignored. buffer.putBoolean(timeoutSpecified); // Padding (1 byte): The client SHOULD set this field to 0x00, and the server MUST ignore it. buffer.putByte((byte) 0); // Name (variable): A Unicode string that contains the name of the named pipe. Name MUST not include the // "\pipe\", so if the operation was on \\server\pipe\pipename, the name would be "pipename". long nameStartPos = buffer.wpos(); buffer.putString(name, Charsets.UTF_16); int endPos = buffer.wpos(); buffer.wpos(nameLengthPos); buffer.putUInt32(endPos - nameStartPos); buffer.wpos(endPos); } }
92380072657dc3f373bf42709105290fd351b196
4,471
java
Java
src/main/java/am/filesystem/VolumeVisitor.java
marco-schmidt/am
50e0ffbef3a870a3883ec6c387f49376c05e325c
[ "Apache-2.0" ]
1
2019-11-27T03:46:53.000Z
2019-11-27T03:46:53.000Z
src/main/java/am/filesystem/VolumeVisitor.java
marco-schmidt/am
50e0ffbef3a870a3883ec6c387f49376c05e325c
[ "Apache-2.0" ]
180
2019-06-27T16:26:28.000Z
2022-03-30T19:03:03.000Z
src/main/java/am/filesystem/VolumeVisitor.java
marco-schmidt/am
50e0ffbef3a870a3883ec6c387f49376c05e325c
[ "Apache-2.0" ]
1
2019-05-08T20:21:51.000Z
2019-05-08T20:21:51.000Z
29.032468
99
0.697383
998,278
/* * Copyright 2019, 2020, 2021 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 am.filesystem; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Date; import java.util.Set; import java.util.Stack; import org.slf4j.LoggerFactory; import am.app.AppConfig; import am.filesystem.model.Directory; import am.filesystem.model.File; /** * Visit all files and directories in a volume, an abstraction for a directory tree. */ public class VolumeVisitor extends SimpleFileVisitor<Path> { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(VolumeScanner.class); private final VolumeScanner scanner; private final AppConfig config; private final Stack<Directory> dirStack; private long numDirectories; private long numFiles; private long numBytes; private final Set<String> ignoreFileNames; public VolumeVisitor(final VolumeScanner scanner, final AppConfig config) { dirStack = new Stack<Directory>(); this.scanner = scanner; this.config = config; ignoreFileNames = config.getIgnoreFileNames(); } @Override public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) throws IOException { final Path fileName = path.getFileName(); final String name = fileName == null ? null : fileName.toString(); if (config.getIgnoreDirNames().contains(name)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(config.msg("scanner.debug.skipping_ignored", path.toAbsolutePath(), name)); } return FileVisitResult.SKIP_SUBTREE; } if (LOGGER.isTraceEnabled()) { LOGGER.trace(config.msg("scanner.trace.enter", path.toAbsolutePath())); } Directory dir; if (dirStack.isEmpty()) { dir = new Directory(); dir.setName(""); scanner.setRootDirectory(dir, path.toAbsolutePath()); } else { dir = scanner.addDirectory(path); final Directory parent = dirStack.peek(); parent.add(dir); } dirStack.push(dir); numDirectories++; return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (LOGGER.isTraceEnabled()) { LOGGER.trace(config.msg("scanner.trace.file", file.toAbsolutePath())); } final Directory dir = dirStack.peek(); if (dir != null) { final java.io.File fileSystemFile = file.toFile(); final Path fileName = file.getFileName(); final String name = fileName == null ? fileSystemFile.getName() : fileName.toString(); if (ignoreFileNames.contains(name)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace(config.msg("scanner.trace.skip_file", file.toAbsolutePath())); } return FileVisitResult.CONTINUE; } final File model = new File(); final long length = fileSystemFile.length(); model.setByteSize(Long.valueOf(length)); numBytes += length; model.setName(name); model.setLastModified(new Date(fileSystemFile.lastModified())); dir.add(model); } numFiles++; return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return super.visitFileFailed(file, exc); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (LOGGER.isTraceEnabled()) { LOGGER.trace(config.msg("scanner.trace.exit", dir.toAbsolutePath())); } dirStack.pop(); return FileVisitResult.CONTINUE; } public long getNumDirectories() { return numDirectories; } public long getNumFiles() { return numFiles; } public long getNumBytes() { return numBytes; } }
92380131bc31c933c5909cb5fdb9ab41fee9844a
6,607
java
Java
oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/metric/MetricStatisticsProviderTest.java
tripodsan/jackrabbit-oak
b8f8f81353de5637b76fa68ee50ba14857672593
[ "Apache-2.0" ]
null
null
null
oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/metric/MetricStatisticsProviderTest.java
tripodsan/jackrabbit-oak
b8f8f81353de5637b76fa68ee50ba14857672593
[ "Apache-2.0" ]
10
2020-03-04T21:42:31.000Z
2022-01-21T23:17:15.000Z
oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/metric/MetricStatisticsProviderTest.java
tripodsan/jackrabbit-oak
b8f8f81353de5637b76fa68ee50ba14857672593
[ "Apache-2.0" ]
null
null
null
40.533742
138
0.743151
998,279
/* * 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.jackrabbit.oak.plugins.metric; import java.lang.management.ManagementFactory; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.Query; import javax.management.QueryExp; import com.codahale.metrics.JmxReporter; import org.apache.jackrabbit.api.stats.RepositoryStatistics.Type; import org.apache.jackrabbit.oak.stats.CounterStats; import org.apache.jackrabbit.oak.stats.HistogramStats; import org.apache.jackrabbit.oak.stats.MeterStats; import org.apache.jackrabbit.oak.stats.NoopStats; import org.apache.jackrabbit.oak.stats.SimpleStats; import org.apache.jackrabbit.oak.stats.StatsOptions; import org.apache.jackrabbit.oak.stats.TimerStats; import org.junit.After; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class MetricStatisticsProviderTest { private MBeanServer server = ManagementFactory.getPlatformMBeanServer(); private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); private MetricStatisticsProvider statsProvider = new MetricStatisticsProvider(server, executorService); @Test public void basicSetup() throws Exception { //By default avg counters would be configured. So check if they are //configured assertEquals(1, statsProvider.getRegistry().getMeters().size()); assertEquals(1, statsProvider.getRegistry().getTimers().size()); assertNotNull(statsProvider.getStats()); assertEquals(statsProvider.getRegistry().getMetrics().size(), getMetricMbeans().size()); statsProvider.close(); assertEquals(0, getMetricMbeans().size()); } @Test public void meter() throws Exception { MeterStats meterStats = statsProvider.getMeter("test", StatsOptions.DEFAULT); assertNotNull(meterStats); assertNotNull(statsProvider.getRegistry().getMeters().containsKey("test")); assertTrue(((CompositeStats) meterStats).isMeter()); } @Test public void counter() throws Exception { CounterStats counterStats = statsProvider.getCounterStats("test", StatsOptions.DEFAULT); assertNotNull(counterStats); assertNotNull(statsProvider.getRegistry().getCounters().containsKey("test")); assertTrue(((CompositeStats) counterStats).isCounter()); } @Test public void timer() throws Exception { TimerStats timerStats = statsProvider.getTimer("test", StatsOptions.DEFAULT); assertNotNull(timerStats); assertNotNull(statsProvider.getRegistry().getTimers().containsKey("test")); assertTrue(((CompositeStats) timerStats).isTimer()); } @Test public void histogram() throws Exception { HistogramStats histoStats = statsProvider.getHistogram("test", StatsOptions.DEFAULT); assertNotNull(histoStats); assertNotNull(statsProvider.getRegistry().getHistograms().containsKey("test")); assertTrue(((CompositeStats) histoStats).isHistogram()); } @Test public void timeSeriesIntegration() throws Exception { MeterStats meterStats = statsProvider.getMeter(Type.SESSION_COUNT.name(), StatsOptions.DEFAULT); meterStats.mark(5); assertEquals(5, statsProvider.getRepoStats().getCounter(Type.SESSION_COUNT).get()); } @Test public void jmxNaming() throws Exception { TimerStats timerStats = statsProvider.getTimer("hello", StatsOptions.DEFAULT); assertNotNull(server.getObjectInstance(new ObjectName("org.apache.jackrabbit.oak:type=Metrics,name=hello"))); } @Test public void noopMeter() throws Exception { assertInstanceOf(statsProvider.getTimer(Type.SESSION_READ_DURATION.name(), StatsOptions.TIME_SERIES_ONLY), SimpleStats.class); assertNotEquals(statsProvider.getMeter(Type.OBSERVATION_EVENT_COUNTER.name(), StatsOptions.TIME_SERIES_ONLY), NoopStats.INSTANCE); } @Test public void statsOptions_MetricOnly() throws Exception{ assertInstanceOf(statsProvider.getTimer("fooTimer", StatsOptions.METRICS_ONLY), TimerImpl.class); assertInstanceOf(statsProvider.getCounterStats("fooCounter", StatsOptions.METRICS_ONLY), CounterImpl.class); assertInstanceOf(statsProvider.getMeter("fooMeter", StatsOptions.METRICS_ONLY), MeterImpl.class); assertInstanceOf(statsProvider.getHistogram("fooHisto", StatsOptions.METRICS_ONLY), HistogramImpl.class); } @Test public void statsOptions_TimeSeriesOnly() throws Exception{ assertInstanceOf(statsProvider.getTimer("fooTimer", StatsOptions.TIME_SERIES_ONLY), SimpleStats.class); } @Test public void statsOptions_Default() throws Exception{ assertInstanceOf(statsProvider.getTimer("fooTimer", StatsOptions.DEFAULT), CompositeStats.class); } @After public void cleanup() { statsProvider.close(); executorService.shutdownNow(); } private Set<ObjectInstance> getMetricMbeans() throws MalformedObjectNameException { QueryExp q = Query.isInstanceOf(Query.value(JmxReporter.MetricMBean.class.getName())); return server.queryMBeans(new ObjectName("org.apache.jackrabbit.oak:*"), q); } private void assertInstanceOf(Object o, Class<?> clazz){ if (!clazz.isInstance(o)){ fail(String.format("%s is not an instance of %s", o.getClass(), clazz)); } } }
92380170022a404158bdbbd173f17ce321784cf8
523
java
Java
src/gdlactivity/service/GithubService.java
GDLActivity/rxjava-demo
5cbaeff9f639aedec96cafd0dc1764e88db9665f
[ "MIT" ]
1
2017-02-09T17:35:21.000Z
2017-02-09T17:35:21.000Z
src/gdlactivity/service/GithubService.java
GDLActivity/rxjava-demo
5cbaeff9f639aedec96cafd0dc1764e88db9665f
[ "MIT" ]
null
null
null
src/gdlactivity/service/GithubService.java
GDLActivity/rxjava-demo
5cbaeff9f639aedec96cafd0dc1764e88db9665f
[ "MIT" ]
null
null
null
21.791667
70
0.715105
998,280
package gdlactivity.service; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; import java.util.List; /** * Created by nacho on 08/02/17. */ public interface GithubService { public static final String BASE_URL = "https://api.github.com/"; @GET("users") Observable<List<Profile>> getUsers(@Query("since") int since); @GET("users/{user}/followers") Observable<List<Profile>> getFollowers(@Path("user") String user); }
923801a35d0c5bf9462991b24e4b23a0759589e3
1,836
java
Java
app/src/main/java/com/nadershamma/apps/androidfunwithflags/LoginActivityMCLB.java
LeninMC/prueba2_Lenin_Moposita_Crespo
4224880ce80fd44e6c0043486a2422d94011a388
[ "MIT" ]
null
null
null
app/src/main/java/com/nadershamma/apps/androidfunwithflags/LoginActivityMCLB.java
LeninMC/prueba2_Lenin_Moposita_Crespo
4224880ce80fd44e6c0043486a2422d94011a388
[ "MIT" ]
null
null
null
app/src/main/java/com/nadershamma/apps/androidfunwithflags/LoginActivityMCLB.java
LeninMC/prueba2_Lenin_Moposita_Crespo
4224880ce80fd44e6c0043486a2422d94011a388
[ "MIT" ]
null
null
null
34.490566
99
0.66849
998,281
package com.nadershamma.apps.androidfunwithflags; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.Locale; public class LoginActivityMCLB extends AppCompatActivity { private EditText etCorreo; private EditText etContraseña; private Button btnAceptar; private String user1 = "lyhxr@example.com"; private String user2 = "hzdkv@example.com"; private String user1pass = "lenin123"; private String user2pass = "bryan123"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_mclb); etCorreo = findViewById(R.id.txtCorreo); etContraseña = findViewById(R.id.txtContraseña); btnAceptar = findViewById(R.id.btnAceptar); } public void onClicAceptar(View view) { String user = etCorreo.getText().toString(); String password = etContraseña.getText().toString(); //nombre.toUpperCase(Locale.ROOT); if (!user.matches("") && !password.matches("") ) { if ((user.matches("lyhxr@example.com") && password.matches("lenin123")) || (user.matches("hzdkv@example.com") && password.matches("bryan123"))){ Intent intent = new Intent(this, MainActivityFragmentMCLB.class); intent.putExtra("key_user",user); startActivity(intent); }else { Toast.makeText(this, "Correo o contraseña erroneos ", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Correo y contraseña son obligatorios", Toast.LENGTH_LONG).show(); } } }
923801ef9be904a4f6cae3bcee8ffe7a2e0ed783
6,508
java
Java
src/main/java/difflib/Delta.java
dnaumenko/java-diff-utils
8c716471bf85f0c9c013856768a89d769dd9f8b6
[ "Apache-1.1" ]
88
2016-02-28T11:35:44.000Z
2021-12-01T13:19:32.000Z
src/main/java/difflib/Delta.java
dnaumenko/java-diff-utils
8c716471bf85f0c9c013856768a89d769dd9f8b6
[ "Apache-1.1" ]
6
2016-02-28T11:18:08.000Z
2018-02-15T14:08:11.000Z
src/main/java/difflib/Delta.java
dnaumenko/java-diff-utils
8c716471bf85f0c9c013856768a89d769dd9f8b6
[ "Apache-1.1" ]
41
2016-07-19T07:56:44.000Z
2021-08-12T02:29:42.000Z
33.076142
84
0.6283
998,282
/* * SPDX-License-Identifier: Apache-1.1 * * ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. * Copyright (c) 1996-2006 Juancarlo Añez * Copyright (c) 2010 Dmitry Naumenko (upchh@example.com) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowledgement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgement may appear in the software itself, * if and wherever such third-party acknowledgements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ychag@example.com. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package difflib; import java.util.*; /** * Describes the delta between original and revised texts. * * @author <a href="upchh@example.com">Dmitry Naumenko</a> * @param T The type of the compared elements in the 'lines'. */ public abstract class Delta<T> { /** The original chunk. */ private Chunk<T> original; /** The revised chunk. */ private Chunk<T> revised; /** * Specifies the type of the delta. * */ public enum TYPE { /** A change in the original. */ CHANGE, /** A delete from the original. */ DELETE, /** An insert into the original. */ INSERT } /** * Construct the delta for original and revised chunks * * @param original Chunk describing the original text. Must not be {@code null}. * @param revised Chunk describing the revised text. Must not be {@code null}. */ public Delta(Chunk<T> original, Chunk<T> revised) { if (original == null) { throw new IllegalArgumentException("original must not be null"); } if (revised == null) { throw new IllegalArgumentException("revised must not be null"); } this.original = original; this.revised = revised; } /** * Verifies that this delta can be used to patch the given text. * * @param target the text to patch. * @throws PatchFailedException if the patch cannot be applied. */ public abstract void verify(List<T> target) throws PatchFailedException; /** * Applies this delta as the patch for a given target * * @param target the given target * @throws PatchFailedException */ public abstract void applyTo(List<T> target) throws PatchFailedException; /** * Cancel this delta for a given revised text. The action is opposite to * patch. * * @param target the given revised text */ public abstract void restore(List<T> target); /** * Returns the type of delta * @return the type enum */ public abstract TYPE getType(); /** * @return The Chunk describing the original text. */ public Chunk<T> getOriginal() { return original; } /** * @param original The Chunk describing the original text to set. */ public void setOriginal(Chunk<T> original) { this.original = original; } /** * @return The Chunk describing the revised text. */ public Chunk<T> getRevised() { return revised; } /** * @param revised The Chunk describing the revised text to set. */ public void setRevised(Chunk<T> revised) { this.revised = revised; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((original == null) ? 0 : original.hashCode()); result = prime * result + ((revised == null) ? 0 : revised.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Delta<T> other = (Delta) obj; if (original == null) { if (other.original != null) return false; } else if (!original.equals(other.original)) return false; if (revised == null) { if (other.revised != null) return false; } else if (!revised.equals(other.revised)) return false; return true; } }
9238023604241c01b5dbe2e166c4b70b65709507
2,038
java
Java
proguard/shrink/ShortestUsageMark.java
CoOwner/VisualPvP
c92d1dcf40a812787e32e8a21d6462b57e755b99
[ "MIT" ]
null
null
null
proguard/shrink/ShortestUsageMark.java
CoOwner/VisualPvP
c92d1dcf40a812787e32e8a21d6462b57e755b99
[ "MIT" ]
null
null
null
proguard/shrink/ShortestUsageMark.java
CoOwner/VisualPvP
c92d1dcf40a812787e32e8a21d6462b57e755b99
[ "MIT" ]
null
null
null
11.259669
177
0.635427
998,283
package proguard.shrink; import proguard.classfile.Clazz; import proguard.classfile.Member; import proguard.classfile.visitor.ClassVisitor; import proguard.classfile.visitor.MemberVisitor; final class ShortestUsageMark { private final boolean certain; private final String reason; private final int depth; private Clazz clazz; private Member member; public ShortestUsageMark(String reason) { certain = true; this.reason = reason; depth = 0; } public ShortestUsageMark(ShortestUsageMark previousUsageMark, String reason, int cost, Clazz clazz) { this(previousUsageMark, reason, cost, clazz, null); } public ShortestUsageMark(ShortestUsageMark previousUsageMark, String reason, int cost, Clazz clazz, Member member) { certain = true; this.reason = reason; depth += cost; this.clazz = clazz; this.member = member; } public ShortestUsageMark(ShortestUsageMark otherUsageMark, boolean certain) { this.certain = certain; reason = reason; depth = depth; clazz = clazz; member = member; } public boolean isCertain() { return certain; } public String getReason() { return reason; } public boolean isShorter(ShortestUsageMark otherUsageMark) { return depth < depth; } public boolean isCausedBy(Clazz clazz) { return clazz.equals(this.clazz); } public void acceptClassVisitor(ClassVisitor classVisitor) { if ((clazz != null) && (member == null)) { clazz.accept(classVisitor); } } public void acceptMemberVisitor(MemberVisitor memberVisitor) { if ((clazz != null) && (member != null)) { member.accept(clazz, memberVisitor); } } public String toString() { return "certain=" + certain + ", depth=" + depth + ": " + reason + (clazz != null ? clazz.getName() : "(none)") + ": " + (member != null ? member.getName(clazz) : "(none)"); } }
923803b87f815ad91400df030faf6b905743281c
1,700
java
Java
redis/redis-core/src/test/java/com/ctrip/xpipe/redis/core/protocal/cmd/pubsub/CrdtPublishCommandTest.java
coral-cloud/x-pipe
d4ad1d9039a83f55439b69ae7d6954171002fa39
[ "Apache-2.0" ]
1,652
2016-04-18T10:34:30.000Z
2022-03-30T06:15:35.000Z
redis/redis-core/src/test/java/com/ctrip/xpipe/redis/core/protocal/cmd/pubsub/CrdtPublishCommandTest.java
coral-cloud/x-pipe
d4ad1d9039a83f55439b69ae7d6954171002fa39
[ "Apache-2.0" ]
342
2016-07-27T10:38:01.000Z
2022-03-31T11:11:46.000Z
redis/redis-core/src/test/java/com/ctrip/xpipe/redis/core/protocal/cmd/pubsub/CrdtPublishCommandTest.java
coral-cloud/x-pipe
d4ad1d9039a83f55439b69ae7d6954171002fa39
[ "Apache-2.0" ]
492
2016-04-25T05:14:10.000Z
2022-03-16T01:40:38.000Z
33.333333
150
0.737647
998,284
package com.ctrip.xpipe.redis.core.protocal.cmd.pubsub; import com.ctrip.xpipe.AbstractTest; import com.ctrip.xpipe.api.command.CommandFuture; import com.ctrip.xpipe.api.command.CommandFutureListener; import com.ctrip.xpipe.api.pool.SimpleObjectPool; import com.ctrip.xpipe.endpoint.DefaultEndPoint; import com.ctrip.xpipe.netty.commands.NettyClient; import com.ctrip.xpipe.simpleserver.Server; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; public class CrdtPublishCommandTest extends AbstractTest { Server redis; private static final String testChannel = "test"; private static final String testMessage = "hello"; @Before public void setupCrdtPublishCommandTest() throws Exception { redis = startServer(":0\r\n"); } @After public void afterCrdtPublishCommandTest() throws Exception { if (null != redis) redis.stop(); } @Test public void testPublish() throws Exception { SimpleObjectPool<NettyClient> clientPool = getXpipeNettyClientKeyedObjectPool().getKeyPool(new DefaultEndPoint("127.0.0.1", redis.getPort())); PublishCommand crdtPublishCommand = new CRDTPublishCommand(clientPool, scheduled, 2000, testChannel, testMessage); AtomicBoolean pubSuccess = new AtomicBoolean(false); crdtPublishCommand.execute(executors).addListener(new CommandFutureListener<Object>() { public void operationComplete(CommandFuture<Object> commandFuture) throws Exception { pubSuccess.set(commandFuture.isSuccess()); } }); waitConditionUntilTimeOut(pubSuccess::get, 3000); } }
9238044c110df4f10e4cbbab1de753016d6b5ed3
7,446
java
Java
components/camel-xmpp/src/generated/java/org/apache/camel/component/xmpp/XmppEndpointConfigurer.java
zycon/camel
c0ac6c0139cc7fe4f54d3b8944c29bb3c187f80b
[ "Apache-2.0" ]
1
2021-04-02T18:51:33.000Z
2021-04-02T18:51:33.000Z
components/camel-xmpp/src/generated/java/org/apache/camel/component/xmpp/XmppEndpointConfigurer.java
zycon/camel
c0ac6c0139cc7fe4f54d3b8944c29bb3c187f80b
[ "Apache-2.0" ]
1
2020-10-17T05:32:06.000Z
2020-10-17T05:32:06.000Z
components/camel-xmpp/src/generated/java/org/apache/camel/component/xmpp/XmppEndpointConfigurer.java
zycon/camel
c0ac6c0139cc7fe4f54d3b8944c29bb3c187f80b
[ "Apache-2.0" ]
null
null
null
54.75
161
0.704539
998,285
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.xmpp; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class XmppEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("host", java.lang.String.class); map.put("port", int.class); map.put("participant", java.lang.String.class); map.put("login", boolean.class); map.put("nickname", java.lang.String.class); map.put("pubsub", boolean.class); map.put("room", java.lang.String.class); map.put("serviceName", java.lang.String.class); map.put("testConnectionOnStartup", boolean.class); map.put("createAccount", boolean.class); map.put("resource", java.lang.String.class); map.put("bridgeErrorHandler", boolean.class); map.put("connectionPollDelay", int.class); map.put("doc", boolean.class); map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class); map.put("exchangePattern", org.apache.camel.ExchangePattern.class); map.put("lazyStartProducer", boolean.class); map.put("basicPropertyBinding", boolean.class); map.put("connectionConfig", org.jivesoftware.smack.ConnectionConfiguration.class); map.put("synchronous", boolean.class); map.put("headerFilterStrategy", org.apache.camel.spi.HeaderFilterStrategy.class); map.put("password", java.lang.String.class); map.put("roomPassword", java.lang.String.class); map.put("user", java.lang.String.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { XmppEndpoint target = (XmppEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "connectionconfig": case "connectionConfig": target.setConnectionConfig(property(camelContext, org.jivesoftware.smack.ConnectionConfiguration.class, value)); return true; case "connectionpolldelay": case "connectionPollDelay": target.setConnectionPollDelay(property(camelContext, int.class, value)); return true; case "createaccount": case "createAccount": target.setCreateAccount(property(camelContext, boolean.class, value)); return true; case "doc": target.setDoc(property(camelContext, boolean.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "headerfilterstrategy": case "headerFilterStrategy": target.setHeaderFilterStrategy(property(camelContext, org.apache.camel.spi.HeaderFilterStrategy.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "login": target.setLogin(property(camelContext, boolean.class, value)); return true; case "nickname": target.setNickname(property(camelContext, java.lang.String.class, value)); return true; case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true; case "pubsub": target.setPubsub(property(camelContext, boolean.class, value)); return true; case "resource": target.setResource(property(camelContext, java.lang.String.class, value)); return true; case "room": target.setRoom(property(camelContext, java.lang.String.class, value)); return true; case "roompassword": case "roomPassword": target.setRoomPassword(property(camelContext, java.lang.String.class, value)); return true; case "servicename": case "serviceName": target.setServiceName(property(camelContext, java.lang.String.class, value)); return true; case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true; case "testconnectiononstartup": case "testConnectionOnStartup": target.setTestConnectionOnStartup(property(camelContext, boolean.class, value)); return true; case "user": target.setUser(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { XmppEndpoint target = (XmppEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": return target.isBasicPropertyBinding(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "connectionconfig": case "connectionConfig": return target.getConnectionConfig(); case "connectionpolldelay": case "connectionPollDelay": return target.getConnectionPollDelay(); case "createaccount": case "createAccount": return target.isCreateAccount(); case "doc": return target.isDoc(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "headerfilterstrategy": case "headerFilterStrategy": return target.getHeaderFilterStrategy(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "login": return target.isLogin(); case "nickname": return target.getNickname(); case "password": return target.getPassword(); case "pubsub": return target.isPubsub(); case "resource": return target.getResource(); case "room": return target.getRoom(); case "roompassword": case "roomPassword": return target.getRoomPassword(); case "servicename": case "serviceName": return target.getServiceName(); case "synchronous": return target.isSynchronous(); case "testconnectiononstartup": case "testConnectionOnStartup": return target.isTestConnectionOnStartup(); case "user": return target.getUser(); default: return null; } } }
923804e715717be9f474f685590b8eba873bfc67
733
java
Java
src/main/java/com/igrejaibc/sgi/util/Utils.java
IBC-Connect/api-sgi
4bfda5d50b3d576848609fa53b13ff66f3b6392f
[ "MIT" ]
null
null
null
src/main/java/com/igrejaibc/sgi/util/Utils.java
IBC-Connect/api-sgi
4bfda5d50b3d576848609fa53b13ff66f3b6392f
[ "MIT" ]
null
null
null
src/main/java/com/igrejaibc/sgi/util/Utils.java
IBC-Connect/api-sgi
4bfda5d50b3d576848609fa53b13ff66f3b6392f
[ "MIT" ]
null
null
null
30.541667
88
0.680764
998,286
package com.igrejaibc.sgi.util; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.logging.Level; import java.util.logging.Logger; public class Utils { private static final Logger LOGGER = Logger.getLogger(Utils.class.getName()); public static String converterDataFormatoBR(String dataBanco) { try { DateTimeFormatter formato = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate data = LocalDate.parse(dataBanco); return formato.format(data); } catch (Exception e) { LOGGER.log(Level.WARNING, e.getMessage()); throw new RuntimeException("Erro ao tentar converter o formado da data", e); } } }
9238057363ff98f51b08cf0b5ec26f03d699b852
2,038
java
Java
core/src/games/stendhal/client/PerceptionListenerImpl.java
zonesgame/StendhalArcClient
70d9c37d1b4112349e4dbabc3206204b4446d6d0
[ "Apache-2.0" ]
1
2021-07-09T05:49:05.000Z
2021-07-09T05:49:05.000Z
core/src/games/stendhal/client/PerceptionListenerImpl.java
zonesgame/StendhalArcClient
70d9c37d1b4112349e4dbabc3206204b4446d6d0
[ "Apache-2.0" ]
null
null
null
core/src/games/stendhal/client/PerceptionListenerImpl.java
zonesgame/StendhalArcClient
70d9c37d1b4112349e4dbabc3206204b4446d6d0
[ "Apache-2.0" ]
2
2021-12-08T18:33:26.000Z
2022-01-06T23:46:55.000Z
26.467532
92
0.55054
998,287
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.client; import marauroa.client.net.IPerceptionListener; import marauroa.common.game.RPObject; import marauroa.common.net.message.MessageS2CPerception; public abstract class PerceptionListenerImpl implements IPerceptionListener { @Override public boolean onAdded(final RPObject object) { return false; } @Override public boolean onClear() { return false; } @Override public boolean onDeleted(final RPObject object) { return false; } @Override public void onException(final Exception exception, final MessageS2CPerception perception) { } @Override public boolean onModifiedAdded(final RPObject object, final RPObject changes) { return false; } @Override public boolean onModifiedDeleted(final RPObject object, final RPObject changes) { return false; } @Override public boolean onMyRPObject(final RPObject added, final RPObject deleted) { return false; } @Override public void onPerceptionBegin(final byte type, final int timestamp) { } @Override public void onPerceptionEnd(final byte type, final int timestamp) { } @Override public void onSynced() { } @Override public void onUnsynced() { } }
923806c32a33373338ea884e8ece6e0672ae49d0
4,848
java
Java
taotao-cloud-dfs/taotao-cloud-dfs-biz/src/main/java/com/taotao/cloud/dfs/biz/controller/FileController.java
moutainhigh/taotao-cloud-parent
2f50734c0514ef23dccc7c2baea065740dace943
[ "Apache-2.0" ]
null
null
null
taotao-cloud-dfs/taotao-cloud-dfs-biz/src/main/java/com/taotao/cloud/dfs/biz/controller/FileController.java
moutainhigh/taotao-cloud-parent
2f50734c0514ef23dccc7c2baea065740dace943
[ "Apache-2.0" ]
null
null
null
taotao-cloud-dfs/taotao-cloud-dfs-biz/src/main/java/com/taotao/cloud/dfs/biz/controller/FileController.java
moutainhigh/taotao-cloud-parent
2f50734c0514ef23dccc7c2baea065740dace943
[ "Apache-2.0" ]
1
2021-03-24T09:12:16.000Z
2021-03-24T09:12:16.000Z
38.784
163
0.737211
998,288
package com.taotao.cloud.dfs.biz.controller; import com.taotao.cloud.common.exception.BusinessException; import com.taotao.cloud.core.model.Result; import com.taotao.cloud.dfs.api.vo.FileVO; import com.taotao.cloud.dfs.api.vo.UploadFileVO; import com.taotao.cloud.dfs.biz.entity.File; import com.taotao.cloud.dfs.biz.mapper.FileMapper; import com.taotao.cloud.dfs.biz.service.FileService; import com.taotao.cloud.log.annotation.RequestOperateLog; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.CollectionUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * 文件管理API * * @author dengtao * @date 2020/11/12 17:42 * @since v1.0 */ @Validated @RestController @AllArgsConstructor @RequestMapping("/file") @Api(value = "文件管理API", tags = {"文件管理API"}) public class FileController { private final FileService fileService; @ApiOperation("上传单个文件") @RequestOperateLog(description = "上传单个文件") @PreAuthorize("hasAuthority('file:upload')") @PostMapping(value = "/upload", headers = "content-type=multipart/form-data") public Result<UploadFileVO> upload(@RequestPart("file") MultipartFile file) { if (file.isEmpty()) { throw new BusinessException("文件不能为空"); } File upload = fileService.upload(file); UploadFileVO result = UploadFileVO.builder().id(upload.getId()).url(upload.getUrl()).build(); return Result.succeed(result); } @ApiOperation("上传多个文件") @RequestOperateLog(description = "上传多个文件") @PreAuthorize("hasAuthority('file:multiple:upload')") @PostMapping(value = "/multiple/upload", headers = "content-type=multipart/form-data") public Result<List<UploadFileVO>> uploadMultipleFiles(@RequestPart("files") MultipartFile[] files) { if (files.length == 0) { throw new BusinessException("文件不能为空"); } List<File> uploads = Arrays.stream(files) .map(fileService::upload) .collect(Collectors.toList()); if (!CollectionUtils.isEmpty(uploads)) { List<UploadFileVO> result = uploads.stream().map(upload -> UploadFileVO.builder().id(upload.getId()).url(upload.getUrl()).build()).collect(Collectors.toList()); return Result.succeed(result); } throw new BusinessException("文件上传失败"); } @ApiOperation("根据id查询文件信息") @RequestOperateLog(description = "根据id查询文件信息") @PreAuthorize("hasAuthority('file:info:id')") @GetMapping("/info/id/{id:[0-9]*}") public Result<FileVO> findFileById(@PathVariable(value = "id") Long id) { File file = fileService.findFileById(id); FileVO vo = FileMapper.INSTANCE.fileToFileVO(file); return Result.succeed(vo); } // // @ApiOperation(value = "根据文件名删除oss上的文件", notes = "根据文件名删除oss上的文件") // @ApiImplicitParams({ // @ApiImplicitParam(name = "token", value = "登录授权码", required = true, paramType = "header", dataType = "String"), // @ApiImplicitParam(name = "fileName", value = "路径名称", required = true, dataType = "String", // example = "robot/2019/04/28/1556429167175766.jpg"), // }) // @PostMapping("file/delete") // public Result<Object> delete(@RequestParam("fileName") String fileName) { // return fileUploadService.delete(fileName); // } // // @ApiOperation(value = "查询oss上的所有文件", notes = "查询oss上的所有文件") // @ApiImplicitParams({ // @ApiImplicitParam(name = "token", value = "登录授权码", required = true, paramType = "header", dataType = "String"), // }) // @GetMapping("file/list") // public Result<List<OSSObjectSummary>> list() { // return fileUploadService.list(); // } // // @ApiOperation(value = "根据文件名下载oss上的文件", notes = "根据文件名下载oss上的文件") // @ApiImplicitParams({ // @ApiImplicitParam(name = "token", value = "登录授权码", required = true, paramType = "header", dataType = "String"), // @ApiImplicitParam(name = "fileName", value = "路径名称", required = true, dataType = "String", // example = "robot/2019/04/28/1556429167175766.jpg"), // }) // @GetMapping("file/download") // public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException { // //通知浏览器以附件形式下载 // response.setHeader("Content-Disposition", // "attachment;filename=" + new String(objectName.getBytes(), StandardCharsets.ISO_8859_1)); // fileUploadService.exportOssFile(response.getOutputStream(), objectName); // } }
923806daab1901710e32c65c462e166f4e3716ee
2,698
java
Java
src/main/java/com/fishercoder/solutions/_1387.java
tthapa1972/LeetCode
3a894a1ff63ea16fd405043417fedda89bd80e78
[ "Apache-2.0" ]
2
2020-05-24T21:29:07.000Z
2020-08-01T16:38:59.000Z
src/main/java/com/fishercoder/solutions/_1387.java
harshitrai17152/Leetcode
786564c50ad643fe77066b1a571461257ee85b0e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/fishercoder/solutions/_1387.java
harshitrai17152/Leetcode
786564c50ad643fe77066b1a571461257ee85b0e
[ "Apache-2.0" ]
5
2020-09-29T13:32:12.000Z
2021-10-04T15:43:05.000Z
35.038961
214
0.55745
998,289
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 1387. Sort Integers by The Power Value * * The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: * if x is even then x = x / 2 * if x is odd then x = 3 * x + 1 * * For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). * Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order. * Return the k-th integer in the range [lo, hi] sorted by the power value. * Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in 32 bit signed integer. * * Example 1: * Input: lo = 12, hi = 15, k = 2 * Output: 13 * Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) * The power of 13 is 9 * The power of 14 is 17 * The power of 15 is 17 * The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. * Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15. * * Example 2: * Input: lo = 1, hi = 1, k = 1 * Output: 1 * * Example 3: * Input: lo = 7, hi = 11, k = 4 * Output: 7 * Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. * The interval sorted by power is [8, 10, 11, 7, 9]. * The fourth number in the sorted array is 7. * * Example 4: * Input: lo = 10, hi = 20, k = 5 * Output: 13 * * Example 5: * Input: lo = 1, hi = 1000, k = 777 * Output: 570 * * Constraints: * 1 <= lo <= hi <= 1000 * 1 <= k <= hi - lo + 1 * */ public class _1387 { public static class Solution1 { public int getKth(int lo, int hi, int k) { List<int[]> power = new ArrayList<>(); for (int i = lo; i <= hi; i++) { power.add(new int[]{getSteps(i), i}); } Collections.sort(power, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); return power.get(k - 1)[1]; } private int getSteps(int number) { int steps = 0; while (number != 1) { if (number % 2 == 0) { number /= 2; } else { number = 3 * number + 1; } steps++; } return steps; } } }
923807533e5348d377fca5ed11692d484ddbc017
1,039
java
Java
src/main/java/software/committed/rejux/impl/SimpleState.java
commitd/rejux
cf52122ae674d8024f56013fc0a533e5bea41379
[ "Apache-2.0" ]
null
null
null
src/main/java/software/committed/rejux/impl/SimpleState.java
commitd/rejux
cf52122ae674d8024f56013fc0a533e5bea41379
[ "Apache-2.0" ]
null
null
null
src/main/java/software/committed/rejux/impl/SimpleState.java
commitd/rejux
cf52122ae674d8024f56013fc0a533e5bea41379
[ "Apache-2.0" ]
null
null
null
30.558824
90
0.783446
998,290
package software.committed.rejux.impl; import java.util.List; import software.committed.rejux.interfaces.ApplyMiddleware; import software.committed.rejux.interfaces.Dispatcher; import software.committed.rejux.interfaces.Middleware; import software.committed.rejux.interfaces.SettableState; import software.committed.rejux.utils.MiddlewareUtils; public class SimpleState<S> extends AbstractSubscribableState<S> implements SettableState<S>, ApplyMiddleware<S> { private final List<Middleware<? super S>> middleware; public SimpleState(final Class<S> clazz, final S initial, final List<Middleware<? super S>> middleware) { super(clazz, initial); this.middleware = middleware; } @Override public synchronized boolean setState(final S newState) { return super.setState(newState); } @Override public Dispatcher applyMiddleware(final Dispatcher firstDispatcher, final Dispatcher lastDispatcher) { return MiddlewareUtils.createChain(firstDispatcher, this, middleware, lastDispatcher); } }
923807e011cccbf4a058f10e4dadaa8f095046c9
11,860
java
Java
src/main/java/org/apache/sysml/hops/globalopt/gdfgraph/GraphBuilder.java
dusenberrymw/incubator-systemml
2cee9bb9f5d8ad43759e747397ba517b0675a7d3
[ "Apache-2.0" ]
6
2018-08-09T09:32:30.000Z
2021-06-24T20:34:54.000Z
src/main/java/org/apache/sysml/hops/globalopt/gdfgraph/GraphBuilder.java
dusenberrymw/incubator-systemml
2cee9bb9f5d8ad43759e747397ba517b0675a7d3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/sysml/hops/globalopt/gdfgraph/GraphBuilder.java
dusenberrymw/incubator-systemml
2cee9bb9f5d8ad43759e747397ba517b0675a7d3
[ "Apache-2.0" ]
3
2017-07-10T14:44:04.000Z
2019-12-06T01:16:48.000Z
39.401993
179
0.725801
998,291
/* * 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.sysml.hops.globalopt.gdfgraph; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; import org.apache.sysml.hops.DataOp; import org.apache.sysml.hops.Hop; import org.apache.sysml.hops.Hop.DataOpTypes; import org.apache.sysml.hops.globalopt.Summary; import org.apache.sysml.hops.HopsException; import org.apache.sysml.parser.ForStatementBlock; import org.apache.sysml.parser.IfStatementBlock; import org.apache.sysml.parser.StatementBlock; import org.apache.sysml.parser.WhileStatementBlock; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.controlprogram.ForProgramBlock; import org.apache.sysml.runtime.controlprogram.FunctionProgramBlock; import org.apache.sysml.runtime.controlprogram.IfProgramBlock; import org.apache.sysml.runtime.controlprogram.Program; import org.apache.sysml.runtime.controlprogram.ProgramBlock; import org.apache.sysml.runtime.controlprogram.WhileProgramBlock; import org.apache.sysml.runtime.controlprogram.parfor.stat.Timing; import org.apache.sysml.utils.Explain; /** * GENERAL 'GDF GRAPH' STRUCTURE, by MB: * 1) Each hop is represented by an GDFNode * 2) Each loop is represented by a structured GDFLoopNode * 3) Transient Read/Write connections are represented via CrossBlockNodes, * a) type PLAIN: single input crossblocknode represents unconditional data flow * b) type MERGE: two inputs crossblocknode represent conditional data flow merge * * In detail, the graph builder essentially does a single pass over the entire program * and constructs the global data flow graph bottom up. We create crossblocknodes for * every transient write, loop nodes for for/while programblocks, and crossblocknodes * after every if programblock. * */ public class GraphBuilder { private static final boolean IGNORE_UNBOUND_UPDATED_VARS = true; public static GDFGraph constructGlobalDataFlowGraph( Program prog, Summary summary ) throws DMLRuntimeException, HopsException { Timing time = new Timing(true); HashMap<String, GDFNode> roots = new HashMap<>(); for( ProgramBlock pb : prog.getProgramBlocks() ) constructGDFGraph( pb, roots ); //create GDF graph root nodes ArrayList<GDFNode> ret = new ArrayList<>(); for( GDFNode root : roots.values() ) if( !(root instanceof GDFCrossBlockNode) ) ret.add(root); //create GDF graph GDFGraph graph = new GDFGraph(prog, ret); summary.setTimeGDFGraph(time.stop()); return graph; } @SuppressWarnings("unchecked") private static void constructGDFGraph( ProgramBlock pb, HashMap<String, GDFNode> roots ) throws DMLRuntimeException, HopsException { if (pb instanceof FunctionProgramBlock ) { throw new DMLRuntimeException("FunctionProgramBlocks not implemented yet."); } else if (pb instanceof WhileProgramBlock) { WhileProgramBlock wpb = (WhileProgramBlock) pb; WhileStatementBlock wsb = (WhileStatementBlock) pb.getStatementBlock(); //construct predicate node (conceptually sequence of from/to/incr) GDFNode pred = constructGDFGraph(wsb.getPredicateHops(), wpb, new HashMap<Long, GDFNode>(), roots); HashMap<String,GDFNode> inputs = constructLoopInputNodes(wpb, wsb, roots); HashMap<String,GDFNode> lroots = (HashMap<String, GDFNode>) inputs.clone(); //process childs blocks for( ProgramBlock pbc : wpb.getChildBlocks() ) constructGDFGraph(pbc, lroots); HashMap<String,GDFNode> outputs = constructLoopOutputNodes(wsb, lroots); GDFLoopNode lnode = new GDFLoopNode(wpb, pred, inputs, outputs ); //construct crossblock nodes constructLoopOutputCrossBlockNodes(wsb, lnode, outputs, roots, wpb); } else if (pb instanceof IfProgramBlock) { IfProgramBlock ipb = (IfProgramBlock) pb; IfStatementBlock isb = (IfStatementBlock) pb.getStatementBlock(); //construct predicate if( isb.getPredicateHops()!=null ) { Hop pred = isb.getPredicateHops(); roots.put(pred.getName(), constructGDFGraph(pred, ipb, new HashMap<Long,GDFNode>(), roots)); } //construct if and else branch separately HashMap<String,GDFNode> ifRoots = (HashMap<String, GDFNode>) roots.clone(); HashMap<String,GDFNode> elseRoots = (HashMap<String, GDFNode>) roots.clone(); for( ProgramBlock pbc : ipb.getChildBlocksIfBody() ) constructGDFGraph(pbc, ifRoots); if( ipb.getChildBlocksElseBody()!=null ) for( ProgramBlock pbc : ipb.getChildBlocksElseBody() ) constructGDFGraph(pbc, elseRoots); //merge data flow roots (if no else, elseRoots refer to original roots) reconcileMergeIfProgramBlockOutputs(ifRoots, elseRoots, roots, ipb); } else if (pb instanceof ForProgramBlock) //incl parfor { ForProgramBlock fpb = (ForProgramBlock) pb; ForStatementBlock fsb = (ForStatementBlock)pb.getStatementBlock(); //construct predicate node (conceptually sequence of from/to/incr) GDFNode pred = constructForPredicateNode(fpb, fsb, roots); HashMap<String,GDFNode> inputs = constructLoopInputNodes(fpb, fsb, roots); HashMap<String,GDFNode> lroots = (HashMap<String, GDFNode>) inputs.clone(); //process childs blocks for( ProgramBlock pbc : fpb.getChildBlocks() ) constructGDFGraph(pbc, lroots); HashMap<String,GDFNode> outputs = constructLoopOutputNodes(fsb, lroots); GDFLoopNode lnode = new GDFLoopNode(fpb, pred, inputs, outputs ); //construct crossblock nodes constructLoopOutputCrossBlockNodes(fsb, lnode, outputs, roots, fpb); } else //last-level program block { StatementBlock sb = pb.getStatementBlock(); ArrayList<Hop> hops = sb.getHops(); if( hops != null ) { //create new local memo structure for local dag HashMap<Long, GDFNode> lmemo = new HashMap<>(); for( Hop hop : hops ) { //recursively construct GDF graph for hop dag root GDFNode root = constructGDFGraph(hop, pb, lmemo, roots); if( root == null ) throw new HopsException( "GDFGraphBuilder: failed to constuct dag root for: "+Explain.explain(hop) ); //create cross block nodes for all transient writes if( hop instanceof DataOp && ((DataOp)hop).getDataOpType()==DataOpTypes.TRANSIENTWRITE ) root = new GDFCrossBlockNode(hop, pb, root, hop.getName()); //add GDF root node to global roots roots.put(hop.getName(), root); } } } } private static GDFNode constructGDFGraph( Hop hop, ProgramBlock pb, HashMap<Long, GDFNode> lmemo, HashMap<String, GDFNode> roots ) { if( lmemo.containsKey(hop.getHopID()) ) return lmemo.get(hop.getHopID()); //process childs recursively first ArrayList<GDFNode> inputs = new ArrayList<>(); for( Hop c : hop.getInput() ) inputs.add( constructGDFGraph(c, pb, lmemo, roots) ); //connect transient reads to existing roots of data flow graph if( hop instanceof DataOp && ((DataOp)hop).getDataOpType()==DataOpTypes.TRANSIENTREAD ){ inputs.add(roots.get(hop.getName())); } //add current hop GDFNode gnode = new GDFNode(hop, pb, inputs); //add GDF node of updated variables to global roots (necessary for loops, where updated local //variables might never be bound to their logical variables names if( !IGNORE_UNBOUND_UPDATED_VARS ) { //NOTE: currently disabled because unnecessary, if no transientwrite by definition included in other transientwrite if( pb.getStatementBlock()!=null && pb.getStatementBlock().variablesUpdated().containsVariable(hop.getName()) ) { roots.put(hop.getName(), gnode); } } //memoize current node lmemo.put(hop.getHopID(), gnode); return gnode; } private static GDFNode constructForPredicateNode(ForProgramBlock fpb, ForStatementBlock fsb, HashMap<String, GDFNode> roots) { HashMap<Long, GDFNode> memo = new HashMap<>(); GDFNode from = (fsb.getFromHops()!=null)? constructGDFGraph(fsb.getFromHops(), fpb, memo, roots) : null; GDFNode to = (fsb.getToHops()!=null)? constructGDFGraph(fsb.getToHops(), fpb, memo, roots) : null; GDFNode incr = (fsb.getIncrementHops()!=null)? constructGDFGraph(fsb.getIncrementHops(), fpb, memo, roots) : null; ArrayList<GDFNode> inputs = new ArrayList<>(); inputs.add(from); inputs.add(to); inputs.add(incr); //TODO for predicates GDFNode pred = new GDFNode(null, fpb, inputs ); return pred; } private static HashMap<String, GDFNode> constructLoopInputNodes( ProgramBlock fpb, StatementBlock fsb, HashMap<String, GDFNode> roots ) throws DMLRuntimeException { HashMap<String, GDFNode> ret = new HashMap<>(); Set<String> invars = fsb.variablesRead().getVariableNames(); for( String var : invars ) { if( fsb.liveIn().containsVariable(var) ) { GDFNode node = roots.get(var); if( node == null ) throw new DMLRuntimeException("GDFGraphBuilder: Non-existing input node for variable: "+var); ret.put(var, node); } } return ret; } private static HashMap<String, GDFNode> constructLoopOutputNodes( StatementBlock fsb, HashMap<String, GDFNode> roots ) throws HopsException { HashMap<String, GDFNode> ret = new HashMap<>(); Set<String> outvars = fsb.variablesUpdated().getVariableNames(); for( String var : outvars ) { GDFNode node = roots.get(var); //handle non-existing nodes if( node == null ) { if( !IGNORE_UNBOUND_UPDATED_VARS ) throw new HopsException( "GDFGraphBuilder: failed to constuct loop output for variable: "+var ); else continue; //skip unbound updated variables } //add existing node to loop outputs ret.put(var, node); } return ret; } private static void reconcileMergeIfProgramBlockOutputs( HashMap<String, GDFNode> ifRoots, HashMap<String, GDFNode> elseRoots, HashMap<String, GDFNode> roots, IfProgramBlock pb ) { //merge same variable names, different data //( incl add new vars from if branch if node2==null) for( Entry<String, GDFNode> e : ifRoots.entrySet() ){ GDFNode node1 = e.getValue(); GDFNode node2 = elseRoots.get(e.getKey()); //original or new if( node1 != node2 ) node1 = new GDFCrossBlockNode(null, pb, node1, node2, e.getKey() ); roots.put(e.getKey(), node1); } //add new vars from else branch for( Entry<String, GDFNode> e : elseRoots.entrySet() ){ if( !ifRoots.containsKey(e.getKey()) ) roots.put(e.getKey(), e.getValue()); } } private static void constructLoopOutputCrossBlockNodes(StatementBlock sb, GDFLoopNode loop, HashMap<String, GDFNode> loutputs, HashMap<String, GDFNode> roots, ProgramBlock pb) { //iterate over all output (updated) variables for( Entry<String,GDFNode> e : loutputs.entrySet() ) { //create crossblocknode, if updated variable is also in liveout if( sb.liveOut().containsVariable(e.getKey()) ) { GDFCrossBlockNode node = null; if( roots.containsKey(e.getKey()) ) node = new GDFCrossBlockNode(null, pb, roots.get(e.getKey()), loop, e.getKey()); //MERGE else node = new GDFCrossBlockNode(null, pb, loop, e.getKey()); //PLAIN roots.put(e.getKey(), node); } } } }
92380956d045bfc12d6abfe55328d828e3f73586
520
java
Java
src/main/java/com/github/danilkozyrev/filestorageapi/persistence/UserRepository.java
danilkozyrev/file-storage-api
bce5564ef11a1fed0c83a71e2aac803ba7a8c44b
[ "MIT" ]
4
2019-12-15T16:10:36.000Z
2021-09-19T03:29:29.000Z
src/main/java/com/github/danilkozyrev/filestorageapi/persistence/UserRepository.java
danilkozyrev/file-storage-api
bce5564ef11a1fed0c83a71e2aac803ba7a8c44b
[ "MIT" ]
1
2021-09-19T10:26:06.000Z
2021-09-22T21:56:57.000Z
src/main/java/com/github/danilkozyrev/filestorageapi/persistence/UserRepository.java
danilkozyrev/file-storage-api
bce5564ef11a1fed0c83a71e2aac803ba7a8c44b
[ "MIT" ]
2
2019-12-15T16:10:38.000Z
2021-09-19T04:06:28.000Z
26
67
0.780769
998,292
package com.github.danilkozyrev.filestorageapi.persistence; import com.github.danilkozyrev.filestorageapi.domain.User; import org.springframework.data.jpa.repository.*; import java.util.List; import java.util.Optional; public interface UserRepository extends JpaRepository<User, Long> { boolean existsByEmailIgnoreCase(String email); Optional<User> findUserByEmailIgnoreCase(String email); @Query("SELECT u FROM User u") @EntityGraph(attributePaths = "roles") List<User> findAllJoinRoles(); }
92380ac416ea4398817fd91a9f84eca92059a39f
3,551
java
Java
src/test/java/com/example/aventurasdemarcoyluis/tests/TestExcept.java
lucasmurray97/Metodologias-de-programacion
b1faf6f5670ba115b8372a6f406261ecbd3f812a
[ "MIT" ]
null
null
null
src/test/java/com/example/aventurasdemarcoyluis/tests/TestExcept.java
lucasmurray97/Metodologias-de-programacion
b1faf6f5670ba115b8372a6f406261ecbd3f812a
[ "MIT" ]
null
null
null
src/test/java/com/example/aventurasdemarcoyluis/tests/TestExcept.java
lucasmurray97/Metodologias-de-programacion
b1faf6f5670ba115b8372a6f406261ecbd3f812a
[ "MIT" ]
null
null
null
42.27381
125
0.697832
998,293
package com.example.aventurasdemarcoyluis.tests; import com.example.aventurasdemarcoyluis.model.BagPack; import com.example.aventurasdemarcoyluis.model.Characters.Enemies.Goomba; import com.example.aventurasdemarcoyluis.model.Characters.Players.Luigi; import com.example.aventurasdemarcoyluis.model.Characters.Players.Marcos; import com.example.aventurasdemarcoyluis.model.Game.Exceptions.InvalidCharacterActionException; import com.example.aventurasdemarcoyluis.model.Game.Exceptions.InvalidGamePlay; import com.example.aventurasdemarcoyluis.model.Game.Exceptions.ItemUnavailableException; import com.example.aventurasdemarcoyluis.model.Game.Game; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Random; import static org.junit.jupiter.api.Assertions.*; public class TestExcept { private Game game; @BeforeEach public void setUp() { } @Test public void testInvalidGamePlay() { Game game = new Game("test"); Goomba goomba = new Goomba(1); Throwable exception = assertThrows(InvalidGamePlay.class, () -> game.getState().chooseTargetLuigi(goomba)); assertEquals("You cannot choose a target now!", exception.getMessage()); } @Test public void testInvalidCharacterAction() { Marcos marcos = new Marcos(1); Luigi luigi = new Luigi(1); marcos.setFp(0); luigi.setFp(0); Throwable exception = assertThrows(InvalidCharacterActionException.class, () -> marcos.jumpAttack(new Goomba(1))); assertEquals("Not enough Fp to perform action!", exception.getMessage()); Throwable exception2 = assertThrows(InvalidCharacterActionException.class, () -> marcos.hammerAttack(new Goomba(1))); assertEquals("Not enough Fp to perform action!", exception.getMessage()); Throwable exception3 = assertThrows(InvalidCharacterActionException.class, () -> luigi.jumpAttack(new Goomba(1))); assertEquals("Not enough Fp to perform action!", exception.getMessage()); Throwable exception4 = assertThrows(InvalidCharacterActionException.class, () -> luigi.jumpAttack(new Goomba(1))); assertEquals("Not enough Fp to perform action!", exception.getMessage()); } @Test public void testItemUnavailableException() { BagPack bag = new BagPack(); Marcos marcos = new Marcos(1, bag); Throwable exception = assertThrows(ItemUnavailableException.class, () -> bag.useItem("RedMushroom", marcos)); assertEquals("You currently don't have this item", exception.getMessage()); } @Test public void testCatch1() { Game game = new Game("test"); game.addRandomEnemy(1); game.createBattle(1); game.addRedMushroom(1); game.addHoneySyrup(1); game.createBattle(1); game.createBattle(); game.levelUp(); game.increaseScore(); } @Test public void testCatch2() { Game game = new Game("test"); game.getBattle(); game.chooseTargetMarcos(new Goomba(1)); game.marcosJumpAttack(); game.normalAttack(); game.chooseTargetLuigi(new Goomba(1)); game.luigiJumpAttack(); game.luigiHammerAttack(); game.marcosHammerAttack(); game.getCharacters(); game.getCurrentPlayer(); game.getNextPlayer(); game.chooseItem("RedMushroom"); game.choosePlayer(game.getLuigi()); game.terminate(); } }
92380cbb922acb315dae56ea86c91d139f904b52
241
java
Java
src/main/java/com/anthunt/aws/spring/boot/xray/dao/TestMapper.java
anthunt/spring-boot-aws-xray-sample
1e8d6972a0958bce959603e5cba00956109a7b1c
[ "Apache-2.0" ]
11
2021-06-10T17:26:22.000Z
2022-03-04T06:25:40.000Z
src/main/java/com/anthunt/aws/spring/boot/xray/dao/TestMapper.java
anthunt/spring-boot-aws-xray-sample
1e8d6972a0958bce959603e5cba00956109a7b1c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/anthunt/aws/spring/boot/xray/dao/TestMapper.java
anthunt/spring-boot-aws-xray-sample
1e8d6972a0958bce959603e5cba00956109a7b1c
[ "Apache-2.0" ]
3
2021-01-25T10:05:34.000Z
2022-03-22T04:49:05.000Z
17.214286
50
0.742739
998,294
package com.anthunt.aws.spring.boot.xray.dao; import org.apache.ibatis.annotations.Mapper; import com.amazonaws.xray.spring.aop.XRayEnabled; @Mapper @XRayEnabled public interface TestMapper { public int count(int idx); }
92380db163c8363ece308eb0c9fe1cf78cf9494b
20,027
java
Java
bmc-streaming/src/main/java/com/oracle/bmc/streaming/StreamAdminAsync.java
mkelkarbv/oci-java-sdk
ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae
[ "UPL-1.0", "Apache-2.0" ]
1
2021-04-09T18:17:14.000Z
2021-04-09T18:17:14.000Z
bmc-streaming/src/main/java/com/oracle/bmc/streaming/StreamAdminAsync.java
mkelkarbv/oci-java-sdk
ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae
[ "UPL-1.0", "Apache-2.0" ]
null
null
null
bmc-streaming/src/main/java/com/oracle/bmc/streaming/StreamAdminAsync.java
mkelkarbv/oci-java-sdk
ccc4f103c588cfd6c1c07db9a43e8a0a98bd88ae
[ "UPL-1.0", "Apache-2.0" ]
null
null
null
55.941341
246
0.684126
998,295
/** * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.streaming; import com.oracle.bmc.streaming.requests.*; import com.oracle.bmc.streaming.responses.*; /** * The API for the Streaming Service. */ @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180418") public interface StreamAdminAsync extends AutoCloseable { /** * Sets the endpoint to call (ex, https://www.example.com). * @param endpoint The endpoint of the serice. */ void setEndpoint(String endpoint); /** * Gets the set endpoint for REST call (ex, https://www.example.com) */ String getEndpoint(); /** * Sets the region to call (ex, Region.US_PHOENIX_1). * <p> * Note, this will call {@link #setEndpoint(String) setEndpoint} after resolving the endpoint. If the service is not available in this region, however, an IllegalArgumentException will be raised. * @param region The region of the service. */ void setRegion(com.oracle.bmc.Region region); /** * Sets the region to call (ex, 'us-phoenix-1'). * <p> * Note, this will first try to map the region ID to a known Region and call * {@link #setRegion(Region) setRegion}. * <p> * If no known Region could be determined, it will create an endpoint based on the * default endpoint format ({@link com.oracle.bmc.Region#formatDefaultRegionEndpoint(Service, String)} * and then call {@link #setEndpoint(String) setEndpoint}. * @param regionId The public region ID. */ void setRegion(String regionId); /** * Moves a resource into a different compartment. When provided, If-Match is checked against ETag values of the resource. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ChangeConnectHarnessCompartmentResponse> changeConnectHarnessCompartment( ChangeConnectHarnessCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< ChangeConnectHarnessCompartmentRequest, ChangeConnectHarnessCompartmentResponse> handler); /** * Moves a resource into a different compartment. * When provided, If-Match is checked against ETag values of the resource. * The stream will also be moved into the default stream pool in the destination compartment. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ChangeStreamCompartmentResponse> changeStreamCompartment( ChangeStreamCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< ChangeStreamCompartmentRequest, ChangeStreamCompartmentResponse> handler); /** * Moves a resource into a different compartment. When provided, If-Match is checked against ETag values of the resource. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ChangeStreamPoolCompartmentResponse> changeStreamPoolCompartment( ChangeStreamPoolCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< ChangeStreamPoolCompartmentRequest, ChangeStreamPoolCompartmentResponse> handler); /** * Starts the provisioning of a new connect harness. * To track the progress of the provisioning, you can periodically call {@link ConnectHarness} object tells you its current state. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateConnectHarnessResponse> createConnectHarness( CreateConnectHarnessRequest request, com.oracle.bmc.responses.AsyncHandler< CreateConnectHarnessRequest, CreateConnectHarnessResponse> handler); /** * Starts the provisioning of a new stream. * The stream will be created in the given compartment id or stream pool id, depending on which parameter is specified. * Compartment id and stream pool id cannot be specified at the same time. * To track the progress of the provisioning, you can periodically call {@link #getStream(GetStreamRequest, Consumer, Consumer) getStream}. * In the response, the `lifecycleState` parameter of the {@link Stream} object tells you its current state. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateStreamResponse> createStream( CreateStreamRequest request, com.oracle.bmc.responses.AsyncHandler<CreateStreamRequest, CreateStreamResponse> handler); /** * Starts the provisioning of a new stream pool. * To track the progress of the provisioning, you can periodically call GetStreamPool. * In the response, the `lifecycleState` parameter of the object tells you its current state. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateStreamPoolResponse> createStreamPool( CreateStreamPoolRequest request, com.oracle.bmc.responses.AsyncHandler<CreateStreamPoolRequest, CreateStreamPoolResponse> handler); /** * Deletes a connect harness and its content. Connect harness contents are deleted immediately. The service retains records of the connect harness itself for 90 days after deletion. * The `lifecycleState` parameter of the `ConnectHarness` object changes to `DELETING` and the connect harness becomes inaccessible for read or write operations. * To verify that a connect harness has been deleted, make a {@link #getConnectHarness(GetConnectHarnessRequest, Consumer, Consumer) getConnectHarness} request. If the call returns the connect harness's * lifecycle state as `DELETED`, then the connect harness has been deleted. If the call returns a \"404 Not Found\" error, that means all records of the * connect harness have been deleted. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteConnectHarnessResponse> deleteConnectHarness( DeleteConnectHarnessRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteConnectHarnessRequest, DeleteConnectHarnessResponse> handler); /** * Deletes a stream and its content. Stream contents are deleted immediately. The service retains records of the stream itself for 90 days after deletion. * The `lifecycleState` parameter of the `Stream` object changes to `DELETING` and the stream becomes inaccessible for read or write operations. * To verify that a stream has been deleted, make a {@link #getStream(GetStreamRequest, Consumer, Consumer) getStream} request. If the call returns the stream's * lifecycle state as `DELETED`, then the stream has been deleted. If the call returns a \"404 Not Found\" error, that means all records of the * stream have been deleted. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteStreamResponse> deleteStream( DeleteStreamRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteStreamRequest, DeleteStreamResponse> handler); /** * Deletes a stream pool. All containing streams will also be deleted. * The default stream pool of a compartment cannot be deleted. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteStreamPoolResponse> deleteStreamPool( DeleteStreamPoolRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteStreamPoolRequest, DeleteStreamPoolResponse> handler); /** * Gets detailed information about a connect harness. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetConnectHarnessResponse> getConnectHarness( GetConnectHarnessRequest request, com.oracle.bmc.responses.AsyncHandler< GetConnectHarnessRequest, GetConnectHarnessResponse> handler); /** * Gets detailed information about a stream, including the number of partitions. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetStreamResponse> getStream( GetStreamRequest request, com.oracle.bmc.responses.AsyncHandler<GetStreamRequest, GetStreamResponse> handler); /** * Gets detailed information about the stream pool, such as Kafka settings. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetStreamPoolResponse> getStreamPool( GetStreamPoolRequest request, com.oracle.bmc.responses.AsyncHandler<GetStreamPoolRequest, GetStreamPoolResponse> handler); /** * Lists the connectharness. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListConnectHarnessesResponse> listConnectHarnesses( ListConnectHarnessesRequest request, com.oracle.bmc.responses.AsyncHandler< ListConnectHarnessesRequest, ListConnectHarnessesResponse> handler); /** * List the stream pools for a given compartment ID. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListStreamPoolsResponse> listStreamPools( ListStreamPoolsRequest request, com.oracle.bmc.responses.AsyncHandler<ListStreamPoolsRequest, ListStreamPoolsResponse> handler); /** * Lists the streams in the given compartment id. * If the compartment id is specified, it will list streams in the compartment, regardless of their stream pool. * If the stream pool id is specified, the action will be scoped to that stream pool. * The compartment id and stream pool id cannot be specified at the same time. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListStreamsResponse> listStreams( ListStreamsRequest request, com.oracle.bmc.responses.AsyncHandler<ListStreamsRequest, ListStreamsResponse> handler); /** * Updates the tags applied to the connect harness. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateConnectHarnessResponse> updateConnectHarness( UpdateConnectHarnessRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateConnectHarnessRequest, UpdateConnectHarnessResponse> handler); /** * Updates the stream. Only specified values will be updated. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateStreamResponse> updateStream( UpdateStreamRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateStreamRequest, UpdateStreamResponse> handler); /** * Updates the specified stream pool. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateStreamPoolResponse> updateStreamPool( UpdateStreamPoolRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateStreamPoolRequest, UpdateStreamPoolResponse> handler); }
92380e14b790267b58def710b59c7d8de443fe26
223
java
Java
src/main/java/com/taskadapter/redmineapi/bean/IssuePriorityFactory.java
Theosakamg/redmine-java-api
adba72e6c99ae8c65342b1b81c23df23221e2259
[ "Apache-2.0" ]
2
2015-03-27T21:07:39.000Z
2015-06-30T14:47:20.000Z
src/main/java/com/taskadapter/redmineapi/bean/IssuePriorityFactory.java
Theosakamg/redmine-java-api
adba72e6c99ae8c65342b1b81c23df23221e2259
[ "Apache-2.0" ]
null
null
null
src/main/java/com/taskadapter/redmineapi/bean/IssuePriorityFactory.java
Theosakamg/redmine-java-api
adba72e6c99ae8c65342b1b81c23df23221e2259
[ "Apache-2.0" ]
1
2021-08-12T09:40:17.000Z
2021-08-12T09:40:17.000Z
20.272727
52
0.659193
998,296
package com.taskadapter.redmineapi.bean; public class IssuePriorityFactory { /** * @param id database ID. */ public static IssuePriority create(Integer id) { return new IssuePriority(id); } }
92380f42f12c453812038e4a17d5681fd81a7b73
1,878
java
Java
src/main/java/uk/gov/hmcts/reform/unspec/service/flowstate/FlowState.java
uk-gov-mirror/hmcts.unspec-service
b97ee9fe71089f40a30b49132be506fc67e87ada
[ "MIT" ]
3
2020-08-24T12:36:25.000Z
2021-02-04T05:42:18.000Z
src/main/java/uk/gov/hmcts/reform/unspec/service/flowstate/FlowState.java
uk-gov-mirror/hmcts.unspec-service
b97ee9fe71089f40a30b49132be506fc67e87ada
[ "MIT" ]
711
2020-07-14T10:50:33.000Z
2021-04-14T08:07:52.000Z
src/main/java/uk/gov/hmcts/reform/unspec/service/flowstate/FlowState.java
uk-gov-mirror/hmcts.unspec-service
b97ee9fe71089f40a30b49132be506fc67e87ada
[ "MIT" ]
2
2020-11-13T16:31:40.000Z
2021-04-10T22:33:56.000Z
32.37931
80
0.679446
998,297
package uk.gov.hmcts.reform.unspec.service.flowstate; import static org.springframework.util.StringUtils.hasLength; public interface FlowState { String fullName(); static FlowState fromFullName(String fullName) { if (!hasLength(fullName)) { throw new IllegalArgumentException("Invalid full name:" + fullName); } int lastIndexOfDot = fullName.lastIndexOf('.'); String flowStateName = fullName.substring(lastIndexOfDot + 1); String flowName = fullName.substring(0, lastIndexOfDot); if (flowName.equals("MAIN")) { return Main.valueOf(flowStateName); } else { throw new IllegalArgumentException("Invalid flow name:" + flowName); } } enum Main implements FlowState { DRAFT, PENDING_CASE_ISSUED, PAYMENT_SUCCESSFUL, PAYMENT_FAILED, AWAITING_CASE_NOTIFICATION, AWAITING_CASE_DETAILS_NOTIFICATION, EXTENSION_REQUESTED, CLAIM_ISSUED, CLAIM_ACKNOWLEDGED, RESPONDENT_FULL_DEFENCE, RESPONDENT_FULL_ADMISSION, RESPONDENT_PART_ADMISSION, RESPONDENT_COUNTER_CLAIM, FULL_DEFENCE_PROCEED, FULL_DEFENCE_NOT_PROCEED, CLAIM_WITHDRAWN, CLAIM_DISCONTINUED, CASE_PROCEEDS_IN_CASEMAN, TAKEN_OFFLINE_PAST_APPLICANT_RESPONSE_DEADLINE, PROCEEDS_OFFLINE_UNREPRESENTED_DEFENDANT, PENDING_CLAIM_ISSUED_UNREGISTERED_DEFENDANT, PROCEEDS_OFFLINE_ADMIT_OR_COUNTER_CLAIM, CLAIM_DISMISSED_DEFENDANT_OUT_OF_TIME, CLAIM_DISMISSED_PAST_CLAIM_NOTIFICATION_DEADLINE, CLAIM_DISMISSED_PAST_CLAIM_DETAILS_NOTIFICATION_DEADLINE; public static final String FLOW_NAME = "MAIN"; @Override public String fullName() { return FLOW_NAME + "." + name(); } } }
92380fadc265efaf7da8c3fb562e4bfd139449b5
3,195
java
Java
kie-pmml-new/kie-pmml-models/kie-pmml-models-drools/kie-pmml-models-drools-scorecard/kie-pmml-models-drools-scorecard-compiler/src/main/java/org/kie/pmml/models/drools/scorecard/compiler/factories/KiePMMLScorecardModelFactory.java
VikramNisarga/drools
fa6ccfe9cbe393ba1d1e1d0d05283b70c4a4a9f6
[ "Apache-2.0" ]
null
null
null
kie-pmml-new/kie-pmml-models/kie-pmml-models-drools/kie-pmml-models-drools-scorecard/kie-pmml-models-drools-scorecard-compiler/src/main/java/org/kie/pmml/models/drools/scorecard/compiler/factories/KiePMMLScorecardModelFactory.java
VikramNisarga/drools
fa6ccfe9cbe393ba1d1e1d0d05283b70c4a4a9f6
[ "Apache-2.0" ]
null
null
null
kie-pmml-new/kie-pmml-models/kie-pmml-models-drools/kie-pmml-models-drools-scorecard/kie-pmml-models-drools-scorecard-compiler/src/main/java/org/kie/pmml/models/drools/scorecard/compiler/factories/KiePMMLScorecardModelFactory.java
VikramNisarga/drools
fa6ccfe9cbe393ba1d1e1d0d05283b70c4a4a9f6
[ "Apache-2.0" ]
null
null
null
46.985294
134
0.766823
998,298
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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.kie.pmml.models.drools.scorecard.compiler.factories; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.dmg.pmml.DataDictionary; import org.dmg.pmml.scorecard.Scorecard; import org.drools.compiler.lang.descr.PackageDescr; import org.kie.pmml.commons.model.KiePMMLOutputField; import org.kie.pmml.commons.model.enums.MINING_FUNCTION; import org.kie.pmml.models.drools.ast.KiePMMLDroolsAST; import org.kie.pmml.models.drools.scorecard.model.KiePMMLScorecardModel; import org.kie.pmml.models.drools.tuples.KiePMMLOriginalTypeGeneratedType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.kie.pmml.compiler.commons.factories.KiePMMLOutputFieldFactory.getOutputFields; import static org.kie.pmml.compiler.commons.utils.ModelUtils.getTargetFieldName; import static org.kie.pmml.models.drools.commons.factories.KiePMMLDescrFactory.getBaseDescr; import static org.kie.pmml.models.drools.scorecard.compiler.factories.KiePMMLScorecardModelASTFactory.getKiePMMLDroolsAST; /** * Class used to generate <code>KiePMMLScorecard</code> out of a <code>DataDictionary</code> and a <code>ScorecardModel</code> */ public class KiePMMLScorecardModelFactory { private static final Logger logger = LoggerFactory.getLogger(KiePMMLScorecardModelFactory.class.getName()); private KiePMMLScorecardModelFactory() { // Avoid instantiation } public static KiePMMLScorecardModel getKiePMMLScorecardModel(DataDictionary dataDictionary, Scorecard model) { logger.trace("getKiePMMLScorecardModel {}", model); String name = model.getModelName(); Optional<String> targetFieldName = getTargetFieldName(dataDictionary, model); final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = new HashMap<>(); final KiePMMLDroolsAST kiePMMLDroolsAST = getKiePMMLDroolsAST(dataDictionary, model, fieldTypeMap); String packageName = name.replace(" ", "_").toLowerCase(); final PackageDescr baseDescr = getBaseDescr(kiePMMLDroolsAST, packageName); final List<KiePMMLOutputField> outputFields = getOutputFields(model); return KiePMMLScorecardModel.builder(name, Collections.emptyList(), MINING_FUNCTION.byName(model.getMiningFunction().value())) .withOutputFields(outputFields) .withPackageDescr(baseDescr) .withFieldTypeMap(fieldTypeMap) .withTargetField(targetFieldName.orElse(null)) .build(); } }
92381040a5bef33803941c40f22bc268b132dce4
336
java
Java
app/src/main/java/com/havryliuk/itarticles/ui/favorites/FavoritesMvpPresenter.java
graviton57/ITArticles
8752dd1f85b831efc01ed606be2f91224b0028d9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/havryliuk/itarticles/ui/favorites/FavoritesMvpPresenter.java
graviton57/ITArticles
8752dd1f85b831efc01ed606be2f91224b0028d9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/havryliuk/itarticles/ui/favorites/FavoritesMvpPresenter.java
graviton57/ITArticles
8752dd1f85b831efc01ed606be2f91224b0028d9
[ "Apache-2.0" ]
null
null
null
21
89
0.767857
998,299
package com.havryliuk.itarticles.ui.favorites; import com.havryliuk.itarticles.ui.base.Presenter; /** * Created by Igor Havrylyuk on 22.10.2017. */ public interface FavoritesMvpPresenter<V extends FavoritesMvpView> extends Presenter<V> { void loadFavorites(); void updateArticleFavorite(int articleId, boolean value); }
9238108433cc058844a8a53f24b9c43a61e34d70
1,299
java
Java
src/com/exemplo/respositorio/RepositorioCliente.java
rubenscorrea20/loja
4deac4107a36b701828d7868f0a435b0d4d935cc
[ "Apache-2.0" ]
null
null
null
src/com/exemplo/respositorio/RepositorioCliente.java
rubenscorrea20/loja
4deac4107a36b701828d7868f0a435b0d4d935cc
[ "Apache-2.0" ]
null
null
null
src/com/exemplo/respositorio/RepositorioCliente.java
rubenscorrea20/loja
4deac4107a36b701828d7868f0a435b0d4d935cc
[ "Apache-2.0" ]
null
null
null
22.016949
73
0.727483
998,300
package com.exemplo.respositorio; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import com.exemplo.entidade.Cliente; public class RepositorioCliente { EntityManagerFactory emf; EntityManager em; public RepositorioCliente(){ emf = Persistence.createEntityManagerFactory("loja"); em = emf.createEntityManager(); } // Busca por ID public Cliente obterPorId(int id) { em.getTransaction().begin(); Cliente cliente = em.find(Cliente.class, id); em.getTransaction().commit(); emf.close(); return cliente; } // Salvar cliente public void salvar(Cliente cliente) { em.getTransaction().begin(); em.merge(cliente); em.getTransaction().commit(); emf.close(); } // Remover cliente public void remover(Cliente c){ em.getTransaction().begin(); em.remove(c); em.getTransaction().commit(); emf.close(); } // Listar Clintes @SuppressWarnings("unchecked") public List<Cliente> listarTodos(){ em.getTransaction().begin(); Query consulta = em.createQuery("select cliente from Cliente cliente"); List<Cliente> clientes = consulta.getResultList(); em.getTransaction().commit(); emf.close(); return clientes; } }
923811c0e732a25ab543180f53c4d31cc64e4782
3,639
java
Java
Javac2007/流程/comp/Check/checkUniqueImport.java
codefollower/Open-Source-Research
b9f2aed9d0f060b80be45f713c3d48fe91f247b2
[ "Apache-2.0" ]
184
2015-01-04T03:38:20.000Z
2022-03-30T05:47:21.000Z
Javac2007/流程/comp/Check/checkUniqueImport.java
codefollower/Open-Source-Research
b9f2aed9d0f060b80be45f713c3d48fe91f247b2
[ "Apache-2.0" ]
1
2016-01-17T09:18:17.000Z
2016-01-17T09:18:17.000Z
Javac2007/流程/comp/Check/checkUniqueImport.java
codefollower/Open-Source-Research
b9f2aed9d0f060b80be45f713c3d48fe91f247b2
[ "Apache-2.0" ]
101
2015-01-16T23:46:31.000Z
2022-03-30T05:47:06.000Z
34.990385
106
0.64798
998,301
/** Check that single-type import is not already imported or top-level defined, * but make an exception for two single-type imports which denote the same type. * @param pos Position for error reporting. * @param sym The symbol. * @param s The scope */ boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) { return checkUniqueImport(pos, sym, s, false); } /** Check that static single-type import is not already imported or top-level defined, * but make an exception for two single-type imports which denote the same type. * @param pos Position for error reporting. * @param sym The symbol. * @param s The scope * @param staticImport Whether or not this was a static import */ boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) { try {//我加上的 DEBUG.P(this,"checkUniqueStaticImport(3)"); return checkUniqueImport(pos, sym, s, true); }finally{//我加上的 DEBUG.P(0,this,"checkUniqueStaticImport(3)"); } } /** Check that single-type import is not already imported or top-level defined, * but make an exception for two single-type imports which denote the same type. * @param pos Position for error reporting. * @param sym The symbol. * @param s The scope. * @param staticImport Whether or not this was a static import */ private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) { try {//我加上的 DEBUG.P(this,"checkUniqueImport(4)"); DEBUG.P("Symbol sym="+sym); DEBUG.P("Scope s="+s); DEBUG.P("staticImport="+staticImport); for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) { // is encountered class entered via a class declaration? boolean isClassDecl = e.scope == s; DEBUG.P("e.scope="+e.scope); DEBUG.P("isClassDecl="+isClassDecl); DEBUG.P("(sym != e.sym)="+(sym != e.sym)); if ((isClassDecl || sym != e.sym) && sym.kind == e.sym.kind && sym.name != names.error) { if (!e.sym.type.isErroneous()) { String what = e.sym.toString(); if (!isClassDecl) { /*如: import static my.StaticImportTest.MyInnerClassStaticPublic; import static my.ExtendsTest.MyInnerClassStaticPublic; import java.util.Date; import java.sql.Date; bin\mysrc\my\test\Test.java:5: 已在静态 single-type 导入中定义 my.StaticImportTest.MyInnerClassStaticPublic import static my.ExtendsTest.MyInnerClassStaticPublic; ^ bin\mysrc\my\test\Test.java:7: 已在 single-type 导入中定义 java.util.Date import java.sql.Date; ^ 2 错误 */ if (staticImport) log.error(pos, "already.defined.static.single.import", what); else log.error(pos, "already.defined.single.import", what); } /* src/my/test/EnterTest.java:9: 已在该编译单元中定义 my.test.InnerInterface import static my.test.EnterTest.InnerInterface; ^ 源码: import static my.test.EnterTest.InnerInterface; interface InnerInterface{} public class EnterTest { public static interface InnerInterface<T extends EnterTest> {} public void m() { class LocalClass{} } }*/ //如果是import static my.test.InnerInterface就不会报错 //因为此时sym == e.sym,虽然没报错,但是还是返回false,指明不用 //把这个sym加入env.toplevel.namedImportScope else if (sym != e.sym) log.error(pos, "already.defined.this.unit", what);//已在该编译单元中定义 } return false; } } return true; }finally{//我加上的 DEBUG.P(0,this,"checkUniqueImport(4)"); } }
923812a7976cdaa9b627866d2ffd2b5907ed29b5
10,396
java
Java
viewer/viewer-awt/src/main/java/org/icepdf/ri/common/views/TwoColumnPageView.java
svn2github/icepdf
6b4a637e1a1dfb8529c3cd041a0e72191079823d
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
12
2015-04-02T06:59:25.000Z
2019-09-26T06:18:35.000Z
viewer/viewer-awt/src/main/java/org/icepdf/ri/common/views/TwoColumnPageView.java
svn2github/icepdf
6b4a637e1a1dfb8529c3cd041a0e72191079823d
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
2
2018-08-01T14:10:05.000Z
2019-01-14T06:16:06.000Z
viewer/viewer-awt/src/main/java/org/icepdf/ri/common/views/TwoColumnPageView.java
svn2github/icepdf
6b4a637e1a1dfb8529c3cd041a0e72191079823d
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
15
2015-01-21T09:34:24.000Z
2021-05-19T14:24:59.000Z
39.984615
96
0.604463
998,302
/* * Copyright 2006-2017 ICEsoft Technologies Canada Corp. * * 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.icepdf.ri.common.views; import org.icepdf.ri.common.CurrentPageChanger; import org.icepdf.ri.common.KeyListenerPageColumnChanger; import org.icepdf.ri.common.SwingController; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; /** * <p>Constructs a two column page view as defined in the PDF specification. * A two column page view displays pages in two columns with odd numbered pages * on the left.</p> * <br> * <p>Page views are basic containers which use Swing Layout Containers to * place pages </p> * * @since 2.5 */ @SuppressWarnings("serial") public class TwoColumnPageView extends AbstractDocumentView { protected int viewAlignment; // specialized listeners for different gui operations protected CurrentPageChanger currentPageChanger; protected KeyListenerPageColumnChanger keyListenerPageChanger; public TwoColumnPageView(DocumentViewController documentDocumentViewController, JScrollPane documentScrollpane, DocumentViewModel documentViewModel, final int viewAlignment) { super(documentDocumentViewController, documentScrollpane, documentViewModel); // used to redirect mouse events this.documentScrollpane = documentScrollpane; // assign view allignemnt this.viewAlignment = viewAlignment; // put all the gui elements together buildGUI(); // add the first of many tools need for this views and others like it. currentPageChanger = new CurrentPageChanger(documentScrollpane, this, documentViewModel.getPageComponents()); // add page changing key listeners if (this.documentViewController.getParentController() instanceof SwingController) { keyListenerPageChanger = KeyListenerPageColumnChanger.install( (SwingController) this.documentViewController.getParentController(), this.documentScrollpane, this, currentPageChanger); } } private void buildGUI() { // add all page components to gridlayout panel pagesPanel = new JPanel(); pagesPanel.setBackground(backgroundColour); // two column equals facing page view continuous GridLayout gridLayout = new GridLayout(0, 2, horizontalSpace, verticalSpace); pagesPanel.setLayout(gridLayout); // use a gridbag to center the page component panel GridBagConstraints gbc = new GridBagConstraints(); gbc.weighty = 1.0; // allows vertical resizing gbc.weightx = 1.0; // allows horizontal resizing gbc.insets = // component spacer [top, left, bottom, right] new Insets(layoutInserts, layoutInserts, layoutInserts, layoutInserts); gbc.gridwidth = GridBagConstraints.REMAINDER; // one component per row this.setLayout(new GridBagLayout()); this.add(pagesPanel, gbc); // finally add all the components // add components for every page in the document java.util.List<AbstractPageViewComponent> pageComponents = documentViewModel.getPageComponents(); if (pageComponents != null) { PageViewComponent pageViewComponent; for (int i = 0, max = pageComponents.size(), max2 = pageComponents.size(); i < max && i < max2; i++) { // save for facing page if (i == 0 && max2 > 2 && viewAlignment == RIGHT_VIEW) { // should be adding spacer pagesPanel.add(new JLabel()); } pageViewComponent = pageComponents.get(i); if (pageViewComponent != null) { pageViewComponent.setDocumentViewCallback(this); pagesPanel.add(new PageViewDecorator( (AbstractPageViewComponent) pageViewComponent)); } } } } // nothing needs to be done for a column view as all components are already // available public void updateDocumentView() { } /** * Returns a next page increment of two. */ public int getNextPageIncrement() { return 2; } /** * Returns a previous page increment of two. */ public int getPreviousPageIncrement() { return 2; } public void mouseReleased(MouseEvent e) { // let the current PageListener now about the mouse release currentPageChanger.mouseReleased(e); } public void dispose() { disposing = true; // remove utilities if (currentPageChanger != null) { currentPageChanger.dispose(); } if (keyListenerPageChanger != null) { keyListenerPageChanger.uninstall(); } // trigger a relayout pagesPanel.removeAll(); pagesPanel.invalidate(); // make sure we call super. super.dispose(); } public Dimension getDocumentSize() { float pageViewWidth = 0; float pageViewHeight = 0; if (pagesPanel != null) { // The page index and corresponding component index are approximately equal // If the first page is on the right, then there's a spacer on the left, // bumping indexes up by one. int currPageIndex = documentViewController.getCurrentPageIndex(); int currCompIndex = currPageIndex; int numComponents = pagesPanel.getComponentCount(); boolean foundCurrent = false; while (currCompIndex >= 0 && currCompIndex < numComponents) { Component comp = pagesPanel.getComponent(currCompIndex); if (comp instanceof PageViewDecorator) { PageViewDecorator pvd = (PageViewDecorator) comp; PageViewComponent pvc = pvd.getPageViewComponent(); if (pvc.getPageIndex() == currPageIndex) { Dimension dim = pvd.getPreferredSize(); pageViewWidth = dim.width; pageViewHeight = dim.height; foundCurrent = true; break; } } currCompIndex++; } if (foundCurrent) { // Determine if the page at (currPageIndex,currCompIndex) was // on the left or right, so that if there's a page next to // it, whether it's earlier or later in the component list, // so we can get it's pageViewHeight and use that for our pageViewHeight // calculation. // If the other component is past the ends of the component // list, or not a PageViewDecorator, then current was either // the first or last page in the document boolean evenPageIndex = ((currPageIndex & 0x1) == 0); boolean bumpedIndex = (currCompIndex != currPageIndex); boolean onLeft = evenPageIndex ^ bumpedIndex; // XOR int otherCompIndex = onLeft ? (currCompIndex + 1) : (currCompIndex - 1); if (otherCompIndex >= 0 && otherCompIndex < numComponents) { Component comp = pagesPanel.getComponent(otherCompIndex); if (comp instanceof PageViewDecorator) { PageViewDecorator pvd = (PageViewDecorator) comp; Dimension dim = pvd.getPreferredSize(); pageViewWidth = dim.width; pageViewHeight = dim.height; } } } } // normalize the dimensions to a zoom level of zero. float currentZoom = documentViewModel.getViewZoom(); pageViewWidth = Math.abs(pageViewWidth / currentZoom); pageViewHeight = Math.abs(pageViewHeight / currentZoom); // two pages wide, generalization, pages are usually the same size we // don't bother to look at the second pages size for the time being. pageViewWidth *= 2; // add any horizontal padding from layout manager pageViewWidth += AbstractDocumentView.horizontalSpace * 4; pageViewHeight += AbstractDocumentView.verticalSpace * 2; return new Dimension((int) pageViewWidth, (int) pageViewHeight); } public void paintComponent(Graphics g) { Rectangle clipBounds = g.getClipBounds(); g.setColor(backgroundColour); g.fillRect(clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height); // paint selection box super.paintComponent(g); } // public void adjustmentValueChanged(AdjustmentEvent e){ // //// System.out.println("Adjusting " + e.getAdjustable().getValue()); // if (e.getAdjustable().getOrientation() == Adjustable.HORIZONTAL){ //// System.out.println("horizontal"); // } // else if (e.getAdjustable().getOrientation() == Adjustable.VERTICAL){ //// System.out.println("vertical"); //// int newValue = e.getAdjustable().getValue(); //// System.out.println("value " + newValue); //// e.getAdjustable().setValue(0); // } // } // public void mouseDragged(MouseEvent e) { // Point point = e.getPoint(); // super.mouseDragged(e); // Point currentLocation = getLocation(); // pageViewComponentImpl.setBounds(point.x, // point.y, 640,480); // } }
923812a7bb7540a27d60dbc961f4d42d68da65a8
238
java
Java
guns-api/src/main/java/com/stylefeng/guns/rest/dto/BuyTicketDTO.java
lxmxiao/cinema
f44728fffdd43fb3d76f007fc9c9c03b77998116
[ "Apache-2.0" ]
2
2019-11-29T09:29:58.000Z
2020-03-19T02:14:23.000Z
guns-api/src/main/java/com/stylefeng/guns/rest/dto/BuyTicketDTO.java
location663/Cinema
ff4565bc287a83baeca4b9def9090ace95f846ed
[ "Apache-2.0" ]
3
2019-12-04T15:06:14.000Z
2021-09-20T20:54:09.000Z
guns-api/src/main/java/com/stylefeng/guns/rest/dto/BuyTicketDTO.java
location663/Cinema
ff4565bc287a83baeca4b9def9090ace95f846ed
[ "Apache-2.0" ]
null
null
null
18.307692
51
0.773109
998,303
package com.stylefeng.guns.rest.dto; import lombok.Data; import java.io.Serializable; @Data public class BuyTicketDTO implements Serializable { private Integer fieldId; private String soldSeats; private String seatsName; }
923812acb68cfd6e4aadb845f0d351e20bb7e975
664
java
Java
src/exwrapper/ch/shaktipat/exwrapper/java/io/OutputStreamWrapper.java
liquid-mind/warp
875a5624f71596b4f40b6133f890ac9626e21574
[ "Apache-2.0" ]
1
2016-02-09T10:15:08.000Z
2016-02-09T10:15:08.000Z
src/exwrapper/ch/shaktipat/exwrapper/java/io/OutputStreamWrapper.java
liquid-mind/warp
875a5624f71596b4f40b6133f890ac9626e21574
[ "Apache-2.0" ]
null
null
null
src/exwrapper/ch/shaktipat/exwrapper/java/io/OutputStreamWrapper.java
liquid-mind/warp
875a5624f71596b4f40b6133f890ac9626e21574
[ "Apache-2.0" ]
null
null
null
15.090909
61
0.665663
998,304
package ch.shaktipat.exwrapper.java.io; import java.io.IOException; import java.io.OutputStream; public class OutputStreamWrapper { public static void write( OutputStream outputStream, int b ) { try { outputStream.write( b ); } catch ( IOException e ) { throw new IOExceptionWrapper( e ); } } public static void flush( OutputStream outputStream ) { try { outputStream.flush(); } catch ( IOException e ) { throw new IOExceptionWrapper( e ); } } public static void close( OutputStream outputStream ) { try { outputStream.close(); } catch ( IOException e ) { throw new IOExceptionWrapper( e ); } } }
9238142927945a7d707e5c120239453528cdc09b
2,398
java
Java
jodd-madvoc/src/main/java/jodd/madvoc/component/MadvocControllerCfg.java
xun404/jodd
d5c7e9cb61842aee2ba7800e4b7a10ba7f0162a1
[ "BSD-2-Clause" ]
3,937
2015-01-02T14:21:57.000Z
2022-03-31T09:03:33.000Z
jodd-madvoc/src/main/java/jodd/madvoc/component/MadvocControllerCfg.java
xun404/jodd
d5c7e9cb61842aee2ba7800e4b7a10ba7f0162a1
[ "BSD-2-Clause" ]
584
2015-01-02T20:58:08.000Z
2022-03-29T02:10:35.000Z
jodd-madvoc/src/main/java/jodd/madvoc/component/MadvocControllerCfg.java
xun404/jodd
d5c7e9cb61842aee2ba7800e4b7a10ba7f0162a1
[ "BSD-2-Clause" ]
800
2015-01-02T06:44:42.000Z
2022-02-16T08:28:49.000Z
35.791045
88
0.769391
998,305
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 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 HOLDER 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. package jodd.madvoc.component; abstract class MadvocControllerCfg { protected boolean applyCharacterEncoding = true; protected boolean preventCaching = true; protected String welcomeFile = "/index.jsp"; public boolean isApplyCharacterEncoding() { return applyCharacterEncoding; } /** * Defines is character encoding has to be set by Madvoc into the request and response. */ public void setApplyCharacterEncoding(final boolean applyCharacterEncoding) { this.applyCharacterEncoding = applyCharacterEncoding; } public boolean isPreventCaching() { return preventCaching; } /** * Specifies if Madvoc should add response params to prevent browser caching. */ public void setPreventCaching(final boolean preventCaching) { this.preventCaching = preventCaching; } public String getWelcomeFile() { return welcomeFile; } /** * Sets the welcome file as defined by servlet container. */ public void setWelcomeFile(final String welcomeFile) { this.welcomeFile = welcomeFile; } }
92381636339f9bd80c3e610feda740a2399ecbd6
1,910
java
Java
Tasktrckr/app/src/main/java/spy/gi/tasktrckr/MainActivity.java
spygi/tasktrckr
d0355df85703a94b33aa4adda99653729e1cd777
[ "MIT" ]
1
2016-05-16T14:12:35.000Z
2016-05-16T14:12:35.000Z
Tasktrckr/app/src/main/java/spy/gi/tasktrckr/MainActivity.java
spygi/tasktrckr
d0355df85703a94b33aa4adda99653729e1cd777
[ "MIT" ]
null
null
null
Tasktrckr/app/src/main/java/spy/gi/tasktrckr/MainActivity.java
spygi/tasktrckr
d0355df85703a94b33aa4adda99653729e1cd777
[ "MIT" ]
null
null
null
32.931034
87
0.696335
998,306
package spy.gi.tasktrckr; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import com.facebook.stetho.Stetho; public class MainActivity extends AppCompatActivity { // AppCompatActivity instead of Activity because it includes already a Toolbar @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Stetho.initializeWithDefaults(this); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, InsertTaskActivity.class)); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
923816f21424282805453dea62942be45d68930a
977
java
Java
src/main/java/at/petrak/hex/common/items/ItemWand.java
DarianLStephens/HexMod
5608db3adaf7bf2f78f0e8e7133612edb1bb5ad7
[ "MIT" ]
null
null
null
src/main/java/at/petrak/hex/common/items/ItemWand.java
DarianLStephens/HexMod
5608db3adaf7bf2f78f0e8e7133612edb1bb5ad7
[ "MIT" ]
null
null
null
src/main/java/at/petrak/hex/common/items/ItemWand.java
DarianLStephens/HexMod
5608db3adaf7bf2f78f0e8e7133612edb1bb5ad7
[ "MIT" ]
null
null
null
30.53125
101
0.750256
998,307
package at.petrak.hex.common.items; import at.petrak.hex.client.gui.GuiSpellcasting; import net.minecraft.client.Minecraft; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; public class ItemWand extends Item { public static final String TAG_HARNESS = "harness"; public ItemWand(Properties pProperties) { super(pProperties); } @Override public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) { if (world.isClientSide()) { Minecraft.getInstance().setScreen(new GuiSpellcasting(hand)); } player.awardStat(Stats.ITEM_USED.get(this)); return InteractionResultHolder.success(player.getItemInHand(hand)); } }
9238171f5cc7f2e5072c0d3696d5600199565e13
1,302
java
Java
example/Simple Example/server/src/main/java/io/first/Server.java
genny-project/vertx-eventbus-bridge-clients
105c1d5dee025b164cc42e47612209264cbeeaa5
[ "MIT" ]
46
2017-03-10T07:52:06.000Z
2022-03-23T19:41:09.000Z
example/Simple Example/server/src/main/java/io/first/Server.java
genny-project/vertx-eventbus-bridge-clients
105c1d5dee025b164cc42e47612209264cbeeaa5
[ "MIT" ]
46
2017-03-31T14:24:44.000Z
2022-03-31T11:44:44.000Z
example/Simple Example/server/src/main/java/io/first/Server.java
genny-project/vertx-eventbus-bridge-clients
105c1d5dee025b164cc42e47612209264cbeeaa5
[ "MIT" ]
28
2017-03-21T10:56:57.000Z
2022-03-30T14:07:08.000Z
26.571429
77
0.727343
998,308
package io.first; import io.vertx.core.*; import io.vertx.core.Vertx; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import io.vertx.core.Handler; import io.vertx.ext.bridge.BridgeOptions; import io.vertx.ext.bridge.PermittedOptions; import io.vertx.ext.eventbus.bridge.tcp.TcpEventBusBridge; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.eventbus.EventBus; import java.util.Map; /** * * @author jay */ public class Server extends AbstractVerticle{ public void start(Future<Void> fut){ TcpEventBusBridge bridge = TcpEventBusBridge.create( vertx, new BridgeOptions() .addInboundPermitted(new PermittedOptions().setAddress("welcome")) .addOutboundPermitted(new PermittedOptions().setAddress("welcome"))); bridge.listen(7000, res -> { if (res.succeeded()) { System.out.println("Started"); } else { System.out.println("failed"); } }); EventBus eb = vertx.eventBus(); MessageConsumer< JsonObject > consumer=eb.consumer("welcome", message -> { System.out.println("Message body: " + message.body()); String jsonString = "{\"msg\":\"welcome\"}"; JsonObject object = new JsonObject(jsonString); message.reply(object); }); } }
923817fa78ed7b4786cab90dd11368a92c25e35d
1,651
java
Java
ex4/ex4/src/edu/cg/algebra/Vec.java
Danpollak/CG_IDC
609724877cb487f7fb0daa99cf6fefc41f9eeb52
[ "MIT" ]
null
null
null
ex4/ex4/src/edu/cg/algebra/Vec.java
Danpollak/CG_IDC
609724877cb487f7fb0daa99cf6fefc41f9eeb52
[ "MIT" ]
null
null
null
ex4/ex4/src/edu/cg/algebra/Vec.java
Danpollak/CG_IDC
609724877cb487f7fb0daa99cf6fefc41f9eeb52
[ "MIT" ]
null
null
null
15.146789
45
0.603271
998,309
package edu.cg.algebra; import java.nio.FloatBuffer; public class Vec { public float x, y, z; public Vec(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public Vec(double x, double y, double z) { this((float)x, (float)y, (float)z); } public Vec(float val) { this(val, val, val); } public Vec(double val) { this((float)val); } public Vec(Vec other) { this(other.x, other.y, other.z); } public Vec() { this(0f); } public float norm() { return Ops.norm(this); } public float normSqr() { return Ops.normSqr(this); } public float length() { return Ops.length(this); } public float lengthSqr() { return Ops.lengthSqr(this); } public Vec normalize() { return Ops.normalize(this); } public Vec neg() { return Ops.neg(this); } public float dot(Vec other) { return Ops.dot(this, other); } public Vec cross(Vec other) { return Ops.cross(this, other); } public Vec mult(float a) { return Ops.mult(a, this); } public Vec mult(double a) { return Ops.mult(a, this); } public Vec mult(Vec v) { return Ops.mult(this, v); } public Vec add(Vec v) { return Ops.add(this, v); } public boolean isFinite() { return Ops.isFinite(this); } public FloatBuffer toGLColor() { return FloatBuffer.wrap(clip().toArray()); } public float[] toArray() { return new float[] {x, y, z}; } public Vec clip() { return new Vec(clip(x), clip(y), clip(z)); } private static float clip(float val) { return Math.min(1, Math.max(0, val)); } @Override public String toString() { return "(" + x + ", " + y + ", " + z + ")"; } }
923817fc85db183e13fc4b45fbcd1052e12661e5
133
java
Java
hed-services/app/models/RuleGroup.java
rkiefer/HeD-editor
2e4fd56baf66f74b4fde2c5ec075a66d87b531e0
[ "Apache-2.0" ]
1
2017-04-17T02:27:50.000Z
2017-04-17T02:27:50.000Z
hed-services/app/models/RuleGroup.java
rkiefer/HeD-editor
2e4fd56baf66f74b4fde2c5ec075a66d87b531e0
[ "Apache-2.0" ]
null
null
null
hed-services/app/models/RuleGroup.java
rkiefer/HeD-editor
2e4fd56baf66f74b4fde2c5ec075a66d87b531e0
[ "Apache-2.0" ]
null
null
null
11.083333
36
0.714286
998,310
package models; import java.util.List; public class RuleGroup { public String label; public List<Artifact> templates; }
92381868325502544206ab2275d8cb3793ae1daa
1,354
java
Java
src/ThreadHandling/ThreadHandler.java
rzahoransky/JMieCalc
2ea0ed727bf061865a3e16a3d2419f106ecc8231
[ "MIT" ]
1
2021-04-22T19:59:49.000Z
2021-04-22T19:59:49.000Z
src/ThreadHandling/ThreadHandler.java
rzahoransky/JMieCalc
2ea0ed727bf061865a3e16a3d2419f106ecc8231
[ "MIT" ]
null
null
null
src/ThreadHandling/ThreadHandler.java
rzahoransky/JMieCalc
2ea0ed727bf061865a3e16a3d2419f106ecc8231
[ "MIT" ]
1
2020-06-25T23:40:44.000Z
2020-06-25T23:40:44.000Z
27.632653
75
0.664697
998,311
package ThreadHandling; import java.util.ArrayList; import calculation.CalculationAssignment; public class ThreadHandler { private ArrayList<Thread> threads; int processors; private CalculationAssignment monitor; public ThreadHandler(ArrayList<Thread> threads) { this.threads=threads; processors = Runtime.getRuntime().availableProcessors(); } public void addThreadMonitor(CalculationAssignment monitor) { this.monitor=monitor; } private void updateMonitor(int currentIndex) { if (monitor!=null) monitor.setProgress(currentIndex, threads.size()); } public void runThreads () throws InterruptedException { boolean finished = false; int i = 0; updateMonitor(i); while(i<threads.size()) { for(int cpu = 0; (cpu < processors)&&((i+cpu)<threads.size()); cpu++) { threads.get(cpu+i).start(); System.out.println("Processing Thread "+(cpu+i)); //System.out.println("Running thread for element "+(i+cpu)); } //wait for them ALL to finish (not the best to do... but still... //System.out.println("Waiting for threads..."); for(int cpu = 0; (cpu < processors)&&((i+cpu)<threads.size()); cpu++) { threads.get(cpu+i).join(); //wait for finish } //System.out.println("Threads finished..."); i=i+processors; updateMonitor(i); } } }
92381a46e7cbc81a355c3573380b56aa58418020
332
java
Java
spring-boot-quartz-spark/src/main/java/com/zhbr/springbootquartzspark/test/Test01.java
daydayup-zyn/springboot-learning-experience
6f265d64d871bc270e2563592013001dcfac67a2
[ "Apache-2.0" ]
null
null
null
spring-boot-quartz-spark/src/main/java/com/zhbr/springbootquartzspark/test/Test01.java
daydayup-zyn/springboot-learning-experience
6f265d64d871bc270e2563592013001dcfac67a2
[ "Apache-2.0" ]
null
null
null
spring-boot-quartz-spark/src/main/java/com/zhbr/springbootquartzspark/test/Test01.java
daydayup-zyn/springboot-learning-experience
6f265d64d871bc270e2563592013001dcfac67a2
[ "Apache-2.0" ]
null
null
null
13.28
55
0.641566
998,312
package com.zhbr.springbootquartzspark.test; public class Test01 { public static void main(String[] args) { // System.out.println(EnumTest.SPRING.getVal()); EnumTest enumDemo = EnumTest.getEnum("SPRING"); System.out.println(enumDemo); System.out.println(enumDemo.getVal()); } }
92381a62066a0db79ff47ef53d00654439319467
2,811
java
Java
rpc/main/java/com/david/common/rpc/client/RpcClient.java
duantonghai1984/Research
67ac958087125a77149f4ae7d35859f2d8d62a51
[ "Apache-2.0" ]
null
null
null
rpc/main/java/com/david/common/rpc/client/RpcClient.java
duantonghai1984/Research
67ac958087125a77149f4ae7d35859f2d8d62a51
[ "Apache-2.0" ]
null
null
null
rpc/main/java/com/david/common/rpc/client/RpcClient.java
duantonghai1984/Research
67ac958087125a77149f4ae7d35859f2d8d62a51
[ "Apache-2.0" ]
null
null
null
32.686047
108
0.644966
998,313
/** * Alipay.com Inc. * Copyright (c) 2004-2014 All Rights Reserved. */ package com.david.common.rpc.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import com.david.common.rpc.Response.RpcResponse; import com.david.common.rpc.request.RpcRequest; import com.david.common.rpc.server.RpcDecoder; import com.david.common.rpc.server.RpcEncoder; /** * * @author zhangwei_david * @version $Id: RpcClient.java, v 0.1 2014年12月31日 下午9:18:34 zhangwei_david Exp $ */ public class RpcClient extends SimpleChannelInboundHandler<RpcResponse> { private String host; private int port; private RpcResponse response; private final Object obj = new Object(); public RpcClient(String host, int port) { this.host = host; this.port = port; } @Override public void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { this.response = response; synchronized (obj) { obj.notifyAll(); // 收到响应,唤醒线程 } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } public RpcResponse send(RpcRequest request) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(new RpcEncoder(RpcRequest.class)) // 将 RPC 请求进行编码(为了发送请求) .addLast(new RpcDecoder(RpcResponse.class)) // 将 RPC 响应进行解码(为了处理响应) .addLast(RpcClient.this); // 使用 RpcClient 发送 RPC 请求 } }).option(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().writeAndFlush(request).sync(); synchronized (obj) { obj.wait(); // 未收到响应,使线程等待 } if (response != null) { future.channel().closeFuture().sync(); } return response; } finally { group.shutdownGracefully(); } } }
92381a64f3136cc3ffa452161765c937c39d672d
938
java
Java
Chapter07/src/main/java/section_08/FinalOverridingIllusion.java
letitgone/thinking_in_java
3c439d2d75851ab0b6953bfd8b7236e09c4367bb
[ "MIT" ]
3
2019-03-09T01:12:47.000Z
2019-03-18T11:31:22.000Z
Chapter07/src/main/java/section_08/FinalOverridingIllusion.java
letitgone/thinking-in-java
3c439d2d75851ab0b6953bfd8b7236e09c4367bb
[ "MIT" ]
null
null
null
Chapter07/src/main/java/section_08/FinalOverridingIllusion.java
letitgone/thinking-in-java
3c439d2d75851ab0b6953bfd8b7236e09c4367bb
[ "MIT" ]
null
null
null
20.844444
58
0.563966
998,314
package section_08; class OverridingPrivate extends WithFinals { private final void f() { System.out.println("OverridingPrivate.f()"); } private void g() { System.out.println("OverridingPrivate.g()"); } } class OverridingPrivate2 extends OverridingPrivate { public final void f() { System.out.println("OverridingPrivate2.f()"); } public void g() { System.out.println("OverridingPrivate2.g()"); } } /** * @Author ZhangGJ * @Date 2019/04/09 */ public class FinalOverridingIllusion { public static void main(String[] args) { OverridingPrivate2 op2 = new OverridingPrivate2(); op2.f(); op2.g(); // You can upcast: OverridingPrivate op = op2; // But you can’t call the methods: //! op.f(); //! op.g(); // Same here: WithFinals wf = op2; //! wf.f(); //! wf.g(); } }
92381a6b4063802487ca208e0f3772d43f6a96bb
1,513
java
Java
server/catgenome/src/main/java/com/epam/catgenome/controller/vo/SpeciesVO.java
lizaveta-vlasova/NGB
11ebd2ecb6fbe4d58a7eca2152eda03458b5767b
[ "MIT" ]
143
2016-12-08T07:57:45.000Z
2022-02-16T01:47:47.000Z
server/catgenome/src/main/java/com/epam/catgenome/controller/vo/SpeciesVO.java
lizaveta-vlasova/NGB
11ebd2ecb6fbe4d58a7eca2152eda03458b5767b
[ "MIT" ]
480
2017-02-21T12:26:43.000Z
2022-03-30T13:36:17.000Z
server/catgenome/src/main/java/com/epam/catgenome/controller/vo/SpeciesVO.java
lizaveta-vlasova/NGB
11ebd2ecb6fbe4d58a7eca2152eda03458b5767b
[ "MIT" ]
54
2016-10-28T16:13:21.000Z
2022-03-04T16:49:23.000Z
32.891304
81
0.734964
998,315
/* * MIT License * * Copyright (c) 2017 EPAM Systems * * 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 com.epam.catgenome.controller.vo; import com.epam.catgenome.entity.reference.Species; /** * <p> * A View Object for Species entity representation * </p> */ public class SpeciesVO { private Species species; public Species getSpecies() { return species; } public void setSpecies(Species species) { this.species = species; } }
92381aba5a3a680aea17d1fd4a315f54cc8b64b7
855
java
Java
gmall-pms/src/main/java/com/atguigu/gmall/pms/entity/CommentReplayEntity.java
yunchaozhang1/gmall
bcb16349b4498163f9808bab6cd788fb22bd7610
[ "Apache-2.0" ]
null
null
null
gmall-pms/src/main/java/com/atguigu/gmall/pms/entity/CommentReplayEntity.java
yunchaozhang1/gmall
bcb16349b4498163f9808bab6cd788fb22bd7610
[ "Apache-2.0" ]
2
2021-04-22T17:03:17.000Z
2021-09-20T20:55:13.000Z
gmall-pms/src/main/java/com/atguigu/gmall/pms/entity/CommentReplayEntity.java
yunchaozhang1/gmall-0805
bcb16349b4498163f9808bab6cd788fb22bd7610
[ "Apache-2.0" ]
null
null
null
20.309524
58
0.728019
998,316
package com.atguigu.gmall.pms.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 商品评价回复关系 * * @author zhangyunchao * @email lyhxr@example.com * @date 2020-01-04 16:55:49 */ @ApiModel @Data @TableName("pms_comment_replay") public class CommentReplayEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId @ApiModelProperty(name = "id",value = "id") private Long id; /** * 评论id */ @ApiModelProperty(name = "commentId",value = "评论id") private Long commentId; /** * 回复id */ @ApiModelProperty(name = "replyId",value = "回复id") private Long replyId; }
92381ad36c8c44b1c60820fd4159ffaf095436ef
1,873
java
Java
app/src/main/java/com/vincevitale/fragmentwork/FragmentWebView.java
VinceVitale/FragmentWork
1354e93a38c94661a2f899d243a14f4adc99668e
[ "MIT" ]
null
null
null
app/src/main/java/com/vincevitale/fragmentwork/FragmentWebView.java
VinceVitale/FragmentWork
1354e93a38c94661a2f899d243a14f4adc99668e
[ "MIT" ]
null
null
null
app/src/main/java/com/vincevitale/fragmentwork/FragmentWebView.java
VinceVitale/FragmentWork
1354e93a38c94661a2f899d243a14f4adc99668e
[ "MIT" ]
null
null
null
30.704918
102
0.689802
998,317
package com.vincevitale.fragmentwork; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; public class FragmentWebView extends Fragment { static String mURL = "http://www.ucmo.edu"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ return inflater.inflate(R.layout.web_view, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); if(savedInstanceState != null){ mURL = savedInstanceState.getString("currentURL", ""); } if(!mURL.equals("")){ WebView myWebView = (WebView) getView().findViewById(R.id.pageInfo); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setWebViewClient(new MyWebViewClient()); myWebView.loadUrl(mURL); } } @Override public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); outState.putString("currentURL", mURL); } public void setURLContent(String URL){ mURL = URL; } public void updateURLContent(String URL){ mURL = URL; WebView myWebView = (WebView) getView().findViewById(R.id.pageInfo); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setWebViewClient(new MyWebViewClient()); myWebView.loadUrl(mURL.trim()); } private class MyWebViewClient extends WebViewClient{ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){ return false; } } }
92381e4c2b44094d27b1d7a93cddf8a1d4657bc4
13,459
java
Java
src/main/java/mtas/search/spans/MtasSpanWithinQuery.java
mwasiluk/mtas-textexploration
96c7911e9c591c2bd4a419dbf0e2194813376776
[ "Apache-2.0" ]
4
2020-12-23T16:25:13.000Z
2021-11-21T19:50:58.000Z
src/main/java/mtas/search/spans/MtasSpanWithinQuery.java
mwasiluk/mtas-textexploration
96c7911e9c591c2bd4a419dbf0e2194813376776
[ "Apache-2.0" ]
6
2020-01-28T22:32:45.000Z
2021-09-08T18:04:47.000Z
src/main/java/mtas/search/spans/MtasSpanWithinQuery.java
mwasiluk/mtas-textexploration
96c7911e9c591c2bd4a419dbf0e2194813376776
[ "Apache-2.0" ]
2
2018-09-11T08:36:34.000Z
2021-11-21T20:02:07.000Z
36.08311
203
0.633257
998,318
package mtas.search.spans; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreMode; import org.apache.lucene.search.spans.SpanWeight; import org.apache.lucene.search.spans.SpanWithinQuery; import mtas.search.spans.util.MtasMaximumExpandSpanQuery; import mtas.search.spans.util.MtasSpanQuery; /** * The Class MtasSpanWithinQuery. */ public class MtasSpanWithinQuery extends MtasSpanQuery { /** The base query. */ private SpanWithinQuery baseQuery; /** The small query. */ private MtasSpanQuery smallQuery; /** The big query. */ private MtasSpanQuery bigQuery; /** The left boundary big minimum. */ private int leftBoundaryBigMinimum; /** The left boundary big maximum. */ private int leftBoundaryBigMaximum; /** The right boundary big maximum. */ private int rightBoundaryBigMaximum; /** The right boundary big minimum. */ private int rightBoundaryBigMinimum; /** The auto adjust big query. */ private boolean autoAdjustBigQuery; /** The field. */ String field; /** * Instantiates a new mtas span within query. * * @param q1 the q 1 * @param q2 the q 2 */ public MtasSpanWithinQuery(MtasSpanQuery q1, MtasSpanQuery q2) { this(q1, q2, 0, 0, 0, 0, true); } /** * Instantiates a new mtas span within query. * * @param q1 the q 1 * @param q2 the q 2 * @param leftMinimum the left minimum * @param leftMaximum the left maximum * @param rightMinimum the right minimum * @param rightMaximum the right maximum * @param adjustBigQuery the adjust big query */ public MtasSpanWithinQuery(MtasSpanQuery q1, MtasSpanQuery q2, int leftMinimum, int leftMaximum, int rightMinimum, int rightMaximum, boolean adjustBigQuery) { super(null, null); bigQuery = q1; smallQuery = q2; leftBoundaryBigMinimum = leftMinimum; leftBoundaryBigMaximum = leftMaximum; rightBoundaryBigMinimum = rightMinimum; rightBoundaryBigMaximum = rightMaximum; autoAdjustBigQuery = adjustBigQuery; // recompute width Integer minimumWidth = null; Integer maximumWidth = null; if (bigQuery != null) { maximumWidth = bigQuery.getMaximumWidth(); maximumWidth = (maximumWidth != null) ? maximumWidth + rightBoundaryBigMaximum + leftBoundaryBigMaximum : null; } if (smallQuery != null) { if (smallQuery.getMaximumWidth() != null && (maximumWidth == null || smallQuery.getMaximumWidth() < maximumWidth)) { maximumWidth = smallQuery.getMaximumWidth(); } minimumWidth = smallQuery.getMinimumWidth(); } setWidth(minimumWidth, maximumWidth); // compute field if (bigQuery != null && bigQuery.getField() != null) { field = bigQuery.getField(); } else if (smallQuery != null && smallQuery.getField() != null) { field = smallQuery.getField(); } else { field = null; } if (field != null) { baseQuery = new SpanWithinQuery(new MtasMaximumExpandSpanQuery(bigQuery, leftBoundaryBigMinimum, leftBoundaryBigMaximum, rightBoundaryBigMinimum, rightBoundaryBigMaximum), smallQuery); } else { baseQuery = null; } } /* * (non-Javadoc) * * @see mtas.search.spans.util.MtasSpanQuery#rewrite(org.apache.lucene.index. * IndexReader) */ @Override public MtasSpanQuery rewrite(IndexReader reader) throws IOException { MtasSpanQuery newBigQuery = bigQuery.rewrite(reader); MtasSpanQuery newSmallQuery = smallQuery.rewrite(reader); if (newBigQuery == null || newBigQuery instanceof MtasSpanMatchNoneQuery || newSmallQuery == null || newSmallQuery instanceof MtasSpanMatchNoneQuery) { return new MtasSpanMatchNoneQuery(field); } if (newSmallQuery.getMinimumWidth() != null && newBigQuery.getMaximumWidth() != null && newSmallQuery.getMinimumWidth() > (newBigQuery.getMaximumWidth() + leftBoundaryBigMaximum + rightBoundaryBigMaximum)) { return new MtasSpanMatchNoneQuery(field); } if (autoAdjustBigQuery) { if (newBigQuery instanceof MtasSpanRecurrenceQuery) { MtasSpanRecurrenceQuery recurrenceQuery = (MtasSpanRecurrenceQuery) newBigQuery; if (recurrenceQuery.getIgnoreQuery() == null && recurrenceQuery.getQuery() instanceof MtasSpanMatchAllQuery) { rightBoundaryBigMaximum += leftBoundaryBigMaximum + recurrenceQuery.getMaximumRecurrence(); rightBoundaryBigMinimum += leftBoundaryBigMinimum + recurrenceQuery.getMinimumRecurrence(); leftBoundaryBigMaximum = 0; leftBoundaryBigMinimum = 0; newBigQuery = new MtasSpanMatchAllQuery(field); // System.out.println("REPLACE WITH " + newBigQuery + " ([" // + leftBoundaryMinimum + "," + leftBoundaryMaximum + "],[" // + rightBoundaryMinimum + "," + rightBoundaryMaximum + "])"); return new MtasSpanWithinQuery(newBigQuery, newSmallQuery, leftBoundaryBigMinimum, leftBoundaryBigMaximum, rightBoundaryBigMinimum, rightBoundaryBigMaximum, autoAdjustBigQuery).rewrite(reader); } } else if (newBigQuery instanceof MtasSpanMatchAllQuery) { if (leftBoundaryBigMaximum > 0) { rightBoundaryBigMaximum += leftBoundaryBigMaximum; rightBoundaryBigMinimum += leftBoundaryBigMinimum; leftBoundaryBigMaximum = 0; leftBoundaryBigMinimum = 0; // System.out.println("REPLACE WITH " + newBigQuery + " ([" // + leftBoundaryMinimum + "," + leftBoundaryMaximum + "],[" // + rightBoundaryMinimum + "," + rightBoundaryMaximum + "])"); return new MtasSpanWithinQuery(newBigQuery, newSmallQuery, leftBoundaryBigMinimum, leftBoundaryBigMaximum, rightBoundaryBigMinimum, rightBoundaryBigMaximum, autoAdjustBigQuery).rewrite(reader); } } else if (newBigQuery instanceof MtasSpanSequenceQuery) { MtasSpanSequenceQuery sequenceQuery = (MtasSpanSequenceQuery) newBigQuery; if (sequenceQuery.getIgnoreQuery() == null) { List<MtasSpanSequenceItem> items = sequenceQuery.getItems(); List<MtasSpanSequenceItem> newItems = new ArrayList<>(); int newLeftBoundaryMinimum = 0; int newLeftBoundaryMaximum = 0; int newRightBoundaryMinimum = 0; int newRightBoundaryMaximum = 0; for (int i = 0; i < items.size(); i++) { // first item if (i == 0) { if (items.get(i).getQuery() instanceof MtasSpanMatchAllQuery) { newLeftBoundaryMaximum++; if (!items.get(i).isOptional()) { newLeftBoundaryMinimum++; } } else if (items.get(i) .getQuery() instanceof MtasSpanRecurrenceQuery) { MtasSpanRecurrenceQuery msrq = (MtasSpanRecurrenceQuery) items .get(i).getQuery(); if (msrq.getQuery() instanceof MtasSpanMatchAllQuery) { newLeftBoundaryMaximum += msrq.getMaximumRecurrence(); if (!items.get(i).isOptional()) { newLeftBoundaryMinimum += msrq.getMinimumRecurrence(); } } else { newItems.add(items.get(i)); } } else { newItems.add(items.get(i)); } // last item } else if (i == (items.size() - 1)) { if (items.get(i).getQuery() instanceof MtasSpanMatchAllQuery) { newRightBoundaryMaximum++; if (!items.get(i).isOptional()) { newRightBoundaryMinimum++; } } else if (items.get(i) .getQuery() instanceof MtasSpanRecurrenceQuery) { MtasSpanRecurrenceQuery msrq = (MtasSpanRecurrenceQuery) items .get(i).getQuery(); if (msrq.getQuery() instanceof MtasSpanMatchAllQuery) { newRightBoundaryMaximum += msrq.getMaximumRecurrence(); if (!items.get(i).isOptional()) { newRightBoundaryMinimum += msrq.getMinimumRecurrence(); } } else { newItems.add(items.get(i)); } } else { newItems.add(items.get(i)); } // other items } else { newItems.add(items.get(i)); } } leftBoundaryBigMaximum += newLeftBoundaryMaximum; leftBoundaryBigMinimum += newLeftBoundaryMinimum; rightBoundaryBigMaximum += newRightBoundaryMaximum; rightBoundaryBigMinimum += newRightBoundaryMinimum; if (newItems.isEmpty()) { rightBoundaryBigMaximum = Math.max(0, rightBoundaryBigMaximum + leftBoundaryBigMaximum - 1); rightBoundaryBigMinimum = Math.max(0, rightBoundaryBigMinimum + leftBoundaryBigMinimum - 1); leftBoundaryBigMaximum = 0; leftBoundaryBigMinimum = 0; newItems.add(new MtasSpanSequenceItem( new MtasSpanMatchAllQuery(field), false)); } if (!items.equals(newItems) || newLeftBoundaryMaximum > 0 || newRightBoundaryMaximum > 0) { newBigQuery = (new MtasSpanSequenceQuery(newItems, null, null)) .rewrite(reader); // System.out.println("REPLACE WITH " + newBigQuery + " ([" // + leftBoundaryMinimum + "," + leftBoundaryMaximum + "],[" // + rightBoundaryMinimum + "," + rightBoundaryMaximum + "])"); return new MtasSpanWithinQuery(newBigQuery, newSmallQuery, leftBoundaryBigMinimum, leftBoundaryBigMaximum, rightBoundaryBigMinimum, rightBoundaryBigMaximum, autoAdjustBigQuery).rewrite(reader); } } } } if (!newBigQuery.equals(bigQuery) || !newSmallQuery.equals(smallQuery)) { return (new MtasSpanWithinQuery(newBigQuery, newSmallQuery, leftBoundaryBigMinimum, leftBoundaryBigMaximum, rightBoundaryBigMinimum, rightBoundaryBigMaximum, autoAdjustBigQuery)) .rewrite(reader); } else if (newBigQuery.equals(newSmallQuery)) { return newBigQuery; } else { baseQuery = (SpanWithinQuery) baseQuery.rewrite(reader); return super.rewrite(reader); } } /* * (non-Javadoc) * * @see org.apache.lucene.search.spans.SpanQuery#getField() */ @Override public String getField() { return field; } /* * (non-Javadoc) * * @see * org.apache.lucene.search.spans.SpanQuery#createWeight(org.apache.lucene. * search.IndexSearcher, boolean) */ @Override public SpanWeight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException { return baseQuery.createWeight(searcher, scoreMode, boost); } /* * (non-Javadoc) * * @see org.apache.lucene.search.Query#toString(java.lang.String) */ @Override public String toString(String field) { StringBuilder buffer = new StringBuilder(); buffer.append(this.getClass().getSimpleName() + "(["); if (smallQuery != null) { buffer.append(smallQuery.toString(smallQuery.getField())); } else { buffer.append("null"); } buffer.append(","); if (bigQuery != null) { buffer.append(bigQuery.toString(bigQuery.getField())); } else { buffer.append("null"); } buffer.append( "],[" + leftBoundaryBigMinimum + "," + leftBoundaryBigMaximum + "],[" + rightBoundaryBigMinimum + "," + rightBoundaryBigMaximum + "])"); return buffer.toString(); } /* * (non-Javadoc) * * @see org.apache.lucene.search.Query#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final MtasSpanWithinQuery that = (MtasSpanWithinQuery) obj; return baseQuery.equals(that.baseQuery) && leftBoundaryBigMinimum == that.leftBoundaryBigMinimum && leftBoundaryBigMaximum == that.leftBoundaryBigMaximum && rightBoundaryBigMinimum == that.rightBoundaryBigMinimum && rightBoundaryBigMaximum == that.rightBoundaryBigMaximum; } /* * (non-Javadoc) * * @see org.apache.lucene.search.Query#hashCode() */ @Override public int hashCode() { return Objects.hash(this.getClass().getSimpleName(), smallQuery, bigQuery, leftBoundaryBigMinimum, leftBoundaryBigMaximum, rightBoundaryBigMinimum, rightBoundaryBigMaximum,autoAdjustBigQuery); } /* * (non-Javadoc) * * @see mtas.search.spans.util.MtasSpanQuery#disableTwoPhaseIterator() */ @Override public void disableTwoPhaseIterator() { super.disableTwoPhaseIterator(); bigQuery.disableTwoPhaseIterator(); smallQuery.disableTwoPhaseIterator(); } @Override public boolean isMatchAllPositionsQuery() { return false; } }
92381e61edd6b89bb4e02c7e385075fe512e8387
1,877
java
Java
src/main/java/serguei/http/UpToBorderStreamReader.java
Serguei-P/http
1a9a5be5dae29346137ae4445a8c98fc14bec5e1
[ "MIT" ]
5
2017-06-21T19:33:33.000Z
2022-02-17T16:30:57.000Z
src/main/java/serguei/http/UpToBorderStreamReader.java
Serguei-P/http
1a9a5be5dae29346137ae4445a8c98fc14bec5e1
[ "MIT" ]
1
2019-05-24T08:51:17.000Z
2019-09-02T10:45:17.000Z
src/main/java/serguei/http/UpToBorderStreamReader.java
Serguei-P/http
1a9a5be5dae29346137ae4445a8c98fc14bec5e1
[ "MIT" ]
2
2020-05-28T23:04:09.000Z
2021-05-26T14:35:37.000Z
28.014925
73
0.500799
998,319
package serguei.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; class UpToBorderStreamReader { private final InputStream inputStream; private final byte[] border; private int lastByte = -1; private int replayPos = 0; private int maxReplayPos = 0; UpToBorderStreamReader(InputStream inputStream, byte[] border) { this.inputStream = inputStream; this.border = border; } public byte[] read() throws IOException { int matchedBytes = 0; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int ch; while ((ch = nextByte()) != -1) { byte b = (byte)ch; if (b == border[matchedBytes]) { matchedBytes++; if (matchedBytes == border.length) { return outputStream.toByteArray(); } } else { if (matchedBytes > 0) { outputStream.write(border[replayPos]); replayPos++; maxReplayPos = matchedBytes; lastByte = b; matchedBytes = 0; } else { outputStream.write(b); } } } if (matchedBytes > 0) { outputStream.write(border, 0, matchedBytes); } return outputStream.toByteArray(); } private int nextByte() throws IOException { if (lastByte != -1) { if (replayPos < maxReplayPos) { return border[replayPos++]; } else { replayPos = 0; maxReplayPos = 0; int b = lastByte; lastByte = -1; return b; } } else { return inputStream.read(); } } }
92381ff5c91a561ab720cc7d11bfd388ae2c67a2
10,182
java
Java
src/main/java/org/jahia/modules/JahiaModule.java
wmnedel/modulesexporter
92454f93c69788c9bb676df7554812cecad986a1
[ "MIT" ]
null
null
null
src/main/java/org/jahia/modules/JahiaModule.java
wmnedel/modulesexporter
92454f93c69788c9bb676df7554812cecad986a1
[ "MIT" ]
null
null
null
src/main/java/org/jahia/modules/JahiaModule.java
wmnedel/modulesexporter
92454f93c69788c9bb676df7554812cecad986a1
[ "MIT" ]
null
null
null
35.477352
149
0.628855
998,320
package org.jahia.modules; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.jahia.data.templates.JahiaTemplatesPackage; import org.jahia.registries.ServicesRegistry; import org.jahia.services.content.JCRNodeWrapper; import org.jahia.services.content.JCRSessionWrapper; import org.osgi.framework.Bundle; import org.osgi.framework.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.query.InvalidQueryException; import javax.jcr.query.Query; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; /**     * Jahia module Class definition */ public class JahiaModule { private static Logger logger = LoggerFactory.getLogger(JahiaModule.class); public static final int JAHIA_MODULE_SOURCE_HIGHER = 1; public static final int JAHIA_MODULE_TARGET_HIGHER = 2; public static final int JAHIA_MODULE_VERSION_EQUAL = 0; protected static final String JAHIA_BUNDLE_TYPE = "MODULE"; private static final String MODULE_MANAGEMENT_QUERY = "SELECT * FROM [jnt:moduleManagementBundle] where NAME() = '"; private static final String BUNDLES_URL = "/modules/api/bundles"; private static final int MAGIC_VERSION_LEVELS_NUMBER = 10; private String name; private String version; private String state; private long versionNumber; /**      * Constructor for JahiaModule * @param name Module name * @param moduleVersion Module version * @param state Module current state */ public JahiaModule(String name, String moduleVersion, String state) { this.name = name; this.version = moduleVersion; this.state = state; this.versionNumber = createVersionNumber(moduleVersion); } /**      * Constructor for JahiaModule * @param name Module name * @param moduleVersion Module version */ public JahiaModule(String name, String moduleVersion) { this.name = name; this.version = moduleVersion; this.versionNumber = createVersionNumber(moduleVersion); } /**      * Constructor for JahiaModule based on jar filename * @param name Jar module name */ public JahiaModule(String name) { String tempNameVersion = name.replace(".jar",""); this.name = tempNameVersion.substring(0, tempNameVersion.lastIndexOf("-")); this.version = tempNameVersion.substring(tempNameVersion.lastIndexOf("-") + 1); this.versionNumber = createVersionNumber(this.version); } /**      * Creates a fixed lenght version number for further comparison. It appends up to 10 zeros at the end of the version * so the number can be compared * @param version Module version */ private long createVersionNumber(String version) { String versionParsed = version.replaceAll("[^0-9]", ""); for (int i = versionParsed.length(); i < MAGIC_VERSION_LEVELS_NUMBER; i++) { versionParsed = versionParsed + "0"; } return new Long(versionParsed); } public String getNameAndVersion() { return name + "-" + version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public long getVersionNumber() { return versionNumber; } public void setVersion(String version) { this.version = version; } public String getState() { return state; } public void setState(String state) { this.state = state; } /**      * Method to compare Jahia module versions * @param source Source module object * @param target Target module object * @return JAHIA_MODULE_SOURCE_HIGHER if source version is higher * JAHIA_MODULE_TARGET_HIGHER if target version is higher * JAHIA_MODULE_VERSION_EQUAL if versions are equal */ public static int compareVersions(JahiaModule source, JahiaModule target) { if (source.getVersionNumber() > target.getVersionNumber()) { return JAHIA_MODULE_SOURCE_HIGHER; } else if (target.getVersionNumber() > source.getVersionNumber()) { return JAHIA_MODULE_TARGET_HIGHER; } else { return JAHIA_MODULE_VERSION_EQUAL; } } /**      * Performs the module installation in Jahia * @param jcrSessionWrapper The current JCR session * @param connection Connection object * @param module Jahia module object * @param autoStart Indicates if the module will be started after installation in target * @return Message to be reported in frontend for this module at the end of the migration */ public static String installModule( JCRSessionWrapper jcrSessionWrapper, HttpConnectionHelper connection, JahiaModule module, boolean autoStart) { logger.debug("Installing module {} on host {}", module.getNameAndVersion(), connection.getHostName()); String query = MODULE_MANAGEMENT_QUERY + module.getNameAndVersion() + ".jar'"; String report = ""; try { NodeIterator iterator = jcrSessionWrapper .getWorkspace() .getQueryManager() .createQuery(query, Query.JCR_SQL2) .execute() .getNodes(); if (iterator.getSize() < 1) { report = "Unable to retreive the modules binary files from JCR"; return report; } while (iterator.hasNext()) { final JCRNodeWrapper node = (JCRNodeWrapper) iterator.nextNode(); String nodeName = node.getName(); logger.debug("Migration Module {}", nodeName); Node fileContent = node.getNode("jcr:content"); InputStream content = fileContent.getProperty("jcr:data").getBinary().getStream(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("start", Boolean.toString(autoStart), ContentType.TEXT_PLAIN); builder.addBinaryBody("bundle", content); HttpEntity multipart = builder.build(); String result = connection.executePostRequest(BUNDLES_URL, multipart); if (result != null) { return result; } } } catch (PathNotFoundException e) { report = String.format("Module %s.jar was not installed. Reason: PathNotFoundException", module.getNameAndVersion()); logger.error(report); logger.debug(e.getMessage(), e); } catch (InvalidQueryException e) { report = String.format("Module %s.jar was not installed. Reason: InvalidQueryException", module.getNameAndVersion()); logger.error(report); logger.debug(e.getMessage(), e); } catch (RepositoryException e) { report = String.format("Module %s.jar was not installed. Reason: RepositoryException", module.getNameAndVersion()); logger.error(report); logger.debug(e.getMessage(), e); } if (!report.isEmpty()) { return report; } return "Unknown error while installing the module" + module.getNameAndVersion(); } /** * Get a list of modules available on the local/source instance * @param onlyStartedModules Indicates if only started modules will be returned * @return List of installed local modules */ protected static List<JahiaModule> getLocalModules(boolean onlyStartedModules) { Map<Bundle, JahiaTemplatesPackage> installedModules = ServicesRegistry.getInstance().getJahiaTemplateManagerService().getRegisteredBundles(); List<JahiaModule> localModules = new ArrayList<>(); for (Map.Entry<Bundle, JahiaTemplatesPackage> module : installedModules.entrySet()) { String moduleType = module.getValue().getModuleType(); if (moduleType.equalsIgnoreCase("module")) { String moduleName = module.getValue().getId(); Version version = module.getKey().getVersion(); String moduleVersion = version.toString(); String moduleState = module.getValue().getState().toString(); JahiaModule jmodule = new JahiaModule(moduleName, moduleVersion, moduleState); if (onlyStartedModules == true && moduleState.toLowerCase().contains("started") == false) { continue; } localModules.add(jmodule); } } return localModules; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JahiaModule that = (JahiaModule) o; return Objects.equals(name, that.name) && Objects.equals(version, that.version); } /**      * Indicates if the object passed as parameter has a newer version than "this" * @param o Object to be compared to this * @return true if newer; false if older or equal */ public boolean newerVersion(Object o) { if (this == o) { return false; } if (o == null || getClass() != o.getClass()) { return false; } JahiaModule that = (JahiaModule) o; return name.equals(that.name) && compareVersions(this, that) == JAHIA_MODULE_SOURCE_HIGHER; } @Override public int hashCode() { return Objects.hash(name, version, state); } }
92382046d9b02d69c25d696540327c634399dcbf
2,694
java
Java
src/main/java/com/zf1976/ddns/api/signer/rpc/AliyunSignatureComposer.java
Coupile1/vertx-ddns
0b232d8efb0d7feef112b4e66b7e194708ddbd16
[ "MIT" ]
1
2021-10-29T23:43:29.000Z
2021-10-29T23:43:29.000Z
src/main/java/com/zf1976/ddns/api/signer/rpc/AliyunSignatureComposer.java
Coupile1/vertx-ddns
0b232d8efb0d7feef112b4e66b7e194708ddbd16
[ "MIT" ]
null
null
null
src/main/java/com/zf1976/ddns/api/signer/rpc/AliyunSignatureComposer.java
Coupile1/vertx-ddns
0b232d8efb0d7feef112b4e66b7e194708ddbd16
[ "MIT" ]
null
null
null
35.447368
115
0.622494
998,321
package com.zf1976.ddns.api.signer.rpc; import com.zf1976.ddns.api.signer.algorithm.Signer; import com.zf1976.ddns.enums.HttpMethod; import com.zf1976.ddns.util.ApiURLEncoderUtil; import com.zf1976.ddns.util.DataTypeConverterUtil; import java.util.Arrays; import java.util.Map; @SuppressWarnings("unused") public class AliyunSignatureComposer implements RpcAPISignatureComposer { private final static String SEPARATOR = "&"; private final Signer signer = Signer.getSHA1Signer(); private AliyunSignatureComposer() { } private static final class ComposerHolder { private static final RpcAPISignatureComposer composer = new AliyunSignatureComposer(); } public static RpcAPISignatureComposer getComposer() { return ComposerHolder.composer; } @Override public String composeStringToSign(HttpMethod method, Map<String, Object> queryParamMap) { String[] sortedKeys = queryParamMap.keySet() .toArray(new String[]{}); Arrays.sort(sortedKeys); StringBuilder canonicalizeQueryString = new StringBuilder(); for (String key : sortedKeys) { canonicalizeQueryString.append("&") .append(ApiURLEncoderUtil.aliyunPercentEncode(key)) .append("=") .append(ApiURLEncoderUtil.aliyunPercentEncode(queryParamMap.get(key) .toString())); } return method.name() + SEPARATOR + ApiURLEncoderUtil.aliyunPercentEncode("/") + SEPARATOR + ApiURLEncoderUtil.aliyunPercentEncode(canonicalizeQueryString.substring(1)); } @Override public String toSignatureUrl(String accessKeySecret, String urlPattern, HttpMethod methodType, Map<String, Object> queries) { // stringToSign final var stringToSign = this.composeStringToSign(methodType, queries); // 签名 final var signature = this.signer.signString(stringToSign, accessKeySecret); final var signatureBase64 = DataTypeConverterUtil._printBase64Binary(signature); return canonicalizeRequestUrl(urlPattern, queries, ApiURLEncoderUtil.aliyunPercentEncode(signatureBase64)); } @Override public String signatureMethod() { return this.signer.getSignerName(); } @Override public String getSignerVersion() { return this.signer.getSignerVersion(); } }
92382197fec73d64f444577e25786bf6d8e1a8fb
1,179
java
Java
core/src/test/java/com/ctrip/ferriswheel/core/formula/func/date/TestToday.java
littleorca/ferris-wheel
aede3ba7e40518856b47e9df59ea221c00c6d871
[ "MIT" ]
17
2019-02-02T03:43:25.000Z
2020-07-23T04:45:52.000Z
core/src/test/java/com/ctrip/ferriswheel/core/formula/func/date/TestToday.java
ctripcorp/ferris-wheel
1d267fa07c5c7c44edd044ad630715d0be1d82e1
[ "MIT" ]
null
null
null
core/src/test/java/com/ctrip/ferriswheel/core/formula/func/date/TestToday.java
ctripcorp/ferris-wheel
1d267fa07c5c7c44edd044ad630715d0be1d82e1
[ "MIT" ]
3
2019-04-03T12:07:53.000Z
2020-04-15T07:43:31.000Z
38.032258
105
0.688719
998,322
package com.ctrip.ferriswheel.core.formula.func.date; import com.ctrip.ferriswheel.common.variant.Variant; import com.ctrip.ferriswheel.common.variant.VariantType; import com.ctrip.ferriswheel.core.formula.FakeEvalContext; import junit.framework.TestCase; import java.util.Calendar; public class TestToday extends TestCase { public void testGetName() { assertEquals("TODAY", new Today().getName()); } public void testEval() { FakeEvalContext context = new FakeEvalContext(); new Today().evaluate(null, context); assertEquals(1, context.getOperands().size()); Variant date = context.popOperand(); assertEquals(VariantType.DATE, date.valueType()); assertEquals(System.currentTimeMillis(), date.dateValue().getTime(), 24 * 60 * 60 * 1000 + 1000); Calendar cal = Calendar.getInstance(); cal.setTime(date.dateValue()); assertEquals(0, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(0, cal.get(Calendar.SECOND)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(0, date.dateValue().getTime() % 1000); } }
9238230292e39df1acaf2eea82f5fa3621120ae1
5,643
java
Java
diboot-core/src/main/java/com/diboot/core/vo/Pagination.java
dibo-software/diboo
7c80ccfb3fd274b5ecca45573a37b3bb219266ac
[ "ECL-2.0", "Apache-2.0" ]
531
2018-11-02T06:40:29.000Z
2022-03-31T16:21:15.000Z
diboot-core/src/main/java/com/diboot/core/vo/Pagination.java
dibo-software/diboo
7c80ccfb3fd274b5ecca45573a37b3bb219266ac
[ "ECL-2.0", "Apache-2.0" ]
17
2020-07-21T12:48:16.000Z
2022-03-08T16:06:43.000Z
diboot-core/src/main/java/com/diboot/core/vo/Pagination.java
dibo-software/diboo
7c80ccfb3fd274b5ecca45573a37b3bb219266ac
[ "ECL-2.0", "Apache-2.0" ]
134
2018-11-04T13:04:40.000Z
2022-03-28T13:23:57.000Z
28.765306
100
0.580525
998,323
/* * Copyright (c) 2015-2020, www.dibo.ltd (nnheo@example.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.diboot.core.vo; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.diboot.core.binding.cache.BindingCacheManager; import com.diboot.core.binding.parser.PropInfo; import com.diboot.core.config.BaseConfig; import com.diboot.core.config.Cons; import com.diboot.core.entity.AbstractEntity; import com.diboot.core.util.S; import com.diboot.core.util.V; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * 分页 (属性以下划线开头以避免与提交参数字段冲突) * * @author anpch@example.com * @version v2.0 * @date 2019/01/01 */ @Getter @Setter @Accessors(chain = true) public class Pagination implements Serializable { private static final Logger log = LoggerFactory.getLogger(Pagination.class); private static final long serialVersionUID = -4083929594112114522L; /*** * 当前页 */ private int pageIndex = 1; /*** * 默认每页数量10 */ private int pageSize = BaseConfig.getPageSize(); /*** * count总数 */ private long totalCount = 0; /** * 默认排序 */ private static final String DEFAULT_ORDER_BY = Cons.FieldName.id.name() + ":" + Cons.ORDER_DESC; /** * 排序 */ private String orderBy = DEFAULT_ORDER_BY; private Class<? extends AbstractEntity> entityClass; public Pagination() { } public Pagination(Class<? extends AbstractEntity> entityClass) { this.entityClass = entityClass; } /*** * 指定当前页数 */ public Pagination(int pageIndex) { setPageIndex(pageIndex); } public void setPageSize(int pageSize) { if (pageSize > 1000) { log.warn("分页pageSize过大,将被调整为默认限值,请检查调用是否合理!pageSize=" + pageSize); pageSize = 1000; } this.pageSize = pageSize; } /*** * 获取总的页数 * @return */ public int getTotalPage() { if (totalCount <= 0) { return 0; } return (int) Math.ceil((float) totalCount / pageSize); } /** * 清空默认排序 */ public void clearDefaultOrder() { // 是否为默认排序 if (isDefaultOrderBy()) { orderBy = null; } } /** * 是否为默认排序 * * @return */ @JsonIgnore public boolean isDefaultOrderBy() { return V.equals(orderBy, DEFAULT_ORDER_BY); } /** * 转换为IPage * * @param <T> * @return */ public <T> Page<T> toPage() { List<OrderItem> orderItemList = null; // 解析排序 if (V.notEmpty(this.orderBy)) { orderItemList = new ArrayList<>(); // orderBy=shortName:DESC,age:ASC,birthdate String[] orderByFields = S.split(this.orderBy); for (String field : orderByFields) { V.securityCheck(field); if (field.contains(":")) { String[] fieldAndOrder = S.split(field, ":"); String fieldName = fieldAndOrder[0]; String columnName = S.toSnakeCase(fieldName); PropInfo propInfo = getEntityPropInfo(); if(propInfo != null){ // 前参数为字段名 if(propInfo.getFieldToColumnMap().containsKey(fieldName)){ columnName = propInfo.getFieldToColumnMap().get(fieldName); } // 前参数为列名 else if(propInfo.getColumnToFieldMap().containsKey(fieldName)){ columnName = fieldName; } } if (Cons.ORDER_DESC.equalsIgnoreCase(fieldAndOrder[1])) { orderItemList.add(OrderItem.desc(columnName)); } else { orderItemList.add(OrderItem.asc(columnName)); } } else { orderItemList.add(OrderItem.asc(S.toSnakeCase(field))); } } } Page<T> page = new Page<T>() .setCurrent(getPageIndex()) .setSize(getPageSize()) // 如果前端传递过来了缓存的总数,则本次不再count统计 .setTotal(getTotalCount() > 0 ? -1 : getTotalCount()); if (orderItemList != null) { page.addOrder(orderItemList); } return page; } /** * 当id不是主键的时候,默认使用创建时间排序 * * @return */ public String setDefaultCreateTimeOrderBy() { return this.orderBy = Cons.FieldName.createTime.name() + ":" + Cons.ORDER_DESC; } private PropInfo getEntityPropInfo(){ if (this.entityClass != null) { return BindingCacheManager.getPropInfoByClass(this.entityClass); } return null; } }
9238232e53e0087f991272194a2c97061335a532
448
java
Java
product/src/main/java/com/example/mall/product/service/SpuCommentService.java
OrangeFeather/mall
1f57a5208c0950e7ecd06ba86d749a46abb0bd27
[ "Apache-2.0" ]
null
null
null
product/src/main/java/com/example/mall/product/service/SpuCommentService.java
OrangeFeather/mall
1f57a5208c0950e7ecd06ba86d749a46abb0bd27
[ "Apache-2.0" ]
null
null
null
product/src/main/java/com/example/mall/product/service/SpuCommentService.java
OrangeFeather/mall
1f57a5208c0950e7ecd06ba86d749a46abb0bd27
[ "Apache-2.0" ]
null
null
null
21.47619
71
0.764967
998,324
package com.example.mall.product.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.common.utils.PageUtils; import com.example.mall.product.entity.SpuCommentEntity; import java.util.Map; /** * 商品评价 * * @author chen * @email dycjh@example.com * @date 2021-08-04 21:47:44 */ public interface SpuCommentService extends IService<SpuCommentEntity> { PageUtils queryPage(Map<String, Object> params); }
92382404b944d7707fa27653402da7e5f1be5587
960
java
Java
src/StockIT-v1-release_source_from_JADX/sources/com/google/android/exoplayer2/offline/FilteringManifestParser.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-11-23T10:12:35.000Z
2021-11-23T10:12:35.000Z
src/StockIT-v2-release_source_from_JADX/sources/com/google/android/exoplayer2/offline/FilteringManifestParser.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
null
null
null
src/StockIT-v2-release_source_from_JADX/sources/com/google/android/exoplayer2/offline/FilteringManifestParser.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-10-01T13:14:19.000Z
2021-10-01T13:14:19.000Z
38.4
114
0.747917
998,325
package com.google.android.exoplayer2.offline; import android.net.Uri; import com.google.android.exoplayer2.offline.FilterableManifest; import com.google.android.exoplayer2.upstream.ParsingLoadable; import java.io.IOException; import java.io.InputStream; import java.util.List; public final class FilteringManifestParser<T extends FilterableManifest<T>> implements ParsingLoadable.Parser<T> { private final ParsingLoadable.Parser<T> parser; private final List<StreamKey> streamKeys; public FilteringManifestParser(ParsingLoadable.Parser<T> parser2, List<StreamKey> list) { this.parser = parser2; this.streamKeys = list; } public T parse(Uri uri, InputStream inputStream) throws IOException { T t = (FilterableManifest) this.parser.parse(uri, inputStream); List<StreamKey> list = this.streamKeys; return (list == null || list.isEmpty()) ? t : (FilterableManifest) t.copy(this.streamKeys); } }
9238243b7bf6b731c4fb28863bd44e835f7c46c3
716
java
Java
stormfake/src/main/java/org/apache/fake/storm/model/ResourceInfo.java
yilong2001/fakestorm
bbfa67ff765fcc0d1a5dbb8eced8bbd285199423
[ "Apache-1.1" ]
null
null
null
stormfake/src/main/java/org/apache/fake/storm/model/ResourceInfo.java
yilong2001/fakestorm
bbfa67ff765fcc0d1a5dbb8eced8bbd285199423
[ "Apache-1.1" ]
null
null
null
stormfake/src/main/java/org/apache/fake/storm/model/ResourceInfo.java
yilong2001/fakestorm
bbfa67ff765fcc0d1a5dbb8eced8bbd285199423
[ "Apache-1.1" ]
null
null
null
20.457143
91
0.657821
998,326
package org.apache.fake.storm.model; import org.apache.fake.storm.utils.JsonSerializable; import java.io.Serializable; /** * Created by yilong on 2017/8/26. */ public class ResourceInfo extends JsonSerializable<ResourceInfo> implements Serializable { private int cpuRatio; private int memMegas; public ResourceInfo(int cpu, int mem) { this.cpuRatio = cpu; this.memMegas = mem; } public int getCpuRatio() { return cpuRatio; } public void setCpuRatio(int cpuRatio) { this.cpuRatio = cpuRatio; } public int getMemMegas() { return memMegas; } public void setMemMegas(int memMegas) { this.memMegas = memMegas; } }
92382514773f7e008ccdf15bf0c0ebe9fd2ecd7c
1,695
java
Java
src/main/java/br/com/msansone/apistockscontrol/service/TransactionServiceImpl.java
msansone73/spring-boot-stockscontrol
42ca95ed912a2b245ba374e0e64f9ad96098db4c
[ "MIT" ]
null
null
null
src/main/java/br/com/msansone/apistockscontrol/service/TransactionServiceImpl.java
msansone73/spring-boot-stockscontrol
42ca95ed912a2b245ba374e0e64f9ad96098db4c
[ "MIT" ]
null
null
null
src/main/java/br/com/msansone/apistockscontrol/service/TransactionServiceImpl.java
msansone73/spring-boot-stockscontrol
42ca95ed912a2b245ba374e0e64f9ad96098db4c
[ "MIT" ]
null
null
null
30.267857
93
0.727434
998,327
package br.com.msansone.apistockscontrol.service; import br.com.msansone.apistockscontrol.model.Transaction; import br.com.msansone.apistockscontrol.repository.TransactionRepositoty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class TransactionServiceImpl implements TransactionService{ @Autowired TransactionRepositoty transactionRepositoty; @Override public List<Transaction> getAll() { return transactionRepositoty.findAll(); } @Override public List<Transaction> getByAccountId(Long id) { return transactionRepositoty.findAllByAccountId(id); } @Override public List<Transaction> getByStockId(Long id) { return transactionRepositoty.findAllByStockId(id); } @Override public Transaction getById(Long id) { return transactionRepositoty.findById(id).orElse(null); } @Override public Transaction add(Transaction transaction) { return transactionRepositoty.save(transaction); } @Override public Transaction change(Transaction transaction, Long id) throws NoSuchFieldException { Transaction atual = this.getById(id); if (atual==null){ throw new NoSuchFieldException("Transaction not found"); } atual.setTransactionType(transaction.getTransactionType()); atual.setQuantity(transaction.getQuantity()); atual.setStock(transaction.getStock()); atual.setAccount(transaction.getAccount()); atual.setUnitPrice(transaction.getUnitPrice()); return transactionRepositoty.save(atual); } }
9238258fb35146678be19fd5ba57b2822765b223
944
java
Java
src.test/test/Test_5_0_Typeset.java
rapidreport/java
eeeb052c0b374b5716fa9fc3642bf110ee80f361
[ "BSD-2-Clause" ]
null
null
null
src.test/test/Test_5_0_Typeset.java
rapidreport/java
eeeb052c0b374b5716fa9fc3642bf110ee80f361
[ "BSD-2-Clause" ]
null
null
null
src.test/test/Test_5_0_Typeset.java
rapidreport/java
eeeb052c0b374b5716fa9fc3642bf110ee80f361
[ "BSD-2-Clause" ]
null
null
null
26.971429
115
0.73411
998,328
package test; import java.io.FileOutputStream; import com.lowagie.text.pdf.BaseFont; import jp.co.systembase.report.Report; import jp.co.systembase.report.ReportPages; import jp.co.systembase.report.data.DummyDataSource; import jp.co.systembase.report.renderer.pdf.PdfRenderer; public class Test_5_0_Typeset { public static void main(String[] args) throws Throwable { String name = "test_5_0_typeset"; // Report.Compatibility._4_37_Typeset = true; Report report = new Report(ReadUtil.readJson("rrpt/" + name + ".rrpt")); report.fill(DummyDataSource.getInstance()); ReportPages pages = report.getPages(); { FileOutputStream fos = new FileOutputStream("out/" + name + ".pdf"); try{ PdfRenderer renderer = new PdfRenderer(fos); renderer.setting.gaijiFont = BaseFont.createFont("rrpt/font/eudc.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); pages.render(renderer); }finally{ fos.close(); } } } }
9238270cd54eeda2c9ac836d8627dd54a3a0e539
8,248
java
Java
src/application/Utility.java
LaszloGlant/PhotoAlbum
6438cd1539eb0b7dc739c961318c3102927d51ab
[ "MIT" ]
null
null
null
src/application/Utility.java
LaszloGlant/PhotoAlbum
6438cd1539eb0b7dc739c961318c3102927d51ab
[ "MIT" ]
null
null
null
src/application/Utility.java
LaszloGlant/PhotoAlbum
6438cd1539eb0b7dc739c961318c3102927d51ab
[ "MIT" ]
null
null
null
38.542056
176
0.591537
998,329
package application; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import view.AdminViewController; /** * * @author Brian Wong, Laszlo Glant * Contains the IO and other helper methods * */ public class Utility { /** * Outputs the database to the user.ser file * @param users all the users in the database */ public static void output(ArrayList<User> users) { try { FileOutputStream fileOut = new FileOutputStream("users.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(users); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in users.ser"); }catch(IOException i) { i.printStackTrace(); } } /** * Loads the database from the user.ser file * @return The database of users */ public static ArrayList<User> input() { ArrayList<User> newUsers= null; try { FileInputStream fileIn = new FileInputStream("users.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); newUsers = (ArrayList<User>) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return newUsers; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return newUsers; } return newUsers; } /** * return the newest image in the album * @param i index of user * @param j index of album * @return newest image */ public static String newestPhoto(int i, int j) { if (AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().size() == 0) { // no images, return "N/A" return "N/A"; } String currImage = AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().get(0); // set current newest to first item String latestImage = currImage; int latestMonth = Integer.parseInt(extractDate(new File(latestImage))[0]); int latestDay = Integer.parseInt(extractDate(new File(latestImage))[1]); int latestYear = Integer.parseInt(extractDate(new File(latestImage))[2]); for (int k = 1; k < AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().size(); k++) { currImage = AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().get(k); int currMonth = Integer.parseInt(extractDate(new File(currImage))[0]); int currDay = Integer.parseInt(extractDate(new File(currImage))[1]); int currYear = Integer.parseInt(extractDate(new File(currImage))[2]); if (PhotoSearch.compareDates(currYear, currMonth, currDay, latestYear, latestMonth, latestDay) < 0) { // images are in correct order, update latestMonth = currMonth; latestDay = currDay; latestYear = currYear; } } return latestMonth + "/" + latestDay + "/" + latestYear; } /** * return the oldest image in the album * @param i user index * @param j album index * @return oldest image in the album */ public static String oldestPhoto(int i, int j) { if (AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().size() == 0) { // no images, return "N/A" return "N/A"; } String currImage = AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().get(0); // set current newest to first item String latestImage = currImage; int latestMonth = Integer.parseInt(extractDate(new File(latestImage))[0]); int latestDay = Integer.parseInt(extractDate(new File(latestImage))[1]); int latestYear = Integer.parseInt(extractDate(new File(latestImage))[2]); for (int k = 1; k < AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().size(); k++) { currImage = AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().get(k); int currMonth = Integer.parseInt(extractDate(new File(currImage))[0]); int currDay = Integer.parseInt(extractDate(new File(currImage))[1]); int currYear = Integer.parseInt(extractDate(new File(currImage))[2]); if (PhotoSearch.compareDates(currYear, currMonth, currDay, latestYear, latestMonth, latestDay) > 0) { // images are in correct order, update latestMonth = currMonth; latestDay = currDay; latestYear = currYear; } } return latestMonth + "/" + latestDay + "/" + latestYear; } /** * set mi's year, month, and day fields * @param mi instance of MyImage, one image in the album */ public static void setDateTaken(MyImage mi) { File f = new File(mi.getPicturePath()); // System.out.println(f); // System.out.println("incoming path"+mi.getPicturePath()); // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); // String date = sdf.format(f.lastModified()); // System.out.println("After Format : " + date); String[] arr = extractDate(f); mi.setMonth(Integer.parseInt(arr[0])); mi.setDay(Integer.parseInt(arr[1])); mi.setYear(Integer.parseInt(arr[2])); } /** * Extracts the last modified date of the given file * @param f The file to get the date from * @return The date in a string format */ public static String[] extractDate(File f) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); String date = sdf.format(f.lastModified()); String[] arr = date.split("/"); return arr; } /** * return range of dates in album as String format * @param userNum integer index for user * @param albumNum integer index for album * @return String for range of dates, used to be displayed in GUI */ public static String dateRange(int userNum, int albumNum) { if (AdminViewController.users.get(userNum).getImageList().size() == 0) { return "N/A"; } return oldestPhoto(userNum, albumNum) + " - " + newestPhoto(userNum, albumNum); } /** * Prints the user database to the console * For testing purposes only */ public static void printUserList(){ int i, j, k; for (i = 0; i < AdminViewController.users.size(); i++){//user selector System.out.println("\nuser name "+AdminViewController.users.get(i).getUserName()+ " number of albums for the user " +AdminViewController.users.get(i).getAlbumList().size()); for (j = 0; j < AdminViewController.users.get(i).getAlbumList().size(); j++){//album selector System.out.println(" album name is " +AdminViewController.users.get(i).getAlbumList().get(j).getAlbumName() +" Number of images in this album: "+AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().size()); for (k = 0; k < AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().size(); k++){//images in albums System.out.println(" picture name: "+AdminViewController.users.get(i).getAlbumList().get(j).getPicsList().get(k) // +"; new location: "+AdminViewController.users.get(i).getAlbumList().get(j).getImageList().get(k).getLocation() // +"; new people: "+AdminViewController.users.get(i).getAlbumList().get(j).getImageList().get(k).getPeople() ); } } } } }
9238294221ff31f02de9949b492223c140c77af2
972
java
Java
src/main/java/com/alipay/api/domain/AlipayOpenMiniExperienceCancelModel.java
alipay/alipay-sdk-java-all
e87bc8e7f6750e168a5f9d37221124c085d1e3c1
[ "Apache-2.0" ]
333
2018-08-28T09:26:55.000Z
2022-03-31T07:26:42.000Z
src/main/java/com/alipay/api/domain/AlipayOpenMiniExperienceCancelModel.java
alipay/alipay-sdk-java-all
e87bc8e7f6750e168a5f9d37221124c085d1e3c1
[ "Apache-2.0" ]
46
2018-09-27T03:52:42.000Z
2021-08-10T07:54:57.000Z
src/main/java/com/alipay/api/domain/AlipayOpenMiniExperienceCancelModel.java
alipay/alipay-sdk-java-all
e87bc8e7f6750e168a5f9d37221124c085d1e3c1
[ "Apache-2.0" ]
158
2018-12-07T17:03:43.000Z
2022-03-17T09:32:43.000Z
22.604651
170
0.713992
998,330
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 小程序取消体验版 * * @author auto create * @since 1.0, 2021-03-22 10:45:40 */ public class AlipayOpenMiniExperienceCancelModel extends AlipayObject { private static final long serialVersionUID = 6464751933693465562L; /** * 小程序版本号 */ @ApiField("app_version") private String appVersion; /** * 小程序客户端类型,默认为支付宝端。支付宝端:com.alipay.alipaywallet,DINGDING端:com.alibaba.android.rimet,高德端:com.amap.app,天猫精灵端:com.alibaba.ailabs.genie.webapps,支付宝IOT:com.alipay.iot.xpaas */ @ApiField("bundle_id") private String bundleId; public String getAppVersion() { return this.appVersion; } public void setAppVersion(String appVersion) { this.appVersion = appVersion; } public String getBundleId() { return this.bundleId; } public void setBundleId(String bundleId) { this.bundleId = bundleId; } }
92382a1126733b4b60363bef77222fb52d6d47b2
1,280
java
Java
scheduler/SchedulerService/src/test/java/org/infy/idp/MixedModeFlywayPreparer.java
VijayabharathiGit/openIDP
2df98bd881608a553f8fd06f679bd5141ab68af8
[ "MIT" ]
95
2018-09-30T10:09:19.000Z
2021-12-12T00:56:53.000Z
scheduler/SchedulerService/src/test/java/org/infy/idp/MixedModeFlywayPreparer.java
VijayabharathiGit/openIDP
2df98bd881608a553f8fd06f679bd5141ab68af8
[ "MIT" ]
89
2018-09-30T02:35:52.000Z
2022-03-02T02:50:01.000Z
scheduler/SchedulerService/src/test/java/org/infy/idp/MixedModeFlywayPreparer.java
VijayabharathiGit/openIDP
2df98bd881608a553f8fd06f679bd5141ab68af8
[ "MIT" ]
116
2018-10-17T02:40:39.000Z
2022-03-29T12:33:22.000Z
27.234043
85
0.691406
998,331
package org.infy.idp; import com.opentable.db.postgres.embedded.DatabasePreparer; import org.flywaydb.core.Flyway; import javax.sql.DataSource; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.Objects; public class MixedModeFlywayPreparer implements DatabasePreparer { private final Flyway flyway; private final List<String> locations; public static MixedModeFlywayPreparer forClasspathLocation(String... locations) { Flyway f = new Flyway(); f.setMixed(true); f.setLocations(locations); return new MixedModeFlywayPreparer(f, Arrays.asList(locations)); } private MixedModeFlywayPreparer(Flyway flyway, List<String> locations) { this.flyway = flyway; this.locations = locations; } @Override public void prepare(DataSource ds) throws SQLException { flyway.setDataSource(ds); flyway.migrate(); } @Override public boolean equals(Object obj) { if (! (obj instanceof MixedModeFlywayPreparer)) { return false; } return Objects.equals(locations, ((MixedModeFlywayPreparer) obj).locations); } @Override public int hashCode() { return Objects.hashCode(locations); } }
92382a810b76a7bf775f68e623519e3b200b0d33
1,747
java
Java
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfiguration.java
shangcg/spring-boot-2.2
0ab7b1b8998a4d17e7dbc91f574c0396cd17bf77
[ "Apache-2.0" ]
66,985
2015-01-01T14:37:10.000Z
2022-03-31T21:00:10.000Z
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfiguration.java
pavelgordon/spring-boot
17d5e170698044336f86969fbad457e0c93b5c3a
[ "Apache-2.0" ]
27,513
2015-01-01T03:27:09.000Z
2022-03-31T19:03:12.000Z
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfiguration.java
pavelgordon/spring-boot
17d5e170698044336f86969fbad457e0c93b5c3a
[ "Apache-2.0" ]
42,709
2015-01-02T01:08:50.000Z
2022-03-31T20:26:44.000Z
37.170213
92
0.808243
998,332
/* * Copyright 2012-2019 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.boot.autoconfigure.context; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.Ordered; /** * {@link EnableAutoConfiguration Auto-configuration} for * {@link PropertySourcesPlaceholderConfigurer}. * * @author Phillip Webb * @author Dave Syer * @since 1.5.0 */ @Configuration(proxyBeanMethods = false) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) public class PropertyPlaceholderAutoConfiguration { @Bean @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
92382abaa3570fcf142e8a6dad1b6d78f8c2b1b8
1,179
java
Java
main/plugins/org.talend.librariesmanager.ui/src/main/java/org/talend/librariesmanager/ui/wizards/AcceptModuleLicensesWizard.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
75
2015-01-29T03:23:32.000Z
2022-02-26T07:05:40.000Z
main/plugins/org.talend.librariesmanager.ui/src/main/java/org/talend/librariesmanager/ui/wizards/AcceptModuleLicensesWizard.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
813
2015-01-21T09:36:31.000Z
2022-03-30T01:15:29.000Z
main/plugins/org.talend.librariesmanager.ui/src/main/java/org/talend/librariesmanager/ui/wizards/AcceptModuleLicensesWizard.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
272
2015-01-08T06:47:46.000Z
2022-02-09T23:22:27.000Z
25.630435
93
0.713316
998,333
package org.talend.librariesmanager.ui.wizards; import java.util.List; import org.eclipse.jface.wizard.Wizard; import org.talend.core.model.general.ModuleToInstall; import org.talend.librariesmanager.ui.i18n.Messages; /** * * created by ycbai on 2013-10-16 Detailled comment * */ public class AcceptModuleLicensesWizard extends Wizard { private AcceptModuleLicensesWizardPage licensesPage; private List<ModuleToInstall> modulesToInstall; public AcceptModuleLicensesWizard(List<ModuleToInstall> modulesToInstall) { super(); this.modulesToInstall = modulesToInstall; setWindowTitle(Messages.getString("AcceptModuleLicensesWizard.title")); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.eclipse.jface.wizard.Wizard#addPages() */ @Override public void addPages() { licensesPage = createLicensesPage(); addPage(licensesPage); } protected AcceptModuleLicensesWizardPage createLicensesPage() { return new AcceptModuleLicensesWizardPage(modulesToInstall); } @Override public boolean performFinish() { return licensesPage.performFinish(); } }
92382b0883a15459b24e117b73b06a844f24a409
1,764
java
Java
alamousse-system/src/main/java/com/alamousse/modules/shop/service/ShopGoodsCatagroryService.java
superufo/onefood_java
381c252051ff8d5b5505de2e7007d266dbb53ba2
[ "Apache-2.0" ]
null
null
null
alamousse-system/src/main/java/com/alamousse/modules/shop/service/ShopGoodsCatagroryService.java
superufo/onefood_java
381c252051ff8d5b5505de2e7007d266dbb53ba2
[ "Apache-2.0" ]
null
null
null
alamousse-system/src/main/java/com/alamousse/modules/shop/service/ShopGoodsCatagroryService.java
superufo/onefood_java
381c252051ff8d5b5505de2e7007d266dbb53ba2
[ "Apache-2.0" ]
null
null
null
24.164384
81
0.681406
998,334
package com.alamousse.modules.shop.service; import com.alamousse.modules.shop.service.dto.ShopGoodsCatagroryDTO; import com.alamousse.modules.shop.domain.ShopGoodsCatagrory; import com.alamousse.modules.shop.service.dto.ShopGoodsCatagroryQueryCriteria; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Pageable; import java.util.List; /** * @author mike * @date 2019-07-20 */ @CacheConfig(cacheNames = "shopGoodsCatagrory") public interface ShopGoodsCatagroryService { /** * queryAll 分页 * @param criteria * @param pageable * @return */ @Cacheable(keyGenerator = "keyGenerator") Object queryAll(ShopGoodsCatagroryQueryCriteria criteria, Pageable pageable); /** * queryAll 不分页 * @param criteria * @return */ @Cacheable(keyGenerator = "keyGenerator") public Object queryAll(ShopGoodsCatagroryQueryCriteria criteria); /** * findById * @param id * @return */ @Cacheable(key = "#p0") ShopGoodsCatagroryDTO findById(Integer id); /** * create * @param resources * @return */ @CacheEvict(allEntries = true) ShopGoodsCatagroryDTO create(ShopGoodsCatagrory resources); /** * update * @param resources */ @CacheEvict(allEntries = true) void update(ShopGoodsCatagrory resources); /** * delete * @param id */ @CacheEvict(allEntries = true) void delete(Integer id); /** * findByPid * @param pid * @return */ @Cacheable(key = "'parentId:'+#p0") List<ShopGoodsCatagroryDTO> findByParentId(Integer pid); }
92382b76ee0de81b3a48942c1c827078a8f7616b
728
java
Java
src.save/test/java/g0701_0800/s0792_number_of_matching_subsequences/SolutionTest.java
jscrdev/LeetCode-in-Java
cb2ec473a6e728e0eafb534518fde41910488d85
[ "MIT" ]
2
2021-12-21T11:30:12.000Z
2022-03-04T09:30:33.000Z
src.save/test/java/g0701_0800/s0792_number_of_matching_subsequences/SolutionTest.java
ThanhNIT/LeetCode-in-Java
d1c1eab40db8ef15d69d78dcc55ebb410b4bb5f5
[ "MIT" ]
null
null
null
src.save/test/java/g0701_0800/s0792_number_of_matching_subsequences/SolutionTest.java
ThanhNIT/LeetCode-in-Java
d1c1eab40db8ef15d69d78dcc55ebb410b4bb5f5
[ "MIT" ]
null
null
null
28
98
0.550824
998,335
package g0701_0800.s0792_number_of_matching_subsequences; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; class SolutionTest { @Test void numMatchingSubseq() { assertThat( new Solution().numMatchingSubseq("abcde", new String[] {"a", "bb", "acd", "ace"}), equalTo(3)); } @Test void numMatchingSubseq2() { assertThat( new Solution() .numMatchingSubseq( "dsahjpjauf", new String[] {"ahjpjau", "ja", "ahbwzgqnuk", "tnmlanowax"}), equalTo(2)); } }
92382bb2b769bd647ca2334009071b71346bdb46
2,989
java
Java
src/main/java/mx/bbva/client/core/operations/CustomerOperations.java
BBVA-Bancomer-Ecommerce/BBVA-JAVA
779347bc39c7bc791bd93be52029a18aa83896d8
[ "Apache-2.0" ]
1
2019-02-13T23:44:32.000Z
2019-02-13T23:44:32.000Z
src/main/java/mx/bbva/client/core/operations/CustomerOperations.java
BBVA-Bancomer-Ecommerce/BBVA-JAVA
779347bc39c7bc791bd93be52029a18aa83896d8
[ "Apache-2.0" ]
null
null
null
src/main/java/mx/bbva/client/core/operations/CustomerOperations.java
BBVA-Bancomer-Ecommerce/BBVA-JAVA
779347bc39c7bc791bd93be52029a18aa83896d8
[ "Apache-2.0" ]
null
null
null
37.835443
102
0.743058
998,336
/* * Copyright 2013 Opencard 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 mx.bbva.client.core.operations; import mx.bbva.client.Customer; import mx.bbva.client.core.JsonServiceClient; import mx.bbva.client.core.requests.parameters.Parameter; import mx.bbva.client.core.requests.parameters.ParameterBuilder; import mx.bbva.client.exceptions.ServiceException; import mx.bbva.client.exceptions.ServiceUnavailableException; import mx.bbva.client.utils.SearchParams; import java.util.HashMap; import java.util.List; import java.util.Map; import static mx.bbva.client.utils.PathComponents.*; /** * Operations for managing Customers. * * @author elopez */ public class CustomerOperations extends ServiceOperations { private static final String CUSTOMERS_PATH = MERCHANT_ID + CUSTOMERS; private static final String GET_CUSTOMER_PATH = CUSTOMERS_PATH + ID; private ParameterBuilder parameterBuilder = new ParameterBuilder(); public CustomerOperations(final JsonServiceClient client) { super(client); } public Customer create(final Customer create) throws ServiceException, ServiceUnavailableException { String path = String.format(CUSTOMERS_PATH, this.getMerchantId()); return this.getJsonClient().post(path, create, Customer.class); } public HashMap create(final List<Parameter> params) throws ServiceException, ServiceUnavailableException { String path = String.format(CUSTOMERS_PATH, this.getMerchantId()); return this.getJsonClient().post(path, parameterBuilder.AsMap(params), HashMap.class); } public List<HashMap> list(final SearchParams params) throws ServiceException, ServiceUnavailableException { String path = String.format(CUSTOMERS_PATH, this.getMerchantId()); Map<String, String> map = params == null ? null : params.asMap(); return this.getJsonClient().list(path, map, HashMap.class); } public HashMap get(final String customerId) throws ServiceException, ServiceUnavailableException { String path = String.format(GET_CUSTOMER_PATH, this.getMerchantId(), customerId); return this.getJsonClient().get(path, HashMap.class); } public void delete(final String customerId) throws ServiceException, ServiceUnavailableException { String path = String.format(GET_CUSTOMER_PATH, this.getMerchantId(), customerId); this.getJsonClient().delete(path); } }
92382d580c34508d573456442ca695e8496d72f2
1,109
java
Java
clbs/src/main/java/com/zw/platform/domain/infoconfig/builder/MonitorInfoBuilder.java
youyouqiu/hybrid-development
784c5227a73d1e6609b701a42ef4cdfd6400d2b7
[ "MIT" ]
1
2021-09-29T02:13:49.000Z
2021-09-29T02:13:49.000Z
clbs/src/main/java/com/zw/platform/domain/infoconfig/builder/MonitorInfoBuilder.java
youyouqiu/hybrid-development
784c5227a73d1e6609b701a42ef4cdfd6400d2b7
[ "MIT" ]
null
null
null
clbs/src/main/java/com/zw/platform/domain/infoconfig/builder/MonitorInfoBuilder.java
youyouqiu/hybrid-development
784c5227a73d1e6609b701a42ef4cdfd6400d2b7
[ "MIT" ]
null
null
null
33.606061
111
0.693417
998,337
package com.zw.platform.domain.infoconfig.builder; import com.zw.platform.domain.enmu.ProtocolEnum; import com.zw.platform.domain.infoconfig.form.MonitorInfo; import java.util.Map; /** * @Author: zjc * @Description:监控对象信息构建类 * @Date: create in 2021/1/6 13:52 */ public class MonitorInfoBuilder { public static void buildVehicleStaticData(Map<String, String> vehicleStaticData, MonitorInfo monitorInfo) { if (vehicleStaticData.size() > 0) { // 运输行业编码 monitorInfo.setTransType(vehicleStaticData.get("transType")); // 车辆类型编码 monitorInfo.setVehicleTypeCode(vehicleStaticData.get("vehicleTypeCode")); monitorInfo.setOwersName(vehicleStaticData.get("owersName")); monitorInfo.setOwersTel(vehicleStaticData.get("owersTel")); } } public static void buildFakeIp(String deviceType, String identification, MonitorInfo monitorInfo) { Integer sign = ProtocolEnum.getSignByDeviceType(deviceType); if (sign == ProtocolEnum.TWO) { monitorInfo.setFakeIp(identification); } } }
92382dd61c70384e07f4587b7ade491aba0fee0e
113
java
Java
src/main/java/com/sut/User.java
nadvolod/java-tdd
dc072d8588102bb5d390291c0cd21352a247d2cf
[ "MIT" ]
null
null
null
src/main/java/com/sut/User.java
nadvolod/java-tdd
dc072d8588102bb5d390291c0cd21352a247d2cf
[ "MIT" ]
null
null
null
src/main/java/com/sut/User.java
nadvolod/java-tdd
dc072d8588102bb5d390291c0cd21352a247d2cf
[ "MIT" ]
null
null
null
14.125
41
0.716814
998,338
package com.sut; public interface User { String getPassword(); void setPassword(String passwordMd5); }
92382fc530e0683377239b39a5a476e56437c27a
7,283
java
Java
app/src/main/java/com/developer/allef/boilerplateapp/validadorboleto/DigitoPara.java
allefsousa/MaterialAppConcept
452f6ddf2e099647cfaa3032b1ae4080e4a342c1
[ "MIT" ]
null
null
null
app/src/main/java/com/developer/allef/boilerplateapp/validadorboleto/DigitoPara.java
allefsousa/MaterialAppConcept
452f6ddf2e099647cfaa3032b1ae4080e4a342c1
[ "MIT" ]
null
null
null
app/src/main/java/com/developer/allef/boilerplateapp/validadorboleto/DigitoPara.java
allefsousa/MaterialAppConcept
452f6ddf2e099647cfaa3032b1ae4080e4a342c1
[ "MIT" ]
null
null
null
31.257511
99
0.593025
998,339
package com.developer.allef.boilerplateapp.validadorboleto; import android.util.Log; import android.util.SparseArray; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * @author allef.santos on 2020-01-22 */ public final class DigitoPara { private final List<Integer> numero = new LinkedList<>(); private final List<Integer> multiplicadores; private final boolean complementar; private final int modulo; private final boolean somarIndividual; private final SparseArray<String> substituicoes; private DigitoPara(Builder builder) { multiplicadores = builder.multiplicadores; complementar = builder.complementar; modulo = builder.modulo; somarIndividual = builder.somarIndividual; substituicoes = builder.substituicoes; } /** * Faz a soma geral das multiplicações dos algarismos pelos multiplicadores, tira o * módulo e devolve seu complementar. * * @param trecho Bloco para calcular o dígito * @return String o dígito vindo do módulo com o número passado e configurações extra. */ public final String calcula(String trecho) { Log.d("allef","trecho "+trecho); numero.clear(); final char[] digitos = trecho.toCharArray(); for (int i = 0; i < digitos.length; i++) { numero.add(Character.getNumericValue(digitos[i])); } Collections.reverse(numero); int soma = 0; int multiplicadorDaVez = 0; for (int i = 0; i < numero.size(); i++) { final int multiplicador = multiplicadores.get(multiplicadorDaVez); final int total = numero.get(i) * multiplicador; soma += somarIndividual ? somaDigitos(total) : total; multiplicadorDaVez = proximoMultiplicador(multiplicadorDaVez); } int resultado = soma % modulo; Log.d("allef","resultado "+resultado +"= "+soma +" % "+ modulo); if (complementar) { resultado = modulo - resultado; } if (substituicoes.get(resultado) != null) { Log.d("allef","Substituição"+substituicoes.get(resultado)); return substituicoes.get(resultado); } Log.d("allef","Resultado "+resultado); return String.valueOf(resultado); } /* * soma os dígitos do número (até 2) * * Ex: 18 => 9 (1+8), 12 => 3 (1+2) */ private int somaDigitos(int total) { return (total / 10) + (total % 10); } /* * Devolve o próximo multiplicador a ser usado, isto é, a próxima posição da lista de * multiplicadores ou, se chegar ao fim da lista, a primeira posição, novamente. */ private int proximoMultiplicador(int multiplicadorDaVez) { int multiplicador = multiplicadorDaVez + 1; if (multiplicador == multiplicadores.size()) { multiplicador = 0; } return multiplicador; } /** * Builder com interface fluente para criação de instâncias configuradas de * {@link DigitoPara} */ public static final class Builder { private List<Integer> multiplicadores = new ArrayList<>(); private boolean complementar; private int modulo; private boolean somarIndividual; private final SparseArray<String> substituicoes = new SparseArray<String>(); /** * @param modulo Inteiro pelo qual o resto será tirado e também seu complementar. * O valor padrão é 11. * @return this */ public final Builder mod(int modulo) { this.modulo = modulo; return this; } /** * Para multiplicadores (ou pesos) sequenciais e em ordem crescente, esse método permite * criar a lista de multiplicadores que será usada ciclicamente, caso o número base seja * maior do que a sequência de multiplicadores. Por padrão os multiplicadores são iniciados * de 2 a 9. No momento em que você inserir outro valor este default será sobrescrito. * * @param inicio Primeiro número do intervalo sequencial de multiplicadores * @param fim Último número do intervalo sequencial de multiplicadores * @return this */ public final Builder comMultiplicadoresDeAte(int inicio, int fim) { this.multiplicadores.clear(); for (int i = inicio; i <= fim; i++) { multiplicadores.add(i); } return this; } /** * <p> * Indica se, ao calcular o módulo, a soma dos resultados da multiplicação deve ser * considerado digito a dígito. * </p> * Ex: 2 X 9 = 18, irá somar 9 (1 + 8) invés de 18 ao total. * * @return this */ public final Builder somandoIndividualmente() { this.somarIndividual = true; return this; } /** * É comum que os geradores de dígito precisem do complementar do módulo em vez * do módulo em sí. Então, a chamada desse método habilita a flag que é usada * no método mod para decidir se o resultado devolvido é o módulo puro ou seu * complementar. * * @return this */ public final Builder complementarAoModulo() { this.complementar = true; return this; } /** * Troca por uma String caso encontre qualquer dos inteiros passados como argumento * * @param substituto String para substituir * @param i varargs de inteiros a serem substituídos * @return this */ public final Builder trocandoPorSeEncontrar(String substituto, Integer... i) { substituicoes.clear(); for (Integer integer : i) { substituicoes.put(integer, substituto); } return this; } /** * Há documentos em que os multiplicadores não usam todos os números de um intervalo * ou alteram sua ordem. Nesses casos, a lista de multiplicadores pode ser passada * através de varargs. * * @param multiplicadoresEmOrdem Sequência de inteiros com os multiplicadores em ordem * @return this */ public final Builder comMultiplicadores(Integer... multiplicadoresEmOrdem) { this.multiplicadores.clear(); this.multiplicadores.addAll(Arrays.asList(multiplicadoresEmOrdem)); return this; } /** * Método responsável por criar o DigitoPara. * Este método inicializará os seguintes valores padrões: * <ul> * <li>multiplicadores: 2 a 9</li> * <li>módulo: 11</li> * </ul> * * @return A instância imutável de DigitoPara */ public final DigitoPara build() { if (multiplicadores.size() == 0) { comMultiplicadoresDeAte(2, 9); } if (modulo == 0) { mod(11); } return new DigitoPara(this); } } }
92383066768f650a54542bd106b66a1fc5a684b0
2,147
java
Java
gulimall-ware/src/main/java/com/atguigu/gulimall/ware/controller/WareInfoController.java
lufeifeile/gulimall
d6dee3176398473dfa0a354210488cdba08cdc73
[ "Apache-2.0" ]
2
2021-09-29T10:12:02.000Z
2021-09-29T10:16:50.000Z
gulimall-ware/src/main/java/com/atguigu/gulimall/ware/controller/WareInfoController.java
lufeifeile/gulimall
d6dee3176398473dfa0a354210488cdba08cdc73
[ "Apache-2.0" ]
null
null
null
gulimall-ware/src/main/java/com/atguigu/gulimall/ware/controller/WareInfoController.java
lufeifeile/gulimall
d6dee3176398473dfa0a354210488cdba08cdc73
[ "Apache-2.0" ]
null
null
null
23.844444
62
0.686859
998,340
package com.atguigu.gulimall.ware.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gulimall.ware.entity.WareInfoEntity; import com.atguigu.gulimall.ware.service.WareInfoService; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; /** * 仓库信息 * * @author lufei * @email anpch@example.com * @date 2021-08-08 16:04:54 */ @RestController @RequestMapping("ware/wareinfo") public class WareInfoController { @Autowired private WareInfoService wareInfoService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("ware:wareinfo:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = wareInfoService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("ware:wareinfo:info") public R info(@PathVariable("id") Long id){ WareInfoEntity wareInfo = wareInfoService.getById(id); return R.ok().put("wareInfo", wareInfo); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("ware:wareinfo:save") public R save(@RequestBody WareInfoEntity wareInfo){ wareInfoService.save(wareInfo); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("ware:wareinfo:update") public R update(@RequestBody WareInfoEntity wareInfo){ wareInfoService.updateById(wareInfo); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("ware:wareinfo:delete") public R delete(@RequestBody Long[] ids){ wareInfoService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
923831741f0ac539cea279bd4cd967b1331dfb3c
2,887
java
Java
jbpm-designer-backend/src/main/java/org/jbpm/designer/web/profile/impl/RepositoryInfo.java
Josephblt/jbpm-designer
01a1ce2eb492f7e4d4c49fd1a3fc266573e042a9
[ "Apache-2.0" ]
65
2017-03-30T02:29:14.000Z
2022-02-03T15:34:56.000Z
jbpm-designer-backend/src/main/java/org/jbpm/designer/web/profile/impl/RepositoryInfo.java
Josephblt/jbpm-designer
01a1ce2eb492f7e4d4c49fd1a3fc266573e042a9
[ "Apache-2.0" ]
236
2017-03-13T14:30:10.000Z
2022-01-10T12:41:06.000Z
jbpm-designer-backend/src/main/java/org/jbpm/designer/web/profile/impl/RepositoryInfo.java
Josephblt/jbpm-designer
01a1ce2eb492f7e4d4c49fd1a3fc266573e042a9
[ "Apache-2.0" ]
89
2017-03-22T10:07:29.000Z
2022-01-19T09:18:30.000Z
39.547945
162
0.667821
998,341
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.jbpm.designer.web.profile.impl; import org.jbpm.designer.web.profile.IDiagramProfile; public class RepositoryInfo { private static final String REPOSITORY_PROTOCOL = "designer.repository.protocol"; private static final String REPOSITORY_HOST = "designer.repository.host"; private static final String REPOSITORY_SUBDOMAIN = "designer.repository.subdomain"; private static final String REPOSITORY_USR = "designer.repository.usr"; private static final String REPOSITORY_PWD = "designer.repository.pwd"; public static String getRepositoryProtocol(IDiagramProfile profile) { return isEmpty(System.getProperty(REPOSITORY_PROTOCOL)) ? "http" : System.getProperty(REPOSITORY_PROTOCOL); } public static String getRepositoryHost(IDiagramProfile profile) { if (!isEmpty(System.getProperty(REPOSITORY_HOST))) { String retStr = System.getProperty(REPOSITORY_HOST); if (retStr.startsWith("/")) { retStr = retStr.substring(1); } if (retStr.endsWith("/")) { retStr = retStr.substring(0, retStr.length() - 1); } return retStr; } else { return "localhost:8080";//profile.getRepositoryHost(); } } public static String getRepositoryUsr(IDiagramProfile profile) { return isEmpty(System.getProperty(REPOSITORY_USR)) ? "admin" : System.getProperty(REPOSITORY_USR); } public static String getRepositoryPwd(IDiagramProfile profile) { return isEmpty(System.getProperty(REPOSITORY_PWD)) ? "admin" : System.getProperty(REPOSITORY_PWD); } public static String getRepositorySubdomain(IDiagramProfile profile) { return isEmpty(System.getProperty(REPOSITORY_SUBDOMAIN)) ? "drools-guvnor/org.drools.guvnor.Guvnor/oryxeditor" : System.getProperty(REPOSITORY_SUBDOMAIN); } private static boolean isEmpty(final CharSequence str) { if (str == null || str.length() == 0) { return true; } for (int i = 0, length = str.length(); i < length; i++) { if (str.charAt(i) != ' ') { return false; } } return true; } }
923831aebc8a52cb377c17d56a2d6d29cdbb8059
557
java
Java
cloud-cunsumer-order8661/src/main/java/com/jt/springcloud/OrderMain8661.java
dididada002/cloud2020
00185ae83dee3ee1df28f5a4c3197336458066c5
[ "MIT" ]
1
2020-07-31T14:57:05.000Z
2020-07-31T14:57:05.000Z
cloud-cunsumer-order8661/src/main/java/com/jt/springcloud/OrderMain8661.java
dididada002/cloud2020
00185ae83dee3ee1df28f5a4c3197336458066c5
[ "MIT" ]
null
null
null
cloud-cunsumer-order8661/src/main/java/com/jt/springcloud/OrderMain8661.java
dididada002/cloud2020
00185ae83dee3ee1df28f5a4c3197336458066c5
[ "MIT" ]
null
null
null
29.315789
101
0.777379
998,342
package com.jt.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @author: jingteng * @date: 2020/4/14 21:22 */ @SpringBootApplication @EnableEurekaClient //@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class) //手动加载ribbon负载均衡算法 public class OrderMain8661 { public static void main(String[] args) { SpringApplication.run(OrderMain8661.class,args); } }
923831cf7dbff3451c9114abb510e65ab30747cf
269
java
Java
molecule-discovery/src/main/java/pl/filipowm/discovery/application/CompoundDto.java
filipowm/meetup-microservices-demo
d883943d90141309bd3d28262d7dd14a6017dc58
[ "MIT" ]
1
2018-10-25T17:05:33.000Z
2018-10-25T17:05:33.000Z
molecule-discovery/src/main/java/pl/filipowm/discovery/application/CompoundDto.java
filipowm/meetup-microservices-demo
d883943d90141309bd3d28262d7dd14a6017dc58
[ "MIT" ]
null
null
null
molecule-discovery/src/main/java/pl/filipowm/discovery/application/CompoundDto.java
filipowm/meetup-microservices-demo
d883943d90141309bd3d28262d7dd14a6017dc58
[ "MIT" ]
null
null
null
16.8125
42
0.776952
998,343
package pl.filipowm.discovery.application; import lombok.Data; import lombok.NoArgsConstructor; import pl.filipowm.discovery.domain.Unit; @Data @NoArgsConstructor public class CompoundDto { private String name; private long amount; private Unit unit; }
923831e2cbab7561127660883dddf5a83506e5df
11,132
java
Java
mixim/src/main/java/com/mixotc/imsdklib/database/provider/ChatTableProvider.java
oynix/goimandroid
0cf1a2871b6abb3f63208fc4357d4c5a9311c437
[ "MIT" ]
1
2018-05-23T12:33:55.000Z
2018-05-23T12:33:55.000Z
mixim/src/main/java/com/mixotc/imsdklib/database/provider/ChatTableProvider.java
oynix/goimandroid
0cf1a2871b6abb3f63208fc4357d4c5a9311c437
[ "MIT" ]
null
null
null
mixim/src/main/java/com/mixotc/imsdklib/database/provider/ChatTableProvider.java
oynix/goimandroid
0cf1a2871b6abb3f63208fc4357d4c5a9311c437
[ "MIT" ]
null
null
null
36.860927
167
0.566116
998,344
package com.mixotc.imsdklib.database.provider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.mixotc.imsdklib.database.DatabaseException; import com.mixotc.imsdklib.database.params.DeleteParams; import com.mixotc.imsdklib.database.params.InsertParams; import com.mixotc.imsdklib.database.params.UpdateParams; import com.mixotc.imsdklib.database.table.ChatTable; import com.mixotc.imsdklib.message.GOIMMessage; import com.mixotc.imsdklib.message.MessageEncoder; import com.mixotc.imsdklib.message.TransferMessageBody; import com.mixotc.imsdklib.utils.Logger; import java.util.ArrayList; import java.util.List; import static com.mixotc.imsdklib.database.table.ChatTable.GROUP_ID; import static com.mixotc.imsdklib.database.table.ChatTable.IS_DELIVERED; import static com.mixotc.imsdklib.database.table.ChatTable.IS_LISTENED; import static com.mixotc.imsdklib.database.table.ChatTable.MSG_BODY; import static com.mixotc.imsdklib.database.table.ChatTable.MSG_ID; import static com.mixotc.imsdklib.database.table.ChatTable.MSG_TIME; import static com.mixotc.imsdklib.database.table.ChatTable.STATUS; import static com.mixotc.imsdklib.database.table.ChatTable.TABLE_NAME; /** * Author : xiaoyu * Date : 2018/3/25 下午4:18 * Version : v1.0.0 * Describe : */ public class ChatTableProvider extends BaseIMTableProvider { private static final String TAG = ChatTableProvider.class.getSimpleName(); public ChatTableProvider(Context context, String uid) { super(context, uid); } /** 插入一条消息 */ public boolean insertMessage(GOIMMessage message) { boolean result = false; if (isMsgExist(message)) { return false; } ContentValues contentValues = ChatTable.createContentValues(message); InsertParams params = new InsertParams(TABLE_NAME, contentValues); try { mHelper.insert(params); result = true; Logger.d(TAG, "save msg to db"); } catch (DatabaseException e) { e.printStackTrace(); } return result; } /** 查看某条消息是否存在,根据消息id判断 */ public boolean isMsgExist(GOIMMessage msg) { boolean result = false; Cursor cursor = null; try { cursor = mHelper.query(TABLE_NAME, null, MSG_ID + "=?", new String[]{msg.getMsgId()}, null, null, null); if (cursor.moveToFirst()) { result = true; } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return result; } /** 更新消息内容 */ public boolean updateMsgBody(GOIMMessage message) { boolean result = false; try { ContentValues contentValues = new ContentValues(); String msgId = message.getMsgId(); String msgBody = MessageEncoder.getJSONMsg(message); contentValues.put(MSG_BODY, msgBody); UpdateParams params = new UpdateParams(TABLE_NAME, MSG_ID + "=?", new String[]{msgId}, contentValues); mHelper.update(params); Logger.d(TAG, "update msg:" + msgId + " message body:" + msgBody); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** 删除消息 */ public void deleteMessage(String msgId) { try { DeleteParams params = new DeleteParams(TABLE_NAME, MSG_ID + "=?", new String[]{msgId}); int affected = mHelper.delete(params); Logger.d(TAG, "delete msg:" + msgId + " return:" + affected); } catch (Exception e) { e.printStackTrace(); } } /** 加载一条消息 */ public GOIMMessage loadMessage(String msgId) { GOIMMessage message = null; Cursor cursor = null; try { cursor = mHelper.query(TABLE_NAME, null, MSG_ID + "=?", new String[]{msgId}, null, null, null); if (cursor.moveToFirst()) { message = GOIMMessage.createFromCursor(cursor); Logger.d(TAG, "load msg msgId:" + msgId); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return message; } /** 删除一个对话的所有消息 */ public void deleteConversationMsg(long groupId) { try { DeleteParams params = new DeleteParams(TABLE_NAME, GROUP_ID + "=?", new String[]{String.valueOf(groupId)}); int affected = mHelper.delete(params); Logger.d(TAG, "delete chat msgs with:" + groupId + " return:" + affected); } catch (Exception e) { e.printStackTrace(); } } /** 更新一条消息的收听状态 */ public void updateMsgListen(String msgId, boolean listened) { try { ContentValues contentValues = new ContentValues(); contentValues.put(IS_LISTENED, listened ? 1 : 0); UpdateParams params = new UpdateParams(TABLE_NAME, MSG_ID + "=?", new String[]{msgId}, contentValues); mHelper.update(params); Logger.d(TAG, "update msg:" + msgId + " isListened:" + listened); } catch (Exception e) { e.printStackTrace(); } } /** 更新一条消息的发送状态 */ public void updateMsgDelivered(String msgId, boolean delivered) { try { ContentValues contentValues = new ContentValues(); contentValues.put(IS_DELIVERED, delivered ? 1 : 0); UpdateParams params = new UpdateParams(TABLE_NAME, MSG_ID + "=?", new String[]{msgId}, contentValues); mHelper.update(params); Logger.d(TAG, "update msg:" + msgId + " delivered:" + delivered); } catch (Exception e) { e.printStackTrace(); } } /** 更新一条消息的状态 */ public void updateMsgStatus(String msgId, int newStatus) { try { ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, newStatus); UpdateParams params = new UpdateParams(TABLE_NAME, MSG_ID + "=?", new String[]{msgId}, contentValues); mHelper.update(params); Logger.d(TAG, "update msg:" + msgId + " status:" + newStatus); } catch (Exception e) { e.printStackTrace(); } } /** 将所有group_id值为oldGroupId的行,更新为newGroupId */ public void updateMsgGroupId(long oldGroupId, long newGroupId) { try { ContentValues contentValues = new ContentValues(); contentValues.put(GROUP_ID, newGroupId); UpdateParams params = new UpdateParams(TABLE_NAME, GROUP_ID + "=?", new String[]{String.valueOf(oldGroupId)}, contentValues); mHelper.update(params); } catch (DatabaseException e) { e.printStackTrace(); } } /** 根据groupId获取消息数量 */ public int getMsgCountById(long groupId) { int result = 0; Cursor cursor; try { String sql = "SELECT COUNT(*) FROM " + TABLE_NAME + " WHERE " + GROUP_ID + "=?;"; cursor = mHelper.rawQuery(sql, new String[]{String.valueOf(groupId)}); if (cursor.moveToFirst()) { result = cursor.getInt(0); } } catch (DatabaseException e) { e.printStackTrace(); } return result; } /** * 从属于groupId的消息列中,从lastMsgId的位置,加载数量为count的消息,以消息时间descending排列。 * * @param groupId 查询的组 * @param lastMsgId 最后一条消息id,即本次查询的基准,如果为空则由最新消息开始查询 * @param count 加载的数量 * @return 查询结果 */ public List<GOIMMessage> loadMsgByLastId(long groupId, String lastMsgId, int count) { List<GOIMMessage> result = new ArrayList<>(); Cursor cursor = null; try { String sql; String[] whereArgs; if (!TextUtils.isEmpty(lastMsgId)) { GOIMMessage message = loadMessage(lastMsgId); if (message == null) { return result; } sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + GROUP_ID + "=?" + " AND " + MSG_TIME + "<?" + " ORDER BY " + MSG_TIME + " DESC LIMIT " + count + ";"; whereArgs = new String[]{String.valueOf(groupId), String.valueOf(message.getMsgTime())}; } else { sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + GROUP_ID + "=?" + " ORDER BY " + MSG_TIME + " DESC LIMIT " + count + ";"; whereArgs = new String[]{String.valueOf(groupId)}; } cursor = mHelper.rawQuery(sql, whereArgs); if (cursor == null) { return result; } while (cursor.moveToNext()) { GOIMMessage message = GOIMMessage.createFromCursor(cursor); if (message == null) { continue; } result.add(0, message); } } catch (DatabaseException e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } Logger.d(TAG, "load msgs size:" + result.size() + " for group id:" + groupId); return result; } /** 加载转账消息 */ public GOIMMessage loadTransferMsg(long groupId, long transferId) { String typeWords = "\"type\":\"transfer\""; String idWords = "\"id\":" + transferId; Cursor cursor = null; GOIMMessage message = null; try { cursor = mHelper.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + GROUP_ID + " = ? AND " + MSG_BODY + " LIKE '%" + typeWords + "%' AND " + MSG_BODY + " LIKE '%" + idWords + "%' ORDER BY " + MSG_TIME + " DESC", new String[]{String.valueOf(groupId)}); if (cursor == null) { return null; } while (cursor.moveToNext()) { GOIMMessage msg = GOIMMessage.createFromCursor(cursor); TransferMessageBody body = (TransferMessageBody) msg.getBody(); if (body.getTransferId() == transferId) { message = msg; break; } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } return message; } /** 删除group id为传入group id的所有message */ public void deleteMsgByGroupId(long groupId) { try { DeleteParams params = new DeleteParams(TABLE_NAME, GROUP_ID + "=?", new String[]{String.valueOf(groupId)}); mHelper.delete(params); Logger.d(TAG, "delete chat of group id:" + groupId); } catch (DatabaseException e) { e.printStackTrace(); } } }
9238329665db2b072f514ee53780c061b608740c
15,006
java
Java
src/main/java/tech/mmmax/kami/impl/features/modules/render/Nametags.java
DriftyDev/-CLEAN_Kami5-1.8-BUILDABLE_SRC
9202b67ec80823e1a9815c1abb204c2db71a8cd4
[ "MIT" ]
26
2021-11-08T20:25:40.000Z
2022-03-19T14:21:51.000Z
src/main/java/tech/mmmax/kami/impl/features/modules/render/Nametags.java
DriftyDev/-CLEAN_Kami5-1.8-BUILDABLE_SRC
9202b67ec80823e1a9815c1abb204c2db71a8cd4
[ "MIT" ]
7
2021-11-08T20:54:02.000Z
2022-01-17T21:29:42.000Z
src/main/java/tech/mmmax/kami/impl/features/modules/render/Nametags.java
DriftyDev/-CLEAN_Kami5-1.8-BUILDABLE_SRC
9202b67ec80823e1a9815c1abb204c2db71a8cd4
[ "MIT" ]
5
2021-11-08T22:18:23.000Z
2021-11-13T00:42:22.000Z
60.753036
451
0.694855
998,345
/* * Decompiled with CFR 0.151. * * Could not load the following classes: * com.mojang.realmsclient.gui.ChatFormatting * net.minecraft.client.renderer.BufferBuilder * net.minecraft.client.renderer.GlStateManager * net.minecraft.client.renderer.RenderHelper * net.minecraft.client.renderer.Tessellator * net.minecraft.client.renderer.vertex.DefaultVertexFormats * net.minecraft.entity.Entity * net.minecraft.entity.player.EntityPlayer * net.minecraft.item.ItemStack * net.minecraft.util.EnumHand * net.minecraft.util.math.Vec3d * net.minecraftforge.client.event.RenderWorldLastEvent * net.minecraftforge.fml.common.eventhandler.SubscribeEvent * org.lwjgl.opengl.GL11 */ package tech.mmmax.kami.impl.features.modules.render; import com.mojang.realmsclient.gui.ChatFormatting; import java.awt.Color; import java.util.ArrayList; import java.util.Collection; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import net.minecraft.util.math.Vec3d; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.lwjgl.opengl.GL11; import tech.mmmax.kami.api.feature.Feature; import tech.mmmax.kami.api.feature.module.Module; import tech.mmmax.kami.api.gui.helpers.Rect; import tech.mmmax.kami.api.gui.render.IRenderer; import tech.mmmax.kami.api.management.FriendManager; import tech.mmmax.kami.api.utils.NullUtils; import tech.mmmax.kami.api.utils.render.RenderUtil; import tech.mmmax.kami.api.value.Value; import tech.mmmax.kami.api.value.builder.ValueBuilder; import tech.mmmax.kami.impl.gui.ClickGui; public class Nametags extends Module { public static Nametags INSTANCE; Value<String> page = new ValueBuilder().withDescriptor("Page").withValue("Colors").withModes("Colors", "Items", "Size").register(this); Value<Color> background = new ValueBuilder().withDescriptor("Background").withValue(new Color(0, 0, 0, 25)).withPageParent(this.page).withPage("Colors").register(this); Value<Color> textColor = new ValueBuilder().withDescriptor("Text Color").withValue(new Color(255, 255, 255)).withPageParent(this.page).withPage("Colors").register(this); Value<Color> lineColor = new ValueBuilder().withDescriptor("Line Color").withValue(new Color(0, 0, 0, 150)).withPageParent(this.page).withPage("Colors").register(this); Value<Color> boxColor = new ValueBuilder().withDescriptor("Box Color").withValue(new Color(25, 25, 25, 255)).withPageParent(this.page).withPage("Colors").register(this); Value<Number> lineWidth = new ValueBuilder().withDescriptor("Line Width").withValue(1).withRange(0.1, 5).withPageParent(this.page).withPage("Items").register(this); Value<Boolean> ping = new ValueBuilder().withDescriptor("Ping").withValue(true).withPageParent(this.page).withPage("Items").register(this); Value<Boolean> health = new ValueBuilder().withDescriptor("Health").withValue(true).withPageParent(this.page).withPage("Items").register(this); Value<Boolean> hands = new ValueBuilder().withDescriptor("Hands").withValue(true).withPageParent(this.page).withPage("Items").register(this); Value<Boolean> armor = new ValueBuilder().withDescriptor("Armor").withValue(true).withPageParent(this.page).withPage("Items").register(this); Value<Boolean> playerBox = new ValueBuilder().withDescriptor("Player Box").withValue(false).withPageParent(this.page).withPage("Items").register(this); Value<Number> playerBoxWidth = new ValueBuilder().withDescriptor("Box Width").withValue(30).withRange(10, 60).withPageParent(this.page).withPage("Items").register(this); Value<Number> padding = new ValueBuilder().withDescriptor("Padding").withValue(1).withRange(0, 5).withPageParent(this.page).withPage("Size").register(this); Value<Number> scale = new ValueBuilder().withDescriptor("Scale").withValue(1).withRange(0, 10).withPageParent(this.page).withPage("Size").register(this); void handlePage(String page) { this.background.setActive(page.equals("Colors")); this.textColor.setActive(page.equals("Colors")); this.lineColor.setActive(page.equals("Colors")); this.lineWidth.setActive(page.equals("Colors")); this.boxColor.setActive(page.equals("Colors")); this.ping.setActive(page.equals("Items")); this.health.setActive(page.equals("Items")); this.hands.setActive(page.equals("Items")); this.armor.setActive(page.equals("Items")); this.playerBox.setActive(page.equals("Items")); this.playerBoxWidth.setActive(page.equals("Items")); this.padding.setActive(page.equals("Size")); this.scale.setActive(page.equals("Size")); } public Nametags() { super("Nametags", Feature.Category.Render); INSTANCE = this; this.handlePage(page.getValue()); } @SubscribeEvent public void onRenderWorld(RenderWorldLastEvent event) { if (NullUtils.nullCheck()) { return; } for (Entity entity : Nametags.mc.world.loadedEntityList) { EntityPlayer player; if (!(entity instanceof EntityPlayer) || (player = (EntityPlayer)entity).getEntityId() == Nametags.mc.player.getEntityId()) continue; Vec3d pos = Nametags.interpolateEntityByTicks(entity, event.getPartialTicks()); double x = pos.x; double distance = pos.y + 0.65; double z = pos.z; double y = distance + (player.isSneaking() ? 0.0 : 0.08); Vec3d entityPos = Nametags.interpolateEntity(entity, event.getPartialTicks()); float linWid = RenderUtil.getInterpolatedLinWid((float)Nametags.mc.player.getDistance(player.posX, player.posY, player.posZ), this.lineWidth.getValue().floatValue(), this.lineWidth.getValue().floatValue()); GL11.glLineWidth((float)linWid); GL11.glDisable((int)2848); GlStateManager.pushMatrix(); this.prepareTranslation(x, y, z, this.scale.getValue().doubleValue() * (Nametags.mc.player.getDistance(entityPos.x, entityPos.y, entityPos.z) / 2.0)); GlStateManager.pushMatrix(); String nametag = this.getNametagString(player); int width = ClickGui.CONTEXT.getRenderer().getTextWidth(nametag); int height = ClickGui.CONTEXT.getRenderer().getTextHeight(nametag); Rect nametagRect = new Rect(-width / 2, -height / 2, width + this.padding.getValue().intValue() * 2, height + this.padding.getValue().intValue() * 2); ClickGui.CONTEXT.getRenderer().renderRect(nametagRect, this.background.getValue(), this.background.getValue(), IRenderer.RectMode.Fill, ClickGui.CONTEXT); ClickGui.CONTEXT.getRenderer().renderRect(nametagRect, this.lineColor.getValue(), this.lineColor.getValue(), IRenderer.RectMode.Outline, ClickGui.CONTEXT); ClickGui.CONTEXT.getRenderer().renderText(nametag, nametagRect.getX() + this.padding.getValue().intValue(), nametagRect.getY() + this.padding.getValue().intValue(), this.textColor.getValue(), ClickGui.CONTEXT.getColorScheme().doesTextShadow()); ArrayList<ItemStack> stacks = new ArrayList<ItemStack>(); if (this.hands.getValue().booleanValue()) { stacks.add(player.getHeldItem(EnumHand.MAIN_HAND)); } if (this.armor.getValue().booleanValue()) { stacks.addAll((Collection<ItemStack>)player.inventory.armorInventory); } if (this.hands.getValue().booleanValue()) { stacks.add(player.getHeldItem(EnumHand.OFF_HAND)); } int offset = this.padding.getValue().intValue(); int offAdd = nametagRect.getWidth() / stacks.size(); for (ItemStack stack : stacks) { int stackX = nametagRect.getX() + offset; int stackY = nametagRect.getY() - (16 + this.padding.getValue().intValue()); this.renderStack(player, stack, stackX, stackY); offset += offAdd; } if (this.playerBox.getValue().booleanValue()) { Rect boxRect = new Rect(-this.playerBoxWidth.getValue().intValue(), nametagRect.getY() + this.padding.getValue().intValue(), this.playerBoxWidth.getValue().intValue() * 2, 100); ClickGui.CONTEXT.getRenderer().renderRect(boxRect, this.boxColor.getValue(), this.boxColor.getValue(), IRenderer.RectMode.Outline, ClickGui.CONTEXT); } GlStateManager.popMatrix(); this.release(); GlStateManager.popMatrix(); } } void renderStack(EntityPlayer player, ItemStack stack, int x, int y) { GlStateManager.pushMatrix(); GlStateManager.depthMask((boolean)true); GlStateManager.clear((int)256); RenderHelper.enableStandardItemLighting(); Nametags.mc.getRenderItem().zLevel = -150.0f; GlStateManager.disableAlpha(); GlStateManager.enableDepth(); GlStateManager.disableCull(); mc.getRenderItem().renderItemAndEffectIntoGUI(stack, x, y); Nametags.mc.getRenderItem().zLevel = 0.0f; RenderHelper.disableStandardItemLighting(); String stackCount = stack.getCount() > 1 ? String.valueOf(stack.getCount()) : ""; int width = ClickGui.CONTEXT.getRenderer().getTextWidth(stackCount); GlStateManager.enableAlpha(); GlStateManager.disableDepth(); ClickGui.CONTEXT.getRenderer().renderText(stackCount, x + 17 - width, y + 9, this.textColor.getValue(), ClickGui.CONTEXT.getColorScheme().doesTextShadow()); if (stack.getItem().showDurabilityBar(stack)) { this.renderDuraBar(stack, x, y); } GlStateManager.scale((float)0.5f, (float)0.5f, (float)0.5f); GlStateManager.scale((float)2.0f, (float)2.0f, (float)2.0f); GlStateManager.popMatrix(); } void renderDuraBar(ItemStack stack, int x, int y) { GlStateManager.disableLighting(); GlStateManager.disableDepth(); GlStateManager.disableTexture2D(); GlStateManager.disableAlpha(); GlStateManager.disableBlend(); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferbuilder = tessellator.getBuffer(); double health = stack.getItem().getDurabilityForDisplay(stack); int rgbfordisplay = stack.getItem().getRGBDurabilityForDisplay(stack); int i = Math.round(13.0f - (float)health * 13.0f); int j = rgbfordisplay; this.draw(bufferbuilder, x + 2, y + 13, 13, 2, 0, 0, 0, 255); this.draw(bufferbuilder, x + 2, y + 13, i, 1, j >> 16 & 0xFF, j >> 8 & 0xFF, j & 0xFF, 255); GlStateManager.enableBlend(); GlStateManager.enableAlpha(); GlStateManager.enableTexture2D(); GlStateManager.enableLighting(); GlStateManager.enableDepth(); } void draw(BufferBuilder renderer, int x, int y, int width, int height, int red, int green, int blue, int alpha) { renderer.begin(7, DefaultVertexFormats.POSITION_COLOR); renderer.pos((double)(x + 0), (double)(y + 0), 0.0).color(red, green, blue, alpha).endVertex(); renderer.pos((double)(x + 0), (double)(y + height), 0.0).color(red, green, blue, alpha).endVertex(); renderer.pos((double)(x + width), (double)(y + height), 0.0).color(red, green, blue, alpha).endVertex(); renderer.pos((double)(x + width), (double)(y + 0), 0.0).color(red, green, blue, alpha).endVertex(); Tessellator.getInstance().draw(); } String getNametagString(EntityPlayer player) { if (player == null) { return ""; } String pingS = mc.getConnection() != null ? mc.getConnection().getPlayerInfo(Nametags.mc.player.getUniqueID()).getResponseTime() + "ms" : "-1ms"; String healthS = (int)(player.getHealth() + player.getAbsorptionAmount()) + ""; String str = (FriendManager.INSTANCE.isFriend((Entity)player) ? ChatFormatting.AQUA : "") + player.getName() + ChatFormatting.RESET + (FriendManager.INSTANCE.isFriend((Entity)player) ? ChatFormatting.AQUA : ""); str = str + " "; str = str + (this.ping.getValue() != false ? pingS : ""); str = str + " "; str = str + (this.health.getValue() != false ? healthS : ""); return str; } public static Vec3d interpolateEntityByTicks(Entity entity, float renderPartialTicks) { return new Vec3d(Nametags.calculateDistanceWithPartialTicks(entity.posX, entity.lastTickPosX, renderPartialTicks) - Nametags.mc.getRenderManager().viewerPosX, Nametags.calculateDistanceWithPartialTicks(entity.posY, entity.lastTickPosY, renderPartialTicks) - Nametags.mc.getRenderManager().viewerPosY, Nametags.calculateDistanceWithPartialTicks(entity.posZ, entity.lastTickPosZ, renderPartialTicks) - Nametags.mc.getRenderManager().viewerPosZ); } public static Vec3d interpolateEntity(Entity entity, float renderPartialTicks) { return new Vec3d(Nametags.calculateDistanceWithPartialTicks(entity.posX, entity.lastTickPosX, renderPartialTicks), Nametags.calculateDistanceWithPartialTicks(entity.posY, entity.lastTickPosY, renderPartialTicks), Nametags.calculateDistanceWithPartialTicks(entity.posZ, entity.lastTickPosZ, renderPartialTicks)); } public static double calculateDistanceWithPartialTicks(double originalPos, double finalPos, float renderPartialTicks) { return finalPos + (originalPos - finalPos) * (double)mc.getRenderPartialTicks(); } public void prepareTranslation(double x, double y, double z, double distanceScale) { GlStateManager.enablePolygonOffset(); GlStateManager.doPolygonOffset((float)1.0f, (float)-1500000.0f); GlStateManager.disableLighting(); GlStateManager.translate((float)((float)x), (float)((float)y + 1.4f), (float)((float)z)); GlStateManager.rotate((float)(-Nametags.mc.getRenderManager().playerViewY), (float)0.0f, (float)1.0f, (float)0.0f); GlStateManager.rotate((float)Nametags.mc.getRenderManager().playerViewX, (float)(Nametags.mc.gameSettings.thirdPersonView == 2 ? -1.0f : 1.0f), (float)0.0f, (float)0.0f); GlStateManager.scale((double)(-(distanceScale / 100.0)), (double)(-(distanceScale / 100.0)), (double)(distanceScale / 100.0)); GlStateManager.disableDepth(); GlStateManager.enableBlend(); } public void release() { GlStateManager.enableDepth(); GlStateManager.disableBlend(); GlStateManager.disablePolygonOffset(); GlStateManager.doPolygonOffset((float)1.0f, (float)1500000.0f); } }
923832ed204055e33099980e1a94430efc0702c6
284
java
Java
demo-design/demo-design-100/src/main/java/com/demo/design/dto/AwardRequest.java
wjgful4163/design
bb8b62aed89e8053a6b671d7f0c0d3d82e53c768
[ "Apache-2.0" ]
null
null
null
demo-design/demo-design-100/src/main/java/com/demo/design/dto/AwardRequest.java
wjgful4163/design
bb8b62aed89e8053a6b671d7f0c0d3d82e53c768
[ "Apache-2.0" ]
null
null
null
demo-design/demo-design-100/src/main/java/com/demo/design/dto/AwardRequest.java
wjgful4163/design
bb8b62aed89e8053a6b671d7f0c0d3d82e53c768
[ "Apache-2.0" ]
null
null
null
15.777778
31
0.683099
998,346
package com.demo.design.dto; import lombok.Data; /** * @author wjgful * @version v1.0 * @description TODO * @date 2021/1/15 15:55 */ @Data public class AwardRequest { private String type; private Integer uid; private String awardNumber; private String bizId; }
92383339e505dd18a089dec33499f5313c9027fc
144
java
Java
chapter_005/src/main/java/ru/job4j/generics/OverflowException.java
AlexandrKarpachov/job4j
d1fa974d64d81004b919e00b3bd6a00770cb8a09
[ "Apache-2.0" ]
null
null
null
chapter_005/src/main/java/ru/job4j/generics/OverflowException.java
AlexandrKarpachov/job4j
d1fa974d64d81004b919e00b3bd6a00770cb8a09
[ "Apache-2.0" ]
2
2020-07-01T18:58:22.000Z
2020-07-01T19:09:28.000Z
chapter_005/src/main/java/ru/job4j/generics/OverflowException.java
AlexandrKarpachov/job4j
d1fa974d64d81004b919e00b3bd6a00770cb8a09
[ "Apache-2.0" ]
null
null
null
18
57
0.701389
998,347
package ru.job4j.generics; public class OverflowException extends RuntimeException { public OverflowException() { super(); } }
9238334eb49dd31943a4899b49a897d813694288
37,482
java
Java
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
renshuaibing-aaron/dubbo-aaron-2.7.5
884693317c14750856bde5c4cce6e01e9fd6f8ba
[ "Apache-2.0" ]
null
null
null
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
renshuaibing-aaron/dubbo-aaron-2.7.5
884693317c14750856bde5c4cce6e01e9fd6f8ba
[ "Apache-2.0" ]
4
2021-03-10T23:34:14.000Z
2021-12-14T21:59:17.000Z
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java
renshuaibing-aaron/dubbo-aaron-2.7.5
884693317c14750856bde5c4cce6e01e9fd6f8ba
[ "Apache-2.0" ]
null
null
null
44.515439
226
0.632197
998,348
package org.apache.dubbo.registry.integration; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.AddressListener; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.Cluster; import org.apache.dubbo.rpc.cluster.Configurator; import org.apache.dubbo.rpc.cluster.Router; import org.apache.dubbo.rpc.cluster.RouterChain; import org.apache.dubbo.rpc.cluster.RouterFactory; import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository; import org.apache.dubbo.rpc.cluster.support.ClusterUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.InvokerWrapper; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; /** * 动态目录 实现NotifyListener接口 服务变更会通知这个类实现 * 继承了 AbstractDirectory 类,而 AbstractDirectory 实现了 Directory 接口,Directory 接口中定义了一个非常重要的方法, * 即 list(Invocation invocation),用于列举 Invoker 列表 * Directory 接口又继承了 Node 接口,Node 接口中定义了一个非常重要的方法,即 getUrl(),获取配置信息 URL, * 实现该接口的类可以向外提供配置信息,dubbo 中像 Registry、Monitor、Invoker 等均继承了这个接口 * RegistryDirectory 不仅实现了 Directory 接口,还实现了 NotifyListener 接口,这样子的话,当注册中心节点信息发生变化后, * RegistryDirectory 可以通过此接口方法得到变更信息,并根据变更信息动态调整内部 Invoker 列表 */ public class RegistryDirectory<T> extends AbstractDirectory<T> implements NotifyListener { private static final Logger logger = LoggerFactory.getLogger(RegistryDirectory.class); private static final Cluster CLUSTER = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); private static final RouterFactory ROUTER_FACTORY = ExtensionLoader.getExtensionLoader(RouterFactory.class) .getAdaptiveExtension(); //com.alibaba.dubbo.registry.RegistryService private final String serviceKey; // Initialization at construction time, assertion not null //interface com.alibaba.dubbo.demo.DemoService private final Class<T> serviceType; // Initialization at construction time, assertion not null //{side=consumer, application=demo-consumer, register.ip=10.10.10.10, methods=sayHello, dubbo=2.0.0, pid=25267, check=false, interface=com.alibaba.dubbo.demo.DemoService, timestamp=1510225913509} private final Map<String, String> queryMap; // Initialization at construction time, assertion not null private final URL directoryUrl; // Initialization at construction time, assertion not null, and always assign non null value private final boolean multiGroup; private Protocol protocol; // Initialization at the time of injection, the assertion is not null //上述的ZookeeperRegistry实例(zookeeper://10.211.55.5:2181/com.alibaba.dubbo.registry.RegistryService?application=demo-consumer&dubbo=2.0.0&interface=com.alibaba.dubbo.registry.RegistryService&pid=25267&timestamp=1510225984358) private Registry registry; // Initialization at the time of injection, the assertion is not null private volatile boolean forbidden = false; private volatile URL overrideDirectoryUrl; // Initialization at construction time, assertion not null, and always assign non null value private volatile URL registeredConsumerUrl; /** * override rules * Priority: override>-D>consumer>provider * Rule one: for a certain provider <ip:port,timeout=100> * Rule two: for all providers <* ,timeout=5000> */ private volatile List<Configurator> configurators; // The initial value is null and the midway may be assigned to null, please use the local variable reference // Map<url, Invoker> cache service url to invoker mapping. // 以注释处的例子为例,初始化之后:{"sayHello":[A,B], "sayBye":[B], "*":[router过滤后的provider]} private volatile Map<String, Invoker<T>> urlInvokerMap; // The initial value is null and the midway may be assigned to null, please use the local variable reference private volatile List<Invoker<T>> invokers; // Set<invokerUrls> cache invokeUrls to invokers mapping. private volatile Set<URL> cachedInvokerUrls; // The initial value is null and the midway may be assigned to null, please use the local variable reference private static final ConsumerConfigurationListener CONSUMER_CONFIGURATION_LISTENER = new ConsumerConfigurationListener(); private ReferenceConfigurationListener serviceConfigurationListener; public RegistryDirectory(Class<T> serviceType, URL url) { super(url); if (serviceType == null) { throw new IllegalArgumentException("service type is null."); } if (url.getServiceKey() == null || url.getServiceKey().length() == 0) { throw new IllegalArgumentException("registry serviceKey is null."); } this.serviceType = serviceType; this.serviceKey = url.getServiceKey(); this.queryMap = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); this.overrideDirectoryUrl = this.directoryUrl = turnRegistryUrlToConsumerUrl(url); String group = directoryUrl.getParameter(GROUP_KEY, ""); this.multiGroup = group != null && (ANY_VALUE.equals(group) || group.contains(",")); } private URL turnRegistryUrlToConsumerUrl(URL url) { // save any parameter in registry that will be useful to the new url. String isDefault = url.getParameter(PREFERRED_KEY); if (StringUtils.isNotEmpty(isDefault)) { queryMap.put(REGISTRY_KEY + "." + PREFERRED_KEY, isDefault); } return URLBuilder.from(url) .setPath(url.getServiceInterface()) .clearParameters() .addParameters(queryMap) .removeParameter(MONITOR_KEY) .build(); } public void setProtocol(Protocol protocol) { this.protocol = protocol; } public void setRegistry(Registry registry) { this.registry = registry; } public void subscribe(URL url) { setConsumerUrl(url); CONSUMER_CONFIGURATION_LISTENER.addNotifyListener(this); serviceConfigurationListener = new ReferenceConfigurationListener(this, url); //FailbackRegistry.subscribe(URL url, NotifyListener listener) registry.subscribe(url, this); } @Override public void destroy() { if (isDestroyed()) { return; } // unregister. try { if (getRegisteredConsumerUrl() != null && registry != null && registry.isAvailable()) { registry.unregister(getRegisteredConsumerUrl()); } } catch (Throwable t) { logger.warn("unexpected error when unregister service " + serviceKey + "from registry" + registry.getUrl(), t); } // unsubscribe. try { if (getConsumerUrl() != null && registry != null && registry.isAvailable()) { registry.unsubscribe(getConsumerUrl(), this); } ExtensionLoader.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension() .removeListener(ApplicationModel.getApplication(), CONSUMER_CONFIGURATION_LISTENER); } catch (Throwable t) { logger.warn("unexpected error when unsubscribe service " + serviceKey + "from registry" + registry.getUrl(), t); } super.destroy(); // must be executed after unsubscribing try { destroyAllInvokers(); } catch (Throwable t) { logger.warn("Failed to destroy service " + serviceKey, t); } } /************************* 初始化更新 newMethodInvokerMap *************************/ // 订阅providers、configurators、routers时,执行的通知逻辑 //通过这个接口可以获取到注册中心变更通知 /** * 1)、根据url中的 protocol 或者 category 参数对 URL 分类存储 * 2)、toConfigurators 和 toRouters 方法分别将 url 转成了 Configurator 和 Router * 3)、根据提供者 url 列表刷新 invoker 列表 * @param urls The list of registered information , is always not empty. The meaning is the same as the return value of {@link org.apache.dubbo.registry.RegistryService#lookup(URL)}. */ @Override public synchronized void notify(List<URL> urls) { // 定义三个 集合,分别为 provider 的 configurators URL、routers URL 和 providers URL Map<String, List<URL>> categoryUrls = urls.stream() .filter(Objects::nonNull) .filter(this::isValidCategory) .filter(this::isNotCompatibleFor26x) .collect(Collectors.groupingBy(url -> { if (UrlUtils.isConfigurator(url)) { // configurators URL return CONFIGURATORS_CATEGORY; } else if (UrlUtils.isRoute(url)) { // routers URL return ROUTERS_CATEGORY; } else if (UrlUtils.isProvider(url)) { // providers URL return PROVIDERS_CATEGORY; } return ""; })); List<URL> configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList()); // configurators URL 转成 Configurator this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators); List<URL> routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList()); // routes URL 转成 Router toRouters(routerURLs).ifPresent(this::addRouters); // providers // 提供者 URL 列表 List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList()); /** * 3.x added for extend URL address */ ExtensionLoader<AddressListener> addressListenerExtensionLoader = ExtensionLoader.getExtensionLoader(AddressListener.class); List<AddressListener> supportedListeners = addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null); if (supportedListeners != null && !supportedListeners.isEmpty()) { for (AddressListener addressListener : supportedListeners) { providerURLs = addressListener.notify(providerURLs, getUrl(),this); } } //refreshInvoker(invokerUrls); //首先将输入的两个provider的url存放在invokerUrls列表中,之后调用refreshInvoker(invokerUrls) refreshOverrideAndInvoker(providerURLs); } private void refreshOverrideAndInvoker(List<URL> urls) { // mock zookeeper://xxx?mock=return null // 获取配置 overrideDirectoryUrl 值 overrideDirectoryUrl(); // 刷新 invoker 列表 refreshInvoker(urls); } /** * 1)、根据入参 invokerUrls 的数量和 url 的协议头判断是否需要禁用所有服务,若需要 forbidden 设为 true,并销毁所有的 Invoker * 2)、将 url 转换成 invoker,并得到 <url, Invoker> 的映射关系 * 3)、合并多个组的 invoker,并赋值给 invokers 变量 * 4)、销毁无用的 invoker,避免 consumer 调用下线的 provider * Convert the invokerURL list to the Invoker Map. The rules of the conversion are as follows: * <ol> * <li> If URL has been converted to invoker, it is no longer re-referenced and obtained directly from the cache, * and notice that any parameter changes in the URL will be re-referenced.</li> * <li>If the incoming invoker list is not empty, it means that it is the latest invoker list.</li> * <li>If the list of incoming invokerUrl is empty, It means that the rule is only a override rule or a route * rule, which needs to be re-contrasted to decide whether to re-reference.</li> * </ol> * * @param invokerUrls this parameter can't be null */ // TODO: 2017/8/31 FIXME The thread pool should be used to refresh the address, otherwise the task may be accumulated. private void refreshInvoker(List<URL> invokerUrls) { logger.info("===========刷新invoker列表=========refreshInvoker"); Assert.notNull(invokerUrls, "invokerUrls should not be null"); // invokerUrls 中只有一个元素 && url 的协议头 Protocol 为 empty,表示禁用所有服务 if (invokerUrls.size() == 1&& invokerUrls.get(0) != null && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) { // 禁用服务标识 this.forbidden = true; // Forbid to access // 空 invoker 列表 this.invokers = Collections.emptyList(); routerChain.setInvokers(this.invokers); // 销毁所有的 invoker destroyAllInvokers(); // Close all invokers } else { this.forbidden = false; // Allow to access // 原来的 invoker 映射map Map<String, Invoker<T>> oldUrlInvokerMap = this.urlInvokerMap; // local reference if (invokerUrls == Collections.<URL>emptyList()) { invokerUrls = new ArrayList<>(); } if (invokerUrls.isEmpty() && this.cachedInvokerUrls != null) { //缓存invokerUrls列表,便于交叉对比 invokerUrls.addAll(this.cachedInvokerUrls); } else { this.cachedInvokerUrls = new HashSet<>(); // 缓存 invokerUrls this.cachedInvokerUrls.addAll(invokerUrls);//Cached invoker urls, convenient for comparison } if (invokerUrls.isEmpty()) { return; } // Translate url list to Invoker map => 将url转换为InvokerDelegate // 将 url 转换成 url 到 invoker 映射 map,map 中 url 为 key,value 为 invoker Map<String, Invoker<T>> newUrlInvokerMap = toInvokers(invokerUrls);// Translate url list to Invoker map /** * If the calculation is wrong, it is not processed. * * 1. The protocol configured by the client is inconsistent with the protocol of the server. * eg: consumer protocol = dubbo, provider only has other protocol services(rest). * 2. The registration center is not robust and pushes illegal specification data. * */ if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) { logger.error(new IllegalStateException("urls to invokers error .invokerUrls.size :" + invokerUrls.size() + ", invoker.size :0. urls :" + invokerUrls .toString())); return; } List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values())); // pre-route and build cache, notice that route cache should build on original Invoker list. // toMergeMethodInvokerMap() will wrap some invokers having different groups, those wrapped invokers not should be routed. routerChain.setInvokers(newInvokers); // 多个 group 时需要合并 invoker this.invokers = multiGroup ? toMergeInvokerList(newInvokers) : newInvokers; this.urlInvokerMap = newUrlInvokerMap; try { // 销毁不需要的 invoker destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker } catch (Exception e) { logger.warn("destroyUnusedInvokers error. ", e); } } } /** * 多个组的 invoker 合并逻辑 * @param invokers * @return */ private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) { List<Invoker<T>> mergedInvokers = new ArrayList<>(); Map<String, List<Invoker<T>>> groupMap = new HashMap<>(); // 遍历 invoker 进行分组 for (Invoker<T> invoker : invokers) { // url 中获取 group 配置 String group = invoker.getUrl().getParameter(GROUP_KEY, ""); groupMap.computeIfAbsent(group, k -> new ArrayList<>()); // invoker 放入同一组中 groupMap.get(group).add(invoker); } if (groupMap.size() == 1) { // 只有一个分组,直接取出值 mergedInvokers.addAll(groupMap.values().iterator().next()); } else if (groupMap.size() > 1) { // 多个分组时,遍历分组中的 invoker列表,并调用集群的 join 方法合并每个组的 invoker 列表 for (List<Invoker<T>> groupList : groupMap.values()) { StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList); staticDirectory.buildRouterChain(); // 通过集群类 的 join 方法合并每个分组对应的 Invoker 列表 mergedInvokers.add(CLUSTER.join(staticDirectory)); } } else { mergedInvokers = invokers; } return mergedInvokers; } /** * @param urls * @return null : no routers ,do nothing * else :routers list */ private Optional<List<Router>> toRouters(List<URL> urls) { if (urls == null || urls.isEmpty()) { return Optional.empty(); } List<Router> routers = new ArrayList<>(); for (URL url : urls) { if (EMPTY_PROTOCOL.equals(url.getProtocol())) { continue; } String routerType = url.getParameter(ROUTER_KEY); if (routerType != null && routerType.length() > 0) { url = url.setProtocol(routerType); } try { Router router = ROUTER_FACTORY.getRouter(url); if (!routers.contains(router)) { routers.add(router); } } catch (Throwable t) { logger.error("convert router url to router error, url: " + url, t); } } return Optional.of(routers); } /** * Turn urls into invokers, and if url has been refer, will not re-reference. * 1. 获取 provider 的所有方法 methods=xxx,yyy,zzz * (同一个接口的不同 provider 的 methods 参数可能不同,例如 DemoService#sayHello() 在 providerA 中有,后续添加了 DemoService#sayBye() 之后,部署到了 providerB, * 此时 providerA 还没部署,这一时刻,进行的服务发现根据 serviceKey 会发现 providerA 和 providerB,但是二者所拥有的方法却是不同的,那么经过如下逻辑后, * newMethodInvokerMap={"sayHello":[A,B], "sayBye":[B]}) * @param urls * @return invokers */ private Map<String, Invoker<T>> toInvokers(List<URL> urls) { Map<String, Invoker<T>> newUrlInvokerMap = new HashMap<>(); if (urls == null || urls.isEmpty()) { // 列表为空,直接返回 return newUrlInvokerMap; } Set<String> keys = new HashSet<>(); // 获取 consumer 端配置的协议 String queryProtocols = this.queryMap.get(PROTOCOL_KEY); for (URL providerUrl : urls) { // If protocol is configured at the reference side, only the matching protocol is selected // 如果在 consumer 端配置了协议,则只选择匹配的协议 if (queryProtocols != null && queryProtocols.length() > 0) { boolean accept = false; String[] acceptProtocols = queryProtocols.split(","); for (String acceptProtocol : acceptProtocols) { // provider 协议是否被 consumer 协议支持 if (providerUrl.getProtocol().equals(acceptProtocol)) { accept = true; break; } } if (!accept) { // provider 协议不被 consumer 协议支持,则忽略此 url continue; } } // 忽略 empty 协议 if (EMPTY_PROTOCOL.equals(providerUrl.getProtocol())) { continue; } // 通过 SPI 检测 provider 端协议是否被 consumer 端支持,不支持则抛出异常 if (!ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(providerUrl.getProtocol())) { logger.error(new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: " + providerUrl + " from registry " + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + ExtensionLoader.getExtensionLoader(Protocol.class).getSupportedExtensions())); continue; } // 合并 url 参数,顺序是 : override > -D > Consumer > Provider URL url = mergeUrl(providerUrl); // url 参数拼接的字符串且被排序了, // 例如:dubbo://192.168.1.247:20887/org.apache.dubbo.config.spring.api.DemoService?anyhost=true&application=service-class& // bean.name=org.apache.dubbo.config.spring.api.DemoService&bind.ip=192.168.1.247&bind.port=20887& // class=org.apache.dubbo.config.spring.impl.DemoServiceImpl&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false& // interface=org.apache.dubbo.config.spring.api.DemoService&methods=sayName,getBox&owner=world&pid=24316&register=true& String key = url.toFullString(); // The parameter urls are sorted if (keys.contains(key)) { // Repeated url // 忽略重复 key continue; } keys.add(key); // 原来本地缓存的 <url, Invoker> // Cache key is url that does not merge with consumer side parameters, regardless of how the consumer combines parameters, if the server url changes, then refer again Map<String, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap; // local reference // 获取现有的 url 对应的 invoker Invoker<T> invoker = localUrlInvokerMap == null ? null : localUrlInvokerMap.get(key); // 原来缓存没有或者provider配置变化了 if (invoker == null) { // Not in the cache, refer again try { boolean enabled = true; if (url.hasParameter(DISABLED_KEY)) { // 获取 url 中 disable 配置值,取反,然后赋值给 enable 变量 enabled = !url.getParameter(DISABLED_KEY, false); } else { // 获取 url 中 enable 配置值 enabled = url.getParameter(ENABLED_KEY, true); } if (enabled) { // 调用 Protocol 的 refer 方法构建获取 Invoker // 具体调用流程是 refer(ProtocolListenerWrapper) -> refer(ProtocolFilterWrapper) -> refer(AbstractProtocol) //这里会遍历两个providerUrl:protocol是Protocol$Adaptive实例,依旧是走listener->filter->DubboProtocol,看一下filter部分 Invoker<T> refer = protocol.refer(serviceType, url); invoker = new InvokerDelegate<>(refer, url, providerUrl); } } catch (Throwable t) { logger.error("Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + t.getMessage(), t); } if (invoker != null) { // Put new invoker in cache // 新 invoker 放入缓存 newUrlInvokerMap.put(key, invoker); } } else { newUrlInvokerMap.put(key, invoker); } } keys.clear(); return newUrlInvokerMap; } /** * Merge url parameters. the order is: override > -D >Consumer > Provider * * @param providerUrl * @return */ private URL mergeUrl(URL providerUrl) { providerUrl = ClusterUtils.mergeUrl(providerUrl, queryMap); // Merge the consumer side parameters providerUrl = overrideWithConfigurator(providerUrl); providerUrl = providerUrl.addParameter(Constants.CHECK_KEY, String.valueOf(false)); // Do not check whether the connection is successful or not, always create Invoker! // The combination of directoryUrl and override is at the end of notify, which can't be handled here this.overrideDirectoryUrl = this.overrideDirectoryUrl.addParametersIfAbsent(providerUrl.getParameters()); // Merge the provider side parameters if ((providerUrl.getPath() == null || providerUrl.getPath() .length() == 0) && DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0 //fix by tony.chenl DUBBO-44 String path = directoryUrl.getParameter(INTERFACE_KEY); if (path != null) { int i = path.indexOf('/'); if (i >= 0) { path = path.substring(i + 1); } i = path.lastIndexOf(':'); if (i >= 0) { path = path.substring(0, i); } providerUrl = providerUrl.setPath(path); } } return providerUrl; } private URL overrideWithConfigurator(URL providerUrl) { // override url with configurator from "override://" URL for dubbo 2.6 and before providerUrl = overrideWithConfigurators(this.configurators, providerUrl); // override url with configurator from configurator from "app-name.configurators" providerUrl = overrideWithConfigurators(CONSUMER_CONFIGURATION_LISTENER.getConfigurators(), providerUrl); // override url with configurator from configurators from "service-name.configurators" if (serviceConfigurationListener != null) { providerUrl = overrideWithConfigurators(serviceConfigurationListener.getConfigurators(), providerUrl); } return providerUrl; } private URL overrideWithConfigurators(List<Configurator> configurators, URL url) { if (CollectionUtils.isNotEmpty(configurators)) { for (Configurator configurator : configurators) { url = configurator.configure(url); } } return url; } /** * Close all invokers */ private void destroyAllInvokers() { Map<String, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap; // local reference if (localUrlInvokerMap != null) { for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) { try { invoker.destroy(); } catch (Throwable t) { logger.warn("Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), t); } } localUrlInvokerMap.clear(); } invokers = null; } /** * Check whether the invoker in the cache needs to be destroyed * If set attribute of url: refer.autodestroy=false, the invokers will only increase without decreasing,there may be a refer leak * * @param oldUrlInvokerMap * @param newUrlInvokerMap */ private void destroyUnusedInvokers(Map<String, Invoker<T>> oldUrlInvokerMap, Map<String, Invoker<T>> newUrlInvokerMap) { if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) { // 新的 invoker 为空,表明禁用了所有的 provider,这里销毁所有的 invoke destroyAllInvokers(); return; } // check deleted invoker // 记录需要被销毁的 invoker 列表 List<String> deleted = null; if (oldUrlInvokerMap != null) { Collection<Invoker<T>> newInvokers = newUrlInvokerMap.values(); for (Map.Entry<String, Invoker<T>> entry : oldUrlInvokerMap.entrySet()) { // 新的 invoker 列表中不包含原有的 invoker,则该 invoker 需要被销毁 if (!newInvokers.contains(entry.getValue())) { if (deleted == null) { deleted = new ArrayList<>(); } // 该 invoker 添加到销毁列表中 deleted.add(entry.getKey()); } } } // 销毁列表中有数据,需要销毁 invoker if (deleted != null) { for (String url : deleted) { if (url != null) { // 缓存中移除要销毁的 invoker Invoker<T> invoker = oldUrlInvokerMap.remove(url); if (invoker != null) { try { // 销毁 invoker invoker.destroy(); if (logger.isDebugEnabled()) { logger.debug("destroy invoker[" + invoker.getUrl() + "] success. "); } } catch (Exception e) { logger.warn("destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(), e); } } } } } } /************************* 从 newMethodInvokerMap 中选择 Invoker *************************/ ////从Map<String, List<Invoker<T>>> methodInvokerMap中获取key为sayHello的List<Invoker<T>> @Override public List<Invoker<T>> doList(Invocation invocation) { if (forbidden) { // 1. No service provider 2. Service providers are disabled // provider 关闭或禁用了服务,此时抛出 No provider 异常 throw new RpcException(RpcException.FORBIDDEN_EXCEPTION, "No provider available from registry " + getUrl().getAddress() + " for service " + getConsumerUrl().getServiceKey() + " on consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please check status of providers(disabled, not registered or in blacklist)."); } if (multiGroup) { // 多个 group 的话直接返回 invoker 列表 return this.invokers == null ? Collections.emptyList() : this.invokers; } List<Invoker<T>> invokers = null; System.out.println("======查找路由=========="); try { // Get invokers from cache, only runtime routers will be executed. //route 路由器职责链过滤满足条件的 Invoker 列表 invokers = routerChain.route(getConsumerUrl(), invocation); } catch (Throwable t) { logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t); } return invokers == null ? Collections.emptyList() : invokers; } @Override public Class<T> getInterface() { return serviceType; } @Override public List<Invoker<T>> getAllInvokers() { return invokers; } @Override public URL getUrl() { return this.overrideDirectoryUrl; } public URL getRegisteredConsumerUrl() { return registeredConsumerUrl; } public void setRegisteredConsumerUrl(URL registeredConsumerUrl) { this.registeredConsumerUrl = registeredConsumerUrl; } @Override public boolean isAvailable() { if (isDestroyed()) { return false; } Map<String, Invoker<T>> localUrlInvokerMap = urlInvokerMap; if (localUrlInvokerMap != null && localUrlInvokerMap.size() > 0) { for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) { if (invoker.isAvailable()) { return true; } } } return false; } public void buildRouterChain(URL url) { this.setRouterChain(RouterChain.buildChain(url)); } /** * Haomin: added for test purpose */ public Map<String, Invoker<T>> getUrlInvokerMap() { return urlInvokerMap; } public List<Invoker<T>> getInvokers() { return invokers; } private boolean isValidCategory(URL url) { String category = url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) || PROVIDERS_CATEGORY.equals(category) || CONFIGURATORS_CATEGORY.equals(category) || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) || APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { return true; } logger.warn("Unsupported category " + category + " in notified url: " + url + " from registry " + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost()); return false; } private boolean isNotCompatibleFor26x(URL url) { return StringUtils.isEmpty(url.getParameter(COMPATIBLE_CONFIG_KEY)); } private void overrideDirectoryUrl() { // merge override parameters this.overrideDirectoryUrl = directoryUrl; List<Configurator> localConfigurators = this.configurators; // local reference doOverrideUrl(localConfigurators); List<Configurator> localAppDynamicConfigurators = CONSUMER_CONFIGURATION_LISTENER.getConfigurators(); // local reference doOverrideUrl(localAppDynamicConfigurators); if (serviceConfigurationListener != null) { List<Configurator> localDynamicConfigurators = serviceConfigurationListener.getConfigurators(); // local reference doOverrideUrl(localDynamicConfigurators); } } private void doOverrideUrl(List<Configurator> configurators) { if (CollectionUtils.isNotEmpty(configurators)) { for (Configurator configurator : configurators) { this.overrideDirectoryUrl = configurator.configure(overrideDirectoryUrl); } } } /** * The delegate class, which is mainly used to store the URL address sent by the registry,and can be reassembled on the basis of providerURL queryMap overrideMap for re-refer. * * @param <T> */ private static class InvokerDelegate<T> extends InvokerWrapper<T> { private URL providerUrl; public InvokerDelegate(Invoker<T> invoker, URL url, URL providerUrl) { super(invoker, url); this.providerUrl = providerUrl; } public URL getProviderUrl() { return providerUrl; } } private static class ReferenceConfigurationListener extends AbstractConfiguratorListener { private RegistryDirectory directory; private URL url; ReferenceConfigurationListener(RegistryDirectory directory, URL url) { this.directory = directory; this.url = url; this.initWith(DynamicConfiguration.getRuleKey(url) + CONFIGURATORS_SUFFIX); } @Override protected void notifyOverrides() { // to notify configurator/router changes directory.refreshInvoker(Collections.emptyList()); } } private static class ConsumerConfigurationListener extends AbstractConfiguratorListener { List<RegistryDirectory> listeners = new ArrayList<>(); ConsumerConfigurationListener() { this.initWith(ApplicationModel.getApplication() + CONFIGURATORS_SUFFIX); } void addNotifyListener(RegistryDirectory listener) { this.listeners.add(listener); } @Override protected void notifyOverrides() { listeners.forEach(listener -> listener.refreshInvoker(Collections.emptyList())); } } }
923833a55b0867046077cc2131cbbd5d0d33ba60
371
java
Java
ebpp-gateway/src/main/java/com/higlowx/scal/ebpp/gateway/AppStart.java
higlowx/spring-cloud-alibaba-learning
c3dffcc261e15d755098f8345b4ea43c308f6fb4
[ "Apache-2.0" ]
null
null
null
ebpp-gateway/src/main/java/com/higlowx/scal/ebpp/gateway/AppStart.java
higlowx/spring-cloud-alibaba-learning
c3dffcc261e15d755098f8345b4ea43c308f6fb4
[ "Apache-2.0" ]
null
null
null
ebpp-gateway/src/main/java/com/higlowx/scal/ebpp/gateway/AppStart.java
higlowx/spring-cloud-alibaba-learning
c3dffcc261e15d755098f8345b4ea43c308f6fb4
[ "Apache-2.0" ]
1
2021-10-09T08:43:49.000Z
2021-10-09T08:43:49.000Z
20.611111
68
0.738544
998,349
package com.higlowx.scal.ebpp.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author Dylan.Li * @date 2021/7/7 * @since */ @SpringBootApplication public class AppStart { public static void main(String[] args) { SpringApplication.run(AppStart.class, args); } }
923833ed86e249048d73fd2da94b25d6dd214141
657
java
Java
src/main/java/com/ohun/stomp/common/ClientListenerAdapter.java
zeng33/stomp-client
63626bf0cfb84831d83ff2c05b40222d421590e3
[ "Apache-2.0" ]
10
2015-07-05T05:04:45.000Z
2021-01-13T09:06:04.000Z
src/main/java/com/ohun/stomp/common/ClientListenerAdapter.java
ohun/stomp-client
63626bf0cfb84831d83ff2c05b40222d421590e3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ohun/stomp/common/ClientListenerAdapter.java
ohun/stomp-client
63626bf0cfb84831d83ff2c05b40222d421590e3
[ "Apache-2.0" ]
7
2016-06-08T07:51:45.000Z
2019-05-05T05:12:31.000Z
21.9
79
0.649924
998,350
package com.ohun.stomp.common; import com.ohun.stomp.StompClient; import com.ohun.stomp.api.ClientListener; /** * Created by xiaoxu.yxx on 2014/10/9. */ public class ClientListenerAdapter implements ClientListener { public static final ClientListener INSTANCE = new ClientListenerAdapter(); @Override public void onConnected(StompClient client) { } @Override public void onDisconnected(StompClient client) { } @Override public void onException(StompClient client, Throwable throwable) { try { client.reconnect(); } catch (Throwable e) { } } }
923834217e2215aa816175ab745c69b42fdd1a04
3,608
java
Java
04Reflection/src/_04BarracksWarsTheCommandsStrikeBack/core/Engine.java
lapd87/SoftUniJavaOOPAdvanced
e06cf284fffc7259210a94f327d078d228edf76f
[ "MIT" ]
null
null
null
04Reflection/src/_04BarracksWarsTheCommandsStrikeBack/core/Engine.java
lapd87/SoftUniJavaOOPAdvanced
e06cf284fffc7259210a94f327d078d228edf76f
[ "MIT" ]
null
null
null
04Reflection/src/_04BarracksWarsTheCommandsStrikeBack/core/Engine.java
lapd87/SoftUniJavaOOPAdvanced
e06cf284fffc7259210a94f327d078d228edf76f
[ "MIT" ]
null
null
null
32.214286
101
0.629989
998,351
package _04BarracksWarsTheCommandsStrikeBack.core; import _04BarracksWarsTheCommandsStrikeBack.contracts.Executable; import _04BarracksWarsTheCommandsStrikeBack.contracts.Repository; import _04BarracksWarsTheCommandsStrikeBack.contracts.UnitFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Engine implements Runnable { private static final String COMMAND_PATH = "_04BarracksWarsTheCommandsStrikeBack.core.commands."; private static final String COMMAND_NAME_SUFFIX = "Command"; private Repository repository; private UnitFactory unitFactory; public Engine(Repository repository, UnitFactory unitFactory) { this.repository = repository; this.unitFactory = unitFactory; } @Override public void run() { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); while (true) { try { String input = reader.readLine(); String[] data = input.split("\\s+"); String commandName = data[0]; String result = interpretCommand(data, commandName); if (result.equals("fight")) { break; } System.out.println(result); } catch (RuntimeException e) { System.out.println(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } } } // TODOs: refactor for problem 4 private String interpretCommand(String[] data, String commandName) { try { String commandClassName = Character.toUpperCase(commandName.charAt(0)) + commandName.substring(1).toLowerCase(); Class<?> commandClass = Class.forName(COMMAND_PATH + commandClassName + COMMAND_NAME_SUFFIX); Constructor<?> declaredConstructor = commandClass.getDeclaredConstructor(String[].class, Repository.class, UnitFactory.class); declaredConstructor.setAccessible(true); Executable executable = (Executable) declaredConstructor .newInstance(data, this.repository, this.unitFactory); return executable.execute(); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Invalid command!"); } // String result; // switch (commandName) { // case "add": // result = this.addUnitCommand(data); // break; // case "report": // result = this.reportCommand(data); // break; // case "fight": // result = this.fightCommand(data); // break; // default: // throw new RuntimeException("Invalid command!"); // } // return result; } // private String reportCommand(String[] data) { // String output = this.repository.getStatistics(); // return output; // } // private String addUnitCommand(String[] data) throws ExecutionControl.NotImplementedException { // String unitType = data[1]; // Unit unitToAdd = this.unitFactory.createUnit(unitType); // this.repository.addUnit(unitToAdd); // String output = unitType + " added!"; // return output; // } // private String fightCommand(String[] data) { // return "fight"; // } }
9238350089b207dc2e58bc4df2fbe338a086f9d8
2,837
java
Java
dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/ErrorEntityWriterTest.java
karandkanwar/dropwizard
90a939ae5838361bc99447964cc7285aad9ad8d5
[ "Apache-2.0" ]
2
2015-04-15T06:34:55.000Z
2019-05-07T09:50:43.000Z
dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/ErrorEntityWriterTest.java
karandkanwar/dropwizard
90a939ae5838361bc99447964cc7285aad9ad8d5
[ "Apache-2.0" ]
10
2020-06-08T13:50:09.000Z
2020-08-11T05:19:55.000Z
dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/ErrorEntityWriterTest.java
karandkanwar/dropwizard
90a939ae5838361bc99447964cc7285aad9ad8d5
[ "Apache-2.0" ]
1
2019-08-16T09:43:50.000Z
2019-08-16T09:43:50.000Z
39.402778
118
0.722242
998,352
package io.dropwizard.jersey.errors; import com.codahale.metrics.MetricRegistry; import io.dropwizard.jersey.AbstractJerseyTest; import io.dropwizard.jersey.DropwizardResourceConfig; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletProperties; import org.glassfish.jersey.test.DeploymentContext; import org.glassfish.jersey.test.ServletDeploymentContext; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.glassfish.jersey.test.spi.TestContainerException; import org.glassfish.jersey.test.spi.TestContainerFactory; import org.junit.Test; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; public class ErrorEntityWriterTest extends AbstractJerseyTest { public static class ErrorEntityWriterTestResourceConfig extends DropwizardResourceConfig { public ErrorEntityWriterTestResourceConfig() { super(true, new MetricRegistry()); register(DefaultLoggingExceptionMapper.class); register(DefaultJacksonMessageBodyProvider.class); register(ExceptionResource.class); register(new ErrorEntityWriter<ErrorMessage, String>(MediaType.TEXT_HTML_TYPE, String.class) { @Override protected String getRepresentation(ErrorMessage entity) { return "<!DOCTYPE html><html><body>" + entity.getMessage() + "</body></html>"; } }); } } @Override protected TestContainerFactory getTestContainerFactory() throws TestContainerException { return new GrizzlyWebTestContainerFactory(); } @Override protected DeploymentContext configureDeployment() { final ResourceConfig rc = new ErrorEntityWriterTestResourceConfig(); return ServletDeploymentContext.builder(rc) .initParam(ServletProperties.JAXRS_APPLICATION_CLASS, ErrorEntityWriterTestResourceConfig.class.getName()) .build(); } @Test public void formatsErrorsAsHtml() { try { target("/exception/html-exception") .request(MediaType.TEXT_HTML_TYPE) .get(String.class); failBecauseExceptionWasNotThrown(WebApplicationException.class); } catch (WebApplicationException e) { final Response response = e.getResponse(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getMediaType()).isEqualTo(MediaType.TEXT_HTML_TYPE); assertThat(response.readEntity(String.class)).isEqualTo("<!DOCTYPE html><html><body>BIFF</body></html>"); } } }
923835164ffe791afb2ea77fd017d0f472a50189
5,256
java
Java
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheEntryListenerExpiredEventsTest.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
218
2015-01-04T13:20:55.000Z
2022-03-28T05:28:55.000Z
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheEntryListenerExpiredEventsTest.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
175
2015-02-04T23:16:56.000Z
2022-03-28T18:34:24.000Z
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheEntryListenerExpiredEventsTest.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
93
2015-01-06T20:54:23.000Z
2022-03-31T08:09:00.000Z
32.85
115
0.683029
998,353
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.cache; import java.util.concurrent.atomic.AtomicInteger; import javax.cache.configuration.CacheEntryListenerConfiguration; import javax.cache.configuration.Factory; import javax.cache.configuration.MutableCacheEntryListenerConfiguration; import javax.cache.event.CacheEntryEvent; import javax.cache.event.CacheEntryExpiredListener; import javax.cache.event.CacheEntryListener; import javax.cache.expiry.Duration; import javax.cache.expiry.ModifiedExpiryPolicy; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.internal.util.lang.GridAbsPredicate; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * */ public class IgniteCacheEntryListenerExpiredEventsTest extends GridCommonAbstractTest { /** */ private static AtomicInteger evtCntr; /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGrid(0); } /** * @throws Exception If failed. */ @Test public void testExpiredEventAtomic() throws Exception { checkExpiredEvents(cacheConfiguration(PARTITIONED, ATOMIC)); } /** * @throws Exception If failed. */ @Test public void testExpiredEventTx() throws Exception { checkExpiredEvents(cacheConfiguration(PARTITIONED, TRANSACTIONAL)); } /** * @param ccfg Cache configuration. * @throws Exception If failed. */ private void checkExpiredEvents(CacheConfiguration<Object, Object> ccfg) throws Exception { IgniteCache<Object, Object> cache = ignite(0).createCache(ccfg); try { evtCntr = new AtomicInteger(); CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>( new ExpiredListenerFactory(), null, true, false ); cache.registerCacheEntryListener(lsnrCfg); IgniteCache<Object, Object> expiryCache = cache.withExpiryPolicy(new ModifiedExpiryPolicy(new Duration(MILLISECONDS, 500))); expiryCache.put(1, 1); for (int i = 0; i < 10; i++) cache.get(i); boolean wait = GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return evtCntr.get() > 0; } }, 5000); assertTrue(wait); U.sleep(100); assertEquals(1, evtCntr.get()); } finally { ignite(0).destroyCache(cache.getName()); } } /** * * @param cacheMode Cache mode. * @param atomicityMode Cache atomicity mode. * @return Cache configuration. */ private CacheConfiguration<Object, Object> cacheConfiguration( CacheMode cacheMode, CacheAtomicityMode atomicityMode) { CacheConfiguration<Object, Object> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME); ccfg.setAtomicityMode(atomicityMode); ccfg.setCacheMode(cacheMode); ccfg.setWriteSynchronizationMode(FULL_SYNC); if (cacheMode == PARTITIONED) ccfg.setBackups(1); return ccfg; } /** * */ private static class ExpiredListenerFactory implements Factory<CacheEntryListener<Object, Object>> { /** {@inheritDoc} */ @Override public CacheEntryListener<Object, Object> create() { return new ExpiredListener(); } } /** * */ private static class ExpiredListener implements CacheEntryExpiredListener<Object, Object> { /** {@inheritDoc} */ @Override public void onExpired(Iterable<CacheEntryEvent<?, ?>> evts) { for (CacheEntryEvent<?, ?> evt : evts) evtCntr.incrementAndGet(); } } }
9238366971b8f801a35a8cd974f6fe23e0dc1567
334
java
Java
springboot/springboot-web/src/main/java/com/jony/controller/HelloController.java
jiaoqiyuan/codeabbeyTests
d0b381c14ccda3f887ac963f92c5cf8075399fff
[ "Apache-2.0" ]
1
2019-08-10T04:39:11.000Z
2019-08-10T04:39:11.000Z
springboot/springboot-web/src/main/java/com/jony/controller/HelloController.java
jiaoqiyuan/codeabbeyTests
d0b381c14ccda3f887ac963f92c5cf8075399fff
[ "Apache-2.0" ]
2
2022-03-31T22:44:44.000Z
2022-03-31T22:44:44.000Z
springboot/springboot-web/src/main/java/com/jony/controller/HelloController.java
jiaoqiyuan/codeabbeyTests
d0b381c14ccda3f887ac963f92c5cf8075399fff
[ "Apache-2.0" ]
1
2019-08-05T05:08:17.000Z
2019-08-05T05:08:17.000Z
20.875
62
0.739521
998,354
package com.jony.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * RestController 表示不走视图了 */ @RestController public class HelloController { @RequestMapping("/hello") public String hello() { return "Hello World"; } }
923837474a00783aa5975e10c55de1412d435a72
11,372
java
Java
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/ParsedJob.java
dmgerman/hadoop
70c015914a8756c5440cd969d70dac04b8b6142b
[ "Apache-2.0" ]
null
null
null
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/ParsedJob.java
dmgerman/hadoop
70c015914a8756c5440cd969d70dac04b8b6142b
[ "Apache-2.0" ]
null
null
null
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/ParsedJob.java
dmgerman/hadoop
70c015914a8756c5440cd969d70dac04b8b6142b
[ "Apache-2.0" ]
null
null
null
16.52907
814
0.7879
998,355
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_comment comment|/** * */ end_comment begin_package DECL|package|org.apache.hadoop.tools.rumen package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|tools operator|. name|rumen package|; end_package begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapreduce operator|. name|JobACL import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|authorize operator|. name|AccessControlList import|; end_import begin_comment comment|/** * This is a wrapper class around {@link LoggedJob}. This provides also the * extra information about the job obtained from job history which is not * written to the JSON trace file. */ end_comment begin_class DECL|class|ParsedJob specifier|public class|class name|ParsedJob extends|extends name|LoggedJob block|{ DECL|field|LOG specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|ParsedJob operator|. name|class argument_list|) decl_stmt|; DECL|field|totalCountersMap specifier|private name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|totalCountersMap init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|Long argument_list|> argument_list|() decl_stmt|; DECL|field|mapCountersMap specifier|private name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|mapCountersMap init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|Long argument_list|> argument_list|() decl_stmt|; DECL|field|reduceCountersMap specifier|private name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|reduceCountersMap init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|Long argument_list|> argument_list|() decl_stmt|; DECL|field|jobConfPath specifier|private name|String name|jobConfPath decl_stmt|; DECL|field|jobAcls specifier|private name|Map argument_list|< name|JobACL argument_list|, name|AccessControlList argument_list|> name|jobAcls decl_stmt|; DECL|method|ParsedJob () name|ParsedJob parameter_list|() block|{ } DECL|method|ParsedJob (String jobID) name|ParsedJob parameter_list|( name|String name|jobID parameter_list|) block|{ name|super argument_list|() expr_stmt|; name|setJobID argument_list|( name|jobID argument_list|) expr_stmt|; block|} comment|/** Set the job total counters */ DECL|method|putTotalCounters (Map<String, Long> totalCounters) name|void name|putTotalCounters parameter_list|( name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|totalCounters parameter_list|) block|{ name|this operator|. name|totalCountersMap operator|= name|totalCounters expr_stmt|; block|} comment|/** * @return the job total counters */ DECL|method|obtainTotalCounters () specifier|public name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|obtainTotalCounters parameter_list|() block|{ return|return name|totalCountersMap return|; block|} comment|/** Set the job level map tasks' counters */ DECL|method|putMapCounters (Map<String, Long> mapCounters) name|void name|putMapCounters parameter_list|( name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|mapCounters parameter_list|) block|{ name|this operator|. name|mapCountersMap operator|= name|mapCounters expr_stmt|; block|} comment|/** * @return the job level map tasks' counters */ DECL|method|obtainMapCounters () specifier|public name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|obtainMapCounters parameter_list|() block|{ return|return name|mapCountersMap return|; block|} comment|/** Set the job level reduce tasks' counters */ DECL|method|putReduceCounters (Map<String, Long> reduceCounters) name|void name|putReduceCounters parameter_list|( name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|reduceCounters parameter_list|) block|{ name|this operator|. name|reduceCountersMap operator|= name|reduceCounters expr_stmt|; block|} comment|/** * @return the job level reduce tasks' counters */ DECL|method|obtainReduceCounters () specifier|public name|Map argument_list|< name|String argument_list|, name|Long argument_list|> name|obtainReduceCounters parameter_list|() block|{ return|return name|reduceCountersMap return|; block|} comment|/** Set the job conf path in staging dir on hdfs */ DECL|method|putJobConfPath (String confPath) name|void name|putJobConfPath parameter_list|( name|String name|confPath parameter_list|) block|{ name|jobConfPath operator|= name|confPath expr_stmt|; block|} comment|/** * @return the job conf path in staging dir on hdfs */ DECL|method|obtainJobConfpath () specifier|public name|String name|obtainJobConfpath parameter_list|() block|{ return|return name|jobConfPath return|; block|} comment|/** Set the job acls */ DECL|method|putJobAcls (Map<JobACL, AccessControlList> acls) name|void name|putJobAcls parameter_list|( name|Map argument_list|< name|JobACL argument_list|, name|AccessControlList argument_list|> name|acls parameter_list|) block|{ name|jobAcls operator|= name|acls expr_stmt|; block|} comment|/** * @return the job acls */ DECL|method|obtainJobAcls () specifier|public name|Map argument_list|< name|JobACL argument_list|, name|AccessControlList argument_list|> name|obtainJobAcls parameter_list|() block|{ return|return name|jobAcls return|; block|} comment|/** * @return the list of map tasks of this job */ DECL|method|obtainMapTasks () specifier|public name|List argument_list|< name|ParsedTask argument_list|> name|obtainMapTasks parameter_list|() block|{ name|List argument_list|< name|LoggedTask argument_list|> name|tasks init|= name|super operator|. name|getMapTasks argument_list|() decl_stmt|; return|return name|convertTasks argument_list|( name|tasks argument_list|) return|; block|} comment|/** * @return the list of reduce tasks of this job */ DECL|method|obtainReduceTasks () specifier|public name|List argument_list|< name|ParsedTask argument_list|> name|obtainReduceTasks parameter_list|() block|{ name|List argument_list|< name|LoggedTask argument_list|> name|tasks init|= name|super operator|. name|getReduceTasks argument_list|() decl_stmt|; return|return name|convertTasks argument_list|( name|tasks argument_list|) return|; block|} comment|/** * @return the list of other tasks of this job */ DECL|method|obtainOtherTasks () specifier|public name|List argument_list|< name|ParsedTask argument_list|> name|obtainOtherTasks parameter_list|() block|{ name|List argument_list|< name|LoggedTask argument_list|> name|tasks init|= name|super operator|. name|getOtherTasks argument_list|() decl_stmt|; return|return name|convertTasks argument_list|( name|tasks argument_list|) return|; block|} comment|/** As we know that this list of {@link LoggedTask} objects is actually a list * of {@link ParsedTask} objects, we go ahead and cast them. * @return the list of {@link ParsedTask} objects */ DECL|method|convertTasks (List<LoggedTask> tasks) specifier|private name|List argument_list|< name|ParsedTask argument_list|> name|convertTasks parameter_list|( name|List argument_list|< name|LoggedTask argument_list|> name|tasks parameter_list|) block|{ name|List argument_list|< name|ParsedTask argument_list|> name|result init|= operator|new name|ArrayList argument_list|< name|ParsedTask argument_list|> argument_list|() decl_stmt|; for|for control|( name|LoggedTask name|t range|: name|tasks control|) block|{ if|if condition|( name|t operator|instanceof name|ParsedTask condition|) block|{ name|result operator|. name|add argument_list|( operator|( name|ParsedTask operator|) name|t argument_list|) expr_stmt|; block|} else|else block|{ throw|throw operator|new name|RuntimeException argument_list|( literal|"Unexpected type of tasks in the list..." argument_list|) throw|; block|} block|} return|return name|result return|; block|} comment|/** Dump the extra info of ParsedJob */ DECL|method|dumpParsedJob () name|void name|dumpParsedJob parameter_list|() block|{ name|LOG operator|. name|info argument_list|( literal|"ParsedJob details:" operator|+ name|obtainTotalCounters argument_list|() operator|+ literal|";" operator|+ name|obtainMapCounters argument_list|() operator|+ literal|";" operator|+ name|obtainReduceCounters argument_list|() operator|+ literal|"\n" operator|+ name|obtainJobConfpath argument_list|() operator|+ literal|"\n" operator|+ name|obtainJobAcls argument_list|() operator|+ literal|";Q=" operator|+ operator|( name|getQueue argument_list|() operator|== literal|null condition|? literal|"null" else|: name|getQueue argument_list|() operator|. name|getValue argument_list|() operator|) argument_list|) expr_stmt|; name|List argument_list|< name|ParsedTask argument_list|> name|maps init|= name|obtainMapTasks argument_list|() decl_stmt|; for|for control|( name|ParsedTask name|task range|: name|maps control|) block|{ name|task operator|. name|dumpParsedTask argument_list|() expr_stmt|; block|} name|List argument_list|< name|ParsedTask argument_list|> name|reduces init|= name|obtainReduceTasks argument_list|() decl_stmt|; for|for control|( name|ParsedTask name|task range|: name|reduces control|) block|{ name|task operator|. name|dumpParsedTask argument_list|() expr_stmt|; block|} name|List argument_list|< name|ParsedTask argument_list|> name|others init|= name|obtainOtherTasks argument_list|() decl_stmt|; for|for control|( name|ParsedTask name|task range|: name|others control|) block|{ name|task operator|. name|dumpParsedTask argument_list|() expr_stmt|; block|} block|} block|} end_class end_unit
923837d548a6f85541ecb80ab687c4c6a123f3a1
1,925
java
Java
Lab03/SailBoat.java
CovertError/Learning_Java
56b4fd8711c8470fd5c30d3cee172de2b11c4d0f
[ "MIT" ]
null
null
null
Lab03/SailBoat.java
CovertError/Learning_Java
56b4fd8711c8470fd5c30d3cee172de2b11c4d0f
[ "MIT" ]
null
null
null
Lab03/SailBoat.java
CovertError/Learning_Java
56b4fd8711c8470fd5c30d3cee172de2b11c4d0f
[ "MIT" ]
null
null
null
25
110
0.606753
998,356
/** *Subclass that extends from superclass Boat *@authors Mostafa Elkattan - Javeria Malik - Omar Yassin *@version 1.3 */ public class SailBoat extends Boat { private int numSails; //defining the attribute /** *Default Constructor *Initializes the attribute */ public SailBoat() { numSails=1; } /** *Parameterized Constructor *Initializes the attribute color and length using Boat class *Initializes the attribute numSails using setNumSails mutator */ public SailBoat(String _color,int _length,int _numSails) { super.setColor(_color); //passing to Boat class super.setLength(_length); //passing to Boat class this.setNumSails(_numSails); //passing to mutator within this subclass } /** *Mutator *Tests the input parameter to see if number of Sails is within the range 1-4 @return True if within range @return False if outside range */ public boolean setNumSails(int _numSails) { if (_numSails>=1 && _numSails<=4) //if statement to check if parameter is within range { numSails=_numSails; //setting numSails return true; } else { System.out.println("Error: Number of sails can only be between 1 and 4, inclusively"); return false; } } /** *Accessor @return numSails */ public int getNumSails() { return numSails; } /** *Method @return price of the sail boat */ public double calcPrice() { return ((length*1000.00)+(numSails*2000)); } /** *Method @return a string in string format */ public String toString() { String priceStr=String.format("$ %,.2f",calcPrice()); return String.format("%1$s Number of Sails = %2$d Cost = %3$s",super.toString(),numSails,priceStr); } }
9238385b8b94e94035f7749a858e4725e0e10c67
2,650
java
Java
items-concurrent/src/main/java/com/bjsxt/base/multi006/lock020/UseManyCondition.java
andyChenHuaYing/scattered-items
33a5e2b3aec34831b8335475fc5dec661622c28b
[ "Apache-2.0" ]
8
2015-02-28T01:07:20.000Z
2017-12-17T07:43:30.000Z
items-concurrent/src/main/java/com/bjsxt/base/multi006/lock020/UseManyCondition.java
andyChenHuaYing/scattered-items
33a5e2b3aec34831b8335475fc5dec661622c28b
[ "Apache-2.0" ]
1
2020-11-07T02:17:39.000Z
2020-11-07T02:17:39.000Z
items-concurrent/src/main/java/com/bjsxt/base/multi006/lock020/UseManyCondition.java
andyChenHuaYing/scattered-items
33a5e2b3aec34831b8335475fc5dec661622c28b
[ "Apache-2.0" ]
5
2017-07-14T03:05:25.000Z
2018-09-19T01:50:15.000Z
19.776119
80
0.594717
998,357
package com.bjsxt.base.multi006.lock020; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class UseManyCondition { private ReentrantLock lock = new ReentrantLock(); private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); public void m1(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m1等待.."); c1.await(); System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m1继续.."); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m2(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m2等待.."); c1.await(); System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m2继续.."); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m3(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "进入方法m3等待.."); c2.await(); System.out.println("当前线程:" +Thread.currentThread().getName() + "方法m3继续.."); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m4(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒.."); c1.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void m5(){ try { lock.lock(); System.out.println("当前线程:" +Thread.currentThread().getName() + "唤醒.."); c2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) { final UseManyCondition umc = new UseManyCondition(); Thread t1 = new Thread(new Runnable() { @Override public void run() { umc.m1(); } },"t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { umc.m2(); } },"t2"); Thread t3 = new Thread(new Runnable() { @Override public void run() { umc.m3(); } },"t3"); Thread t4 = new Thread(new Runnable() { @Override public void run() { umc.m4(); } },"t4"); Thread t5 = new Thread(new Runnable() { @Override public void run() { umc.m5(); } },"t5"); t1.start(); // c1 t2.start(); // c1 t3.start(); // c2 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } t4.start(); // c1 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } t5.start(); // c2 } }