blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
6d48ffe1963f3b50df58083bbc2ffdb8088d9572
14e8601114178202e8469916f279a03543797585
/app-note/src/main/java/kr/co/myroute/note/NoteActivity.java
76bf1563fdd525c9592ae37a689452ad4be33308
[]
no_license
myroute/myroute
29fb43c51bc3fdeb508df77fc77c65d5e75600f1
f8c6caa37430aa5ccbd003513a94885d8d1b4db3
refs/heads/master
2020-04-10T11:57:00.107587
2018-12-09T09:56:46
2018-12-09T09:56:46
161,007,237
0
0
null
null
null
null
UTF-8
Java
false
false
267
java
package kr.co.myroute.note; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class NoteActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
280240c54992ba479a2299a8409a3002e2435445
b0330ec447372a925ebdfc0c1be842704e19e419
/src/service/UrbisPwikService.java
4d4122b97eda3d9e6f2fd549536d3e8ecb2f68ed
[]
no_license
krzychuka/Projekt
27ceeec30332c0ec255b2e6cc9ed997a26cf08e3
b1a008340716ece714562cd9e4984a4693e536ca
refs/heads/master
2021-01-21T19:35:56.625308
2015-02-25T21:58:00
2015-02-25T21:58:00
29,072,148
0
0
null
null
null
null
UTF-8
Java
false
false
964
java
package service; import java.util.List; import model.UrbisPwik; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import dao.UrbisPwikDao; @Service("urbisPwikService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class UrbisPwikService { @Autowired private UrbisPwikDao urbisPwikDao; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addUrbisPwik(UrbisPwik urbisPwik){ urbisPwikDao.addUrbisPwik(urbisPwik); } public List<UrbisPwik> urbisPwikList(){ return urbisPwikDao.urbisPwikList(); } public UrbisPwik getUrbisPwik(long urbisPwikId){ return urbisPwikDao.getUrbisPwik(urbisPwikId); } public void deleteUrbisPwik(UrbisPwik urbisPwik){ urbisPwikDao.deleteUrbisPwik(urbisPwik); } }
701e1f00499af435521ce719fa1837ba5b25f28e
5561531808622c188b6b27fcdf63ff34416d15b8
/src/main/java/com/concert/service/impl/AggregateServiceImpl.java
0df7e268c379c1454e95de01700b1cc90ec0a307
[ "Apache-2.0" ]
permissive
himanshuvirmani/concert
1f3c88ce12451245392e493d18f5fca560836d95
740b8dbb116e69965f52221ffeead699a4f5a4d1
refs/heads/master
2021-01-20T20:08:41.810897
2016-08-16T11:22:20
2016-08-16T11:22:20
65,223,928
0
0
null
null
null
null
UTF-8
Java
false
false
1,408
java
package com.concert.service.impl; import com.concert.domain.Aggregate; import com.concert.repository.AggregateRepository; import com.concert.service.AggregateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; @Component("aggregateService") @Transactional public class AggregateServiceImpl implements AggregateService { private final AggregateRepository cityRepository; /* @Autowired private HashCacheRedisRepository<Aggregate> valueCacheRedisRepository;*/ @Autowired public AggregateServiceImpl(AggregateRepository cityRepository) { this.cityRepository = cityRepository; } @Override public Aggregate getAggregateByExternalId(String externalId) { Assert.notNull(externalId, "Name must not be null"); // Aggregate city = valueCacheRedisRepository.multiGet("city:" + name + ":country:" + country, Aggregate.class); Aggregate city = cityRepository.findByExternalId(externalId); /* if (city != null) { valueCacheRedisRepository.multiPut("city:" + name + ":country:" + country, city); valueCacheRedisRepository.expire("city:" + name + ":country:" + country, 60, TimeUnit.SECONDS); }*/ return city; } }
44f1c62d1e66514853ce44bdf3583680a26b1c71
7d75dabad0ff3e3ad438c20a7eff8bb0c5855939
/national-agent-portal/src/main/java/com/pay/national/agent/portal/web/AppFeedBackController.java
9c1f86fe04021507514a94f9400a38508c1e0b0a
[]
no_license
AgentNational/national-agent
668b73c7025b500adaf202ea95f4cdb4c83c813f
a1ab41871d834a37fd90b2c326ff3df991a4c1c1
refs/heads/master
2021-09-10T05:36:25.151823
2018-03-21T05:34:09
2018-03-21T05:34:09
117,088,312
0
0
null
null
null
null
UTF-8
Java
false
false
5,813
java
package com.pay.national.agent.portal.web; import java.util.Date; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.pay.national.agent.common.persistence.Page; import com.pay.national.agent.model.entity.AppFeedback; import com.pay.national.agent.portal.service.common.AppFeedbackService; /** * @ClassName: AppFeedBackController * @Description:TODO(这里用一句话描述这个类的作用) * @author: xiaodi.fu * @date: 2017年9月11日 下午4:29:18 * */ @Controller @RequestMapping("/appFeedBack") public class AppFeedBackController { private Logger logger = LoggerFactory.getLogger(AppFeedBackController.class); @Resource private AppFeedbackService appFeedbackService; // //TODO SmsService接口,实现发送处理意见至用户邮箱,现阶段未定义相关接口,需后续加上。 // @Resource // private SmsService smsService; // // //TODO MessagePushFacade接口,实现推送处理意见至app端,现阶段未定义相关推送接口,需后续加上。 // @Resource // private MessagePushFacade messagePushFacade; // /** * init反馈信息查询页面 * @Description 一句话描述方法的用法 * @return * @see 需要参考的类或方法 */ @RequestMapping("/toFeedbackQuery.action") public ModelAndView toFeedbackQuery() { ModelAndView model = new ModelAndView(); model.setViewName("/feedBack/feedbackQuery"); return model; } /** * 查询消息主体列表 * @Description 一句话描述方法用法 * @return * @see 需要参考的类或方法 */ @RequestMapping("/feedbackQuery.action") public ModelAndView feedbackQuery(@RequestParam Map<String, Object> queryParams) { logger.info("feedbackQuery params : {}",queryParams); ModelAndView model = new ModelAndView(); int currentPage = queryParams.get("currentPage") == null ? 1 : Integer.parseInt(queryParams.get("currentPage").toString()); String source = queryParams.get("appClientType") == null ? null: queryParams.get("appClientType").toString().toUpperCase(); queryParams.put("source", source); Page<Map<String,Object>> page = new Page<Map<String,Object>>(); page.setCurrentPage(currentPage); // 分页查询 List<Map<String,Object>> feedbackList = this.appFeedbackService.findAllFeedback(page, queryParams); model.addObject("feedbackList", feedbackList); model.addObject("page", page); model.setViewName("/feedBack/feedbackQueryResult"); return model; } /** * * @Description 查询反馈详情 * @param id * @return * @see 需要参考的类或方法 */ @RequestMapping("/feedbackDetail.action") public ModelAndView feedbackDetail(@RequestParam("id") String id) { ModelAndView model = new ModelAndView(); AppFeedback appFeedback = this.appFeedbackService.findAppFeedbackById(id); model.addObject("feedback", appFeedback); model.setViewName("/feedBack/feedbackDetail"); return model; } /** * * @Description 处理反馈跳转 * @param id * @return * @see 需要参考的类或方法 */ @RequestMapping("/toFeedbackModify.action") public ModelAndView toFeedbackModify(@RequestParam("id") String id) { ModelAndView model = new ModelAndView(); AppFeedback appFeedback = appFeedbackService.findAppFeedbackById(id); model.addObject("feedback", appFeedback); model.setViewName("/feedBack/feedbackEdit"); return model; } /** * * @Description 处理反馈 * @param id * @return * @see 需要参考的类或方法 */ @RequestMapping("/feedbackModify.action") public ModelAndView feedbackModify(@RequestParam("feedId") String feedId,@RequestParam("remark") String remark,@RequestParam("type") String[] type, HttpServletRequest request) { ModelAndView model = new ModelAndView(); /*测试时需要注掉,否则报nullpointexception 因为操作员需要集成boss之后才能获取,*/ // Authorization auth = (Authorization) request.getSession().getAttribute(Constants.SESSION_AUTH); // String userName = auth.getUserName(); AppFeedback appFeedback = appFeedbackService.findAppFeedbackById(feedId); /*处理checkbox选择的返回类型*/ for(String s : type){ dealReturnType(s ,appFeedback ,remark); } appFeedback.setReturnType(appFeedback.arrayToString(type)); appFeedback.setRemark(remark); appFeedback.setOperatorTime(new Date()); appFeedback.setStatus("SUCCESS"); // appFeedback.setOperator(userName);//测试时需要注掉。 appFeedbackService.modify(appFeedback); model.setViewName("/feedBack/feedbackQuery"); return model; } /** * 处理意见返回 * @Description 一句话描述方法的用法 * @see 需要参考的类或方法 */ public void dealReturnType(String s,AppFeedback appFeedback ,String remark){ //判断是否需要发送短信 /*if(s.equals("sms")){ boolean flag = smsService.sendSms(appFeedback.getPhone(), remark ,true); if(flag){ appFeedback.setIsRead("Y");//修改发送信息状态 } }else if(s.equals("message")){ Map<String, String> extras = new HashMap<String, String>(); extras.put("type", "MESSAGE"); boolean flag = messagePushFacade.push(appFeedback.getPhone(), "N", "反馈处理", appFeedback.getRemark(), true,extras); if(!flag) { logger.error("messagePushFacade 推送反馈处理失败!"); } }*/ } }
f48750743f1123e33ea98db711133095efe46ef7
5cda26db8e88035e8407b8a414ae1ba9fc7d2b37
/Saada1.7/java/sources/saadadb/sqltable/Table_Tap_Schema_Tables.java
fd6c059fdfa6f41ef6413330e3bfdb797afcad48
[]
no_license
lmichel/saada
585078a0c928f6fbd1027f0ff42da258ce0567f0
0149e95a23e0e154e24cbcf154016c66751fdb72
refs/heads/master
2021-07-22T11:19:17.711091
2021-04-15T07:47:09
2021-04-15T07:47:09
32,446,998
0
0
null
null
null
null
UTF-8
Java
false
false
5,325
java
package saadadb.sqltable; import java.sql.ResultSet; import java.util.ArrayList; import java.util.LinkedHashMap; import saadadb.database.Database; import saadadb.database.spooler.Spooler; import saadadb.exceptions.AbortException; import saadadb.exceptions.SaadaException; import saadadb.meta.AttributeHandler; import saadadb.util.Messenger; /** * @author laurent * @version $Id@ * */ public class Table_Tap_Schema_Tables extends SQLTable { public static final LinkedHashMap<String, AttributeHandler> attMap; public static final String tableName = "tables"; static { attMap = new LinkedHashMap<String, AttributeHandler>(); AttributeHandler ah; ah = new AttributeHandler(); ah.setNameattr("schema_name"); ah.setNameattr("schema_name"); ah.setType("String"); ah.setComment("the schema name from TAP_SCHEMA.schemas"); attMap.put("schema_name", ah); ah = new AttributeHandler(); ah.setNameattr("table_name"); ah.setNameattr("table_name"); ah.setType("String"); ah.setComment("table name as it should be used in queries"); attMap.put("table_name", ah); ah = new AttributeHandler(); ah.setNameattr("table_type"); ah.setNameattr("table_type"); ah.setType("String"); ah.setComment("one of: table, view"); attMap.put("table_type", ah); ah = new AttributeHandler(); ah.setNameattr("description"); ah.setNameattr("description"); ah.setType("String"); ah.setComment("brief description of table"); attMap.put("description", ah); ah = new AttributeHandler(); ah.setNameattr("utype"); ah.setNameattr("utype"); ah.setType("String"); ah.setComment("UTYPE if table corresponds to a data model"); attMap.put("utype", ah); } /** * @throws SaadaException */ public static void createTable() throws SaadaException { String sql = ""; for (AttributeHandler ah: attMap.values() ) { if( sql.length() > 0 ) sql += ", "; sql += ah.getNameattr() + " " + Database.getWrapper().getSQLTypeFromJava(ah.getType()); } Messenger.printMsg(Messenger.TRACE, "Create table " + tableName); SQLTable.createTable(tableName, sql, "table_name", false); } /** * @throws AbortException */ public static void dropTable() throws AbortException { Messenger.printMsg(Messenger.TRACE, "Drop table " + tableName); SQLTable.dropTable(tableName); } /** * @param schema * @param table * @param description * @param utype * @throws AbortException */ public static void addTable(String schema, String table, String description, String utype) throws AbortException { String fn = schema + "." + table; Messenger.printMsg(Messenger.TRACE, "Add table " + table + " to " + tableName); SQLTable.addQueryToTransaction("INSERT INTO " + tableName + " VALUES (?, ?, ?, ?, ?)" // , new Object[]{schema, table, "table",description, utype}); , new Object[]{schema, fn, "table",description, utype}); } /** * @param schemaName * @throws AbortException */ public static void dropPublishedSchema(String schemaName) throws Exception { Messenger.printMsg(Messenger.TRACE, "Drop tables of schema " + schemaName); SQLQuery sq = new SQLQuery(); ArrayList<String> tempo = new ArrayList<String>(); ResultSet rs = sq.run("SELECT table_name FROM " + tableName + " WHERE schema_name = '" + schemaName + "'"); while( rs.next() ) { tempo.add(rs.getString(1)); } sq.close(); for( String s: tempo) { Table_Tap_Schema_Tables.dropPublishedTable(s); } SQLTable.addQueryToTransaction("DELETE FROM " + tableName + " WHERE schema_name = '" + schemaName + "'"); } /** * @param schemaName * @param tableName * @throws AbortException */ public static void dropPublishedTable(String schemaName, String table) throws Exception { String fn = schemaName + "." + table; Messenger.printMsg(Messenger.TRACE, "Drop published table " + schemaName + "." + table); Table_Tap_Schema_Keys.dropPublishedTable(schemaName, table); Table_Tap_Schema_Columns.dropPublishedTable(schemaName, table); //SQLTable.addQueryToTransaction("DELETE FROM " + tableName + " WHERE schema_name = '" + schemaName + "' AND table_name = '" + table + "'"); SQLTable.addQueryToTransaction("DELETE FROM " + tableName + " WHERE schema_name = '" + schemaName + "' AND table_name = '" + fn + "'"); } /** * @param stable: schema.table * @throws Exception */ public static void dropPublishedTable(String stable) throws Exception { Messenger.printMsg(Messenger.TRACE, "Drop published table " + stable); Table_Tap_Schema_Keys.dropPublishedTable(stable); Table_Tap_Schema_Columns.dropPublishedTable(stable); //SQLTable.addQueryToTransaction("DELETE FROM " + tableName + " WHERE schema_name = '" + schemaName + "' AND table_name = '" + table + "'"); SQLTable.addQueryToTransaction("DELETE FROM " + tableName + " WHERE table_name = '" + stable + "'"); } /** * Returns true if bale is already referenced in tap_schema_tables * @param table * @return * @throws Exception */ public static boolean knowsTable(String schemaName, String table) throws Exception { String fn = schemaName + "." + table; SQLQuery sq = new SQLQuery(); boolean retour = false; ResultSet rs = sq.run("SELECT table_name FROM " + tableName + " WHERE table_name = '" + fn + "' LIMIT 1"); while (rs.next()) { retour = true; break; } sq.close(); return retour; } }
[ "laurent.mistahl@ff1e8092-12d3-63eb-d73d-7507d0dcd924" ]
laurent.mistahl@ff1e8092-12d3-63eb-d73d-7507d0dcd924
4745305b1b32a9495de28959802cbf2ad5f509c1
9e43383d90a509944a0c46e1abebfbf45bbf44e6
/TESTER/GooglePlace/src/hung/vo/hung/vo/GooglePlaceActivity.java
7712c0e427629bc64fac840fa44736745d0fc4e2
[]
no_license
qx/mygradle
cf47aa3ddccb235ac62878c5a50348f1000c3879
a0fa9edf693fe1792f7aeafa2692ac595a3f5212
refs/heads/master
2016-09-05T22:07:23.600725
2014-07-24T02:50:25
2014-07-24T02:50:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,896
java
package hung.vo.hung.vo; import hung.vo.PlaceRequest; import hung.vo.R; import hung.vo.model.Place; import hung.vo.model.PlacesList; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class GooglePlaceActivity extends Activity { /** Called when the activity is first created. */ Button btn1; TextView txt1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.main); btn1 = (Button)findViewById(R.id.button1); txt1 = (TextView)findViewById(R.id.textView1); btn1.setOnClickListener(l); } private class SearchSrv extends AsyncTask<Void, Void, PlacesList>{ @Override protected PlacesList doInBackground(Void... params) { // TODO Auto-generated method stub PlacesList pl = null; try { pl = new PlaceRequest().performSearch(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return pl; } @Override protected void onPostExecute(PlacesList result) { // TODO Auto-generated method stub String text = "Result \n"; if (result!=null){ for(Place place: result.results){ text = text + place.name +"\n"; } txt1.setText(text); } setProgressBarIndeterminateVisibility(false); } } View.OnClickListener l = new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SearchSrv srv = new SearchSrv(); setProgressBarIndeterminateVisibility(true); srv.execute(); } }; }
6cb7b77f81bb0b1da4f961155e40980391fbb748
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/ant_cluster/9655/src_0.java
9bfe997dea66ca07043dd8af2129e56b0299c853
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
21,384
java
/* * Copyright 2000-2004 The Apache Software Foundation * * 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.apache.tools.ant.taskdefs; import java.io.File; import java.util.Vector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.condition.Os; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.selectors.AndSelector; import org.apache.tools.ant.types.selectors.ContainsRegexpSelector; import org.apache.tools.ant.types.selectors.ContainsSelector; import org.apache.tools.ant.types.selectors.DateSelector; import org.apache.tools.ant.types.selectors.DependSelector; import org.apache.tools.ant.types.selectors.DepthSelector; import org.apache.tools.ant.types.selectors.ExtendSelector; import org.apache.tools.ant.types.selectors.FilenameSelector; import org.apache.tools.ant.types.selectors.MajoritySelector; import org.apache.tools.ant.types.selectors.NoneSelector; import org.apache.tools.ant.types.selectors.NotSelector; import org.apache.tools.ant.types.selectors.OrSelector; import org.apache.tools.ant.types.selectors.PresentSelector; import org.apache.tools.ant.types.selectors.SelectSelector; import org.apache.tools.ant.types.selectors.SizeSelector; import org.apache.tools.ant.types.selectors.FileSelector; import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector; /** * Deletes a file or directory, or set of files defined by a fileset. * The original delete task would delete a file, or a set of files * using the include/exclude syntax. The deltree task would delete a * directory tree. This task combines the functionality of these two * originally distinct tasks. * <p>Currently Delete extends MatchingTask. This is intend <i>only</i> * to provide backwards compatibility for a release. The future position * is to use nested filesets exclusively.</p> * * @since Ant 1.2 * * @ant.task category="filesystem" */ public class Delete extends MatchingTask { private static final int DELETE_RETRY_SLEEP_MILLIS = 10; protected File file = null; protected File dir = null; protected Vector filesets = new Vector(); protected boolean usedMatchingTask = false; // by default, remove matching empty dirs protected boolean includeEmpty = false; private int verbosity = Project.MSG_VERBOSE; private boolean quiet = false; private boolean failonerror = true; /** * Set the name of a single file to be removed. * * @param file the file to be deleted */ public void setFile(File file) { this.file = file; } /** * Set the directory from which files are to be deleted * * @param dir the directory path. */ public void setDir(File dir) { this.dir = dir; } /** * If true, list all names of deleted files. * * @param verbose "true" or "on" */ public void setVerbose(boolean verbose) { if (verbose) { this.verbosity = Project.MSG_INFO; } else { this.verbosity = Project.MSG_VERBOSE; } } /** * If true and the file does not exist, do not display a diagnostic * message or modify the exit status to reflect an error. * This means that if a file or directory cannot be deleted, * then no error is reported. This setting emulates the * -f option to the Unix &quot;rm&quot; command. * Default is false meaning things are &quot;noisy&quot; * @param quiet "true" or "on" */ public void setQuiet(boolean quiet) { this.quiet = quiet; if (quiet) { this.failonerror = false; } } /** * If false, note errors but continue. * * @param failonerror true or false */ public void setFailOnError(boolean failonerror) { this.failonerror = failonerror; } /** * If true, delete empty directories. * @param includeEmpty if true delete empty directories (only * for filesets). Default is false. */ public void setIncludeEmptyDirs(boolean includeEmpty) { this.includeEmpty = includeEmpty; } /** * Adds a set of files to be deleted. * @param set the set of files to be deleted */ public void addFileset(FileSet set) { filesets.addElement(set); } /** * add a name entry on the include list * @return a NameEntry object to be configured */ public PatternSet.NameEntry createInclude() { usedMatchingTask = true; return super.createInclude(); } /** * add a name entry on the include files list * @return an NameEntry object to be configured */ public PatternSet.NameEntry createIncludesFile() { usedMatchingTask = true; return super.createIncludesFile(); } /** * add a name entry on the exclude list * @return an NameEntry object to be configured */ public PatternSet.NameEntry createExclude() { usedMatchingTask = true; return super.createExclude(); } /** * add a name entry on the include files list * @return an NameEntry object to be configured */ public PatternSet.NameEntry createExcludesFile() { usedMatchingTask = true; return super.createExcludesFile(); } /** * add a set of patterns * @return PatternSet object to be configured */ public PatternSet createPatternSet() { usedMatchingTask = true; return super.createPatternSet(); } /** * Sets the set of include patterns. Patterns may be separated by a comma * or a space. * * @param includes the string containing the include patterns */ public void setIncludes(String includes) { usedMatchingTask = true; super.setIncludes(includes); } /** * Sets the set of exclude patterns. Patterns may be separated by a comma * or a space. * * @param excludes the string containing the exclude patterns */ public void setExcludes(String excludes) { usedMatchingTask = true; super.setExcludes(excludes); } /** * Sets whether default exclusions should be used or not. * * @param useDefaultExcludes "true"|"on"|"yes" when default exclusions * should be used, "false"|"off"|"no" when they * shouldn't be used. */ public void setDefaultexcludes(boolean useDefaultExcludes) { usedMatchingTask = true; super.setDefaultexcludes(useDefaultExcludes); } /** * Sets the name of the file containing the includes patterns. * * @param includesfile A string containing the filename to fetch * the include patterns from. */ public void setIncludesfile(File includesfile) { usedMatchingTask = true; super.setIncludesfile(includesfile); } /** * Sets the name of the file containing the includes patterns. * * @param excludesfile A string containing the filename to fetch * the include patterns from. */ public void setExcludesfile(File excludesfile) { usedMatchingTask = true; super.setExcludesfile(excludesfile); } /** * Sets case sensitivity of the file system * * @param isCaseSensitive "true"|"on"|"yes" if file system is case * sensitive, "false"|"off"|"no" when not. */ public void setCaseSensitive(boolean isCaseSensitive) { usedMatchingTask = true; super.setCaseSensitive(isCaseSensitive); } /** * Sets whether or not symbolic links should be followed. * * @param followSymlinks whether or not symbolic links should be followed */ public void setFollowSymlinks(boolean followSymlinks) { usedMatchingTask = true; super.setFollowSymlinks(followSymlinks); } /** * add a "Select" selector entry on the selector list * @param selector the selector to be added */ public void addSelector(SelectSelector selector) { usedMatchingTask = true; super.addSelector(selector); } /** * add an "And" selector entry on the selector list * @param selector the selector to be added */ public void addAnd(AndSelector selector) { usedMatchingTask = true; super.addAnd(selector); } /** * add an "Or" selector entry on the selector list * @param selector the selector to be added */ public void addOr(OrSelector selector) { usedMatchingTask = true; super.addOr(selector); } /** * add a "Not" selector entry on the selector list * @param selector the selector to be added */ public void addNot(NotSelector selector) { usedMatchingTask = true; super.addNot(selector); } /** * add a "None" selector entry on the selector list * @param selector the selector to be added */ public void addNone(NoneSelector selector) { usedMatchingTask = true; super.addNone(selector); } /** * add a majority selector entry on the selector list * @param selector the selector to be added */ public void addMajority(MajoritySelector selector) { usedMatchingTask = true; super.addMajority(selector); } /** * add a selector date entry on the selector list * @param selector the selector to be added */ public void addDate(DateSelector selector) { usedMatchingTask = true; super.addDate(selector); } /** * add a selector size entry on the selector list * @param selector the selector to be added */ public void addSize(SizeSelector selector) { usedMatchingTask = true; super.addSize(selector); } /** * add a selector filename entry on the selector list * @param selector the selector to be added */ public void addFilename(FilenameSelector selector) { usedMatchingTask = true; super.addFilename(selector); } /** * add an extended selector entry on the selector list * @param selector the selector to be added */ public void addCustom(ExtendSelector selector) { usedMatchingTask = true; super.addCustom(selector); } /** * add a contains selector entry on the selector list * @param selector the selector to be added */ public void addContains(ContainsSelector selector) { usedMatchingTask = true; super.addContains(selector); } /** * add a present selector entry on the selector list * @param selector the selector to be added */ public void addPresent(PresentSelector selector) { usedMatchingTask = true; super.addPresent(selector); } /** * add a depth selector entry on the selector list * @param selector the selector to be added */ public void addDepth(DepthSelector selector) { usedMatchingTask = true; super.addDepth(selector); } /** * add a depends selector entry on the selector list * @param selector the selector to be added */ public void addDepend(DependSelector selector) { usedMatchingTask = true; super.addDepend(selector); } /** * add a regular expression selector entry on the selector list * @param selector the selector to be added */ public void addContainsRegexp(ContainsRegexpSelector selector) { usedMatchingTask = true; super.addContainsRegexp(selector); } /** * add the modified selector * @param selector the selector to add * @since ant 1.6 */ public void addModified(ModifiedSelector selector) { usedMatchingTask = true; super.addModified(selector); } /** * add an arbitrary selector * @param selector the selector to be added * @since Ant 1.6 */ public void add(FileSelector selector) { usedMatchingTask = true; super.add(selector); } /** * Delete the file(s). * @exception BuildException if an error occurs */ public void execute() throws BuildException { if (usedMatchingTask) { log("DEPRECATED - Use of the implicit FileSet is deprecated. " + "Use a nested fileset element instead."); } if (file == null && dir == null && filesets.size() == 0) { throw new BuildException("At least one of the file or dir " + "attributes, or a fileset element, " + "must be set."); } if (quiet && failonerror) { throw new BuildException("quiet and failonerror cannot both be " + "set to true", getLocation()); } // delete the single file if (file != null) { if (file.exists()) { if (file.isDirectory()) { log("Directory " + file.getAbsolutePath() + " cannot be removed using the file attribute. " + "Use dir instead."); } else { log("Deleting: " + file.getAbsolutePath()); if (!delete(file)) { String message = "Unable to delete file " + file.getAbsolutePath(); if (failonerror) { throw new BuildException(message); } else { log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_WARN); } } } } else { log("Could not find file " + file.getAbsolutePath() + " to delete.", Project.MSG_VERBOSE); } } // delete the directory if (dir != null && dir.exists() && dir.isDirectory() && !usedMatchingTask) { /* If verbosity is MSG_VERBOSE, that mean we are doing regular logging (backwards as that sounds). In that case, we want to print one message about deleting the top of the directory tree. Otherwise, the removeDir method will handle messages for _all_ directories. */ if (verbosity == Project.MSG_VERBOSE) { log("Deleting directory " + dir.getAbsolutePath()); } removeDir(dir); } // delete the files in the filesets for (int i = 0; i < filesets.size(); i++) { FileSet fs = (FileSet) filesets.elementAt(i); try { DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] files = ds.getIncludedFiles(); String[] dirs = ds.getIncludedDirectories(); removeFiles(fs.getDir(getProject()), files, dirs); } catch (BuildException be) { // directory doesn't exist or is not readable if (failonerror) { throw be; } else { log(be.getMessage(), quiet ? Project.MSG_VERBOSE : Project.MSG_WARN); } } } // delete the files from the default fileset if (usedMatchingTask && dir != null) { try { DirectoryScanner ds = super.getDirectoryScanner(dir); String[] files = ds.getIncludedFiles(); String[] dirs = ds.getIncludedDirectories(); removeFiles(dir, files, dirs); } catch (BuildException be) { // directory doesn't exist or is not readable if (failonerror) { throw be; } else { log(be.getMessage(), quiet ? Project.MSG_VERBOSE : Project.MSG_WARN); } } } } //************************************************************************ // protected and private methods //************************************************************************ /** * Accommodate Windows bug encountered in both Sun and IBM JDKs. * Others possible. If the delete does not work, call System.gc(), * wait a little and try again. */ private boolean delete(File f) { if (!f.delete()) { if (Os.isFamily("windows")) { System.gc(); } try { Thread.sleep(DELETE_RETRY_SLEEP_MILLIS); return f.delete(); } catch (InterruptedException ex) { return f.delete(); } } return true; } /** * Delete a directory * * @param d the directory to delete */ protected void removeDir(File d) { String[] list = d.list(); if (list == null) { list = new String[0]; } for (int i = 0; i < list.length; i++) { String s = list[i]; File f = new File(d, s); if (f.isDirectory()) { removeDir(f); } else { log("Deleting " + f.getAbsolutePath(), verbosity); if (!delete(f)) { String message = "Unable to delete file " + f.getAbsolutePath(); if (failonerror) { throw new BuildException(message); } else { log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_WARN); } } } } log("Deleting directory " + d.getAbsolutePath(), verbosity); if (!delete(d)) { String message = "Unable to delete directory " + dir.getAbsolutePath(); if (failonerror) { throw new BuildException(message); } else { log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_WARN); } } } /** * remove an array of files in a directory, and a list of subdirectories * which will only be deleted if 'includeEmpty' is true * @param d directory to work from * @param files array of files to delete; can be of zero length * @param dirs array of directories to delete; can of zero length */ protected void removeFiles(File d, String[] files, String[] dirs) { if (files.length > 0) { log("Deleting " + files.length + " files from " + d.getAbsolutePath()); for (int j = 0; j < files.length; j++) { File f = new File(d, files[j]); log("Deleting " + f.getAbsolutePath(), verbosity); if (!delete(f)) { String message = "Unable to delete file " + f.getAbsolutePath(); if (failonerror) { throw new BuildException(message); } else { log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_WARN); } } } } if (dirs.length > 0 && includeEmpty) { int dirCount = 0; for (int j = dirs.length - 1; j >= 0; j--) { File dir = new File(d, dirs[j]); String[] dirFiles = dir.list(); if (dirFiles == null || dirFiles.length == 0) { log("Deleting " + dir.getAbsolutePath(), verbosity); if (!delete(dir)) { String message = "Unable to delete directory " + dir.getAbsolutePath(); if (failonerror) { throw new BuildException(message); } else { log(message, quiet ? Project.MSG_VERBOSE : Project.MSG_WARN); } } else { dirCount++; } } } if (dirCount > 0) { log("Deleted " + dirCount + " director" + (dirCount == 1 ? "y" : "ies") + " from " + d.getAbsolutePath()); } } } }
1e0a569cf79adea2309595c0b417e0f24f6125f7
e9c163a9fc08fb64a7350f33e1f822fd6fad2404
/code/flink/master/code/src/main/java/io/boontadata/flink1/BoundedOutOfOrdernessGenerator.java
a967054f8224d706b3dd28e2ec7f20657aea542f
[ "MIT" ]
permissive
dmgactive/boontadata-streams
1777f90f8d028232bc36f5e2289b52cd3654bfd9
f83a2f0f7003d67a7c2ba455c497ecb61030f301
refs/heads/master
2020-03-31T04:13:26.339080
2017-06-12T08:30:54
2017-06-12T08:30:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,489
java
package io.boontadata.flink1; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.api.common.functions.ReduceFunction; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple; import org.apache.flink.api.java.tuple.Tuple5; import org.apache.flink.api.java.tuple.Tuple6; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks; import org.apache.flink.streaming.api.functions.sink.SinkFunction; import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction; import org.apache.flink.streaming.api.functions.windowing.WindowFunction; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.Window; import org.apache.flink.util.Collector; import org.apache.flink.streaming.api.watermark.Watermark; import static java.util.concurrent.TimeUnit.MILLISECONDS; // cf https://ci.apache.org/projects/flink/flink-docs-release-1.1/apis/streaming/event_timestamps_watermarks.html /** * This generator generates watermarks assuming that elements come out of order to a certain degree only. * The latest elements for a certain timestamp t will arrive at most n milliseconds after the earliest * elements for timestamp t. */ public class BoundedOutOfOrdernessGenerator implements AssignerWithPeriodicWatermarks<Tuple6<String, String, Long, String, Long, Double>> { private final long maxOutOfOrderness = 1_000L; // 1 second private final long maxProcessingTimeLag = 6_000L; // 6 seconds private long currentMaxTimestamp = 0; @Override public long extractTimestamp(Tuple6<String, String, Long, String, Long, Double> element, long previousElementTimestamp) { long timestamp = element.f2; // get processing timestamp from current event currentMaxTimestamp = Math.max(timestamp, currentMaxTimestamp); return timestamp; } @Override public Watermark getCurrentWatermark() { // return the watermark as current highest timestamp minus the out-of-orderness bound // or current processing time - maxProcessingTimeLag if it's higher (case of the last events) return new Watermark(Math.max(currentMaxTimestamp - maxOutOfOrderness, System.currentTimeMillis() - maxProcessingTimeLag)); } }
f6e46ad96db37ff1a84bb7774c1f83416a1b3f53
ef0c1514e9af6de3ba4a20e0d01de7cc3a915188
/sdk/connectedvmware/azure-resourcemanager-connectedvmware/src/main/java/com/azure/resourcemanager/connectedvmware/fluent/models/GuestAgentInner.java
3d9b35d9e49a41951b1760421703a80d2a72d4b9
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
Azure/azure-sdk-for-java
0902d584b42d3654b4ce65b1dad8409f18ddf4bc
789bdc6c065dc44ce9b8b630e2f2e5896b2a7616
refs/heads/main
2023-09-04T09:36:35.821969
2023-09-02T01:53:56
2023-09-02T01:53:56
2,928,948
2,027
2,084
MIT
2023-09-14T21:37:15
2011-12-06T23:33:56
Java
UTF-8
Java
false
false
6,065
java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.connectedvmware.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.ProxyResource; import com.azure.core.management.SystemData; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.connectedvmware.models.GuestCredential; import com.azure.resourcemanager.connectedvmware.models.HttpProxyConfiguration; import com.azure.resourcemanager.connectedvmware.models.ProvisioningAction; import com.azure.resourcemanager.connectedvmware.models.ResourceStatus; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Defines the GuestAgent. */ @Fluent public final class GuestAgentInner extends ProxyResource { /* * Resource properties. */ @JsonProperty(value = "properties", required = true) private GuestAgentProperties innerProperties = new GuestAgentProperties(); /* * The system data. */ @JsonProperty(value = "systemData", access = JsonProperty.Access.WRITE_ONLY) private SystemData systemData; /** * Get the innerProperties property: Resource properties. * * @return the innerProperties value. */ private GuestAgentProperties innerProperties() { return this.innerProperties; } /** * Get the systemData property: The system data. * * @return the systemData value. */ public SystemData systemData() { return this.systemData; } /** * Get the uuid property: Gets or sets a unique identifier for this resource. * * @return the uuid value. */ public String uuid() { return this.innerProperties() == null ? null : this.innerProperties().uuid(); } /** * Get the credentials property: Username / Password Credentials to provision guest agent. * * @return the credentials value. */ public GuestCredential credentials() { return this.innerProperties() == null ? null : this.innerProperties().credentials(); } /** * Set the credentials property: Username / Password Credentials to provision guest agent. * * @param credentials the credentials value to set. * @return the GuestAgentInner object itself. */ public GuestAgentInner withCredentials(GuestCredential credentials) { if (this.innerProperties() == null) { this.innerProperties = new GuestAgentProperties(); } this.innerProperties().withCredentials(credentials); return this; } /** * Get the httpProxyConfig property: HTTP Proxy configuration for the VM. * * @return the httpProxyConfig value. */ public HttpProxyConfiguration httpProxyConfig() { return this.innerProperties() == null ? null : this.innerProperties().httpProxyConfig(); } /** * Set the httpProxyConfig property: HTTP Proxy configuration for the VM. * * @param httpProxyConfig the httpProxyConfig value to set. * @return the GuestAgentInner object itself. */ public GuestAgentInner withHttpProxyConfig(HttpProxyConfiguration httpProxyConfig) { if (this.innerProperties() == null) { this.innerProperties = new GuestAgentProperties(); } this.innerProperties().withHttpProxyConfig(httpProxyConfig); return this; } /** * Get the provisioningAction property: Gets or sets the guest agent provisioning action. * * @return the provisioningAction value. */ public ProvisioningAction provisioningAction() { return this.innerProperties() == null ? null : this.innerProperties().provisioningAction(); } /** * Set the provisioningAction property: Gets or sets the guest agent provisioning action. * * @param provisioningAction the provisioningAction value to set. * @return the GuestAgentInner object itself. */ public GuestAgentInner withProvisioningAction(ProvisioningAction provisioningAction) { if (this.innerProperties() == null) { this.innerProperties = new GuestAgentProperties(); } this.innerProperties().withProvisioningAction(provisioningAction); return this; } /** * Get the status property: Gets or sets the guest agent status. * * @return the status value. */ public String status() { return this.innerProperties() == null ? null : this.innerProperties().status(); } /** * Get the customResourceName property: Gets the name of the corresponding resource in Kubernetes. * * @return the customResourceName value. */ public String customResourceName() { return this.innerProperties() == null ? null : this.innerProperties().customResourceName(); } /** * Get the statuses property: The resource status information. * * @return the statuses value. */ public List<ResourceStatus> statuses() { return this.innerProperties() == null ? null : this.innerProperties().statuses(); } /** * Get the provisioningState property: Gets or sets the provisioning state. * * @return the provisioningState value. */ public String provisioningState() { return this.innerProperties() == null ? null : this.innerProperties().provisioningState(); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (innerProperties() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException("Missing required property innerProperties in model GuestAgentInner")); } else { innerProperties().validate(); } } private static final ClientLogger LOGGER = new ClientLogger(GuestAgentInner.class); }
b53ab6dc7f918f57ce731c05d49e49e6a365de8d
469c29f150b9d64f226bcc624a24399fecb04e44
/15-2/src/Demo.java
89c1a1bd397512023268efd54aa09d9d1eaa087a
[]
no_license
Zooeeee/-Java-
4e3822e69b82c7925447fabad197a84c206a462e
9e6f8d111b21fc4c10e6bb00a204449ed5e73006
refs/heads/master
2020-03-28T18:14:44.574346
2018-12-08T15:36:00
2018-12-08T15:36:00
148,864,534
0
0
null
null
null
null
GB18030
Java
false
false
2,241
java
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Demo { public String printFileReader(File file ) { String result = new String(); try { FileReader fileReader = new FileReader(file); char byt[] = new char[1024]; int len = fileReader.read(byt); result = new String(byt,0,len); fileReader.close(); } catch (Exception e) { e.printStackTrace(); } return result; } public void writeTxt(File file,String string) { try { FileWriter fileWriter = new FileWriter(file); fileWriter.write(string); fileWriter.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } //加密一个字符串 返回一个字符串 public String encryption(String string) { char[] cha = string.toCharArray(); for (int i = 0; i < cha.length; i++) { cha[i] =(char)(cha[i]+5); //所有字符转化为unicode码值+5的值 } return String.valueOf(cha); } //解密一个字符串 返回一个字符串 public String decrypt(String string) { char[] cha = string.toCharArray(); for (int i = 0; i < cha.length; i++) { cha[i] =(char)(cha[i]-5); //所有字符转化为unicode码值+5的值 } return String.valueOf(cha); } public static void main(String[] args) { Demo demo = new Demo(); File file = new File("word.txt"); //在15-2的根目录中 有一个word.txt来存放密码 Scanner scanner = new Scanner(System.in); System.out.println("请输入密码"); String string = scanner.nextLine(); System.out.println("这是密码的原字符串:"+string); System.out.println("这是密码加密后的字符串:"+demo.encryption(string)); demo.writeTxt(file, demo.encryption(string)); System.out.println("加密后字符串写入成功"); System.out.println("此时word.txt中字符串:"+demo.printFileReader(file)); System.out.println("---------------------------------------------"); String string2 = demo.printFileReader(file); System.out.println("读取word.txt中的加密字符串:"+ string2); System.out.println("进行解密,解密后得到原字符串为:"+demo.decrypt(string2)); } }
de38feb858406f0ed5aa80f2f56e239e4639c3bd
250bfb76e0e969edb7248050b81962e87e221912
/misProject/src/main/java/com/mis/controller/ProductController.java
4a52370d46a24486b87986b0cd1e76a510509754
[]
no_license
clftjdanrhd/hopebook
411bc5dc3c644b77448ee5ea48115df5a31ef169
37140814f5e48bb02f8d4dc6a570b6f57e1ff81c
refs/heads/master
2022-12-09T20:48:16.326724
2020-09-11T07:44:52
2020-09-11T07:44:52
286,460,356
0
2
null
null
null
null
UTF-8
Java
false
false
3,679
java
package com.mis.controller; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.mis.domain.PageMaker; import com.mis.domain.ProductVO; import com.mis.domain.SearchCriteria; import com.mis.service.ProductService; @Controller @RequestMapping("/product/*") public class ProductController { private static final Logger logger = LoggerFactory.getLogger(ProductController.class); @Inject private ProductService service; @RequestMapping(value = "/list", method = RequestMethod.GET) public void listPage(@ModelAttribute("cri") SearchCriteria cri, Model model) throws Exception { logger.info(cri.toString()); // model.addAttribute("list", service.listCriteria(cri)); model.addAttribute("list", service.listSearchCriteria(cri)); PageMaker pageMaker = new PageMaker(); pageMaker.setCri(cri); // pageMaker.setTotalCount(service.listCountCriteria(cri)); pageMaker.setTotalCount(service.listSearchCount(cri)); model.addAttribute("pageMaker", pageMaker); } @RequestMapping(value = "/readPage", method = RequestMethod.GET) public void read(@RequestParam("pno") int pno, @ModelAttribute("cri") SearchCriteria cri, Model model) throws Exception { model.addAttribute(service.read(pno)); } @RequestMapping(value = "/removePage", method = RequestMethod.POST) public String remove(@RequestParam("pno") int pno, SearchCriteria cri, RedirectAttributes rttr) throws Exception { service.remove(pno); rttr.addAttribute("page", cri.getPage()); rttr.addAttribute("perPageNum", cri.getPerPageNum()); rttr.addAttribute("searchType", cri.getSearchType()); rttr.addAttribute("keyword", cri.getKeyword()); rttr.addFlashAttribute("msg", "SUCCESS"); return "redirect:/product/list"; } @RequestMapping(value = "/modifyPage", method = RequestMethod.GET) public void modifyPagingGET(int pno, @ModelAttribute("cri") SearchCriteria cri, Model model) throws Exception { model.addAttribute(service.read(pno)); } @RequestMapping(value = "/modifyPage", method = RequestMethod.POST) public String modifyPagingPOST(ProductVO Product, SearchCriteria cri, RedirectAttributes rttr) throws Exception { logger.info(cri.toString()); service.modify(Product); rttr.addAttribute("page", cri.getPage()); rttr.addAttribute("perPageNum", cri.getPerPageNum()); rttr.addAttribute("searchType", cri.getSearchType()); rttr.addAttribute("keyword", cri.getKeyword()); rttr.addFlashAttribute("msg", "SUCCESS"); logger.info(rttr.toString()); return "redirect:/product/list"; } @RequestMapping(value = "/register", method = RequestMethod.GET) public void registGET() throws Exception { logger.info("regist get..................."); } @RequestMapping(value = "/register", method = RequestMethod.POST) public String registPOST(ProductVO Product, RedirectAttributes rttr) throws Exception { logger.info("regist post..............."); logger.info(Product.toString()); service.register(Product); rttr.addFlashAttribute("msg", "SUCCESS"); return "redirect:/product/list"; } }
[ "82104@DESKTOP-TO9ANO4" ]
82104@DESKTOP-TO9ANO4
020d06133c9996af7d0a4611591c9dab4ad804e2
821646773d3d28dbf23e84ebe9a5814c4a8a0a5b
/app/src/main/java/com/example/ecat/score.java
a4b240b9b3f804d6b974c11857b086837703210b
[]
no_license
bisma-soomro12/ECAT_PREPARATION
f1241baba468508ae3bd4883a06eb448acdebd04
f65abb06c87a8e62b93c0c01920ecb26fc939b53
refs/heads/master
2023-06-04T05:47:55.616545
2021-06-28T14:03:44
2021-06-28T14:03:44
321,760,400
0
0
null
null
null
null
UTF-8
Java
false
false
1,184
java
package com.example.ecat; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; public class score extends AppCompatActivity { ImageButton back_btn; TextView txt_score; int s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_score); getSupportActionBar().hide(); back_btn=(ImageButton)findViewById(R.id.backButton4); txt_score=(TextView)findViewById(R.id.scoring); s=getIntent().getIntExtra("score",5); if(s>5&&s<=11){ txt_score.setText("Comgratulations!! you have scored "+s); } else{ txt_score.setText("oh no! better luck next time, you have scored "+s); } back_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(score.this,home.class); startActivity(intent); } }); } }
2f79e85a83c4552841980420bcf4b0ae5753f8ef
811b4e68c4902b8d6527371e95626902d3f3c019
/src/main/java/pl/zzpj2019/solid/lsp/shape/Shape.java
55d529cbc1cce4b4367c87733d931ae2823316b2
[]
no_license
ShiroixD/clean_code_2019
eb4a306197b6d5926e932faad94dd329e66f3e16
25607e4193d3ff287b39c3e815ed239bc6ccd999
refs/heads/master
2020-05-04T11:34:16.355435
2019-04-02T15:51:24
2019-04-02T15:51:24
179,111,000
0
0
null
2019-04-02T15:49:43
2019-04-02T15:49:43
null
UTF-8
Java
false
false
169
java
package pl.zzpj2019.solid.lsp.shape; public abstract class Shape { public abstract double calculateArea(); public abstract double calculatePerimeter(); }
cb95e4f8fc3b948d592836a996ed25d878ee8b94
54f400abbe9d246f3224d0a502e864610c2c7a98
/src/main/java/tabletlawyer/uk/tabletlawyer/MailFragment.java
5188b954307961bfe15d0f31f054f6afe1650372
[]
no_license
thanhnh1806/TabletLawyer
4353cb2e4728b72b99a1dff2443eae524026b82a
714542611f2b4fda1fce2ecaad7e716c2022e5fb
refs/heads/master
2021-01-14T08:11:37.689302
2017-02-14T10:47:09
2017-02-14T10:47:09
81,935,182
0
0
null
null
null
null
UTF-8
Java
false
false
494
java
package tabletlawyer.uk.tabletlawyer; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class MailFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_mail, container, false); } }
d56a22ab7e14c055e9606f37990ccbb4da2ded27
6b4e0d42fce779d4167235a16dcba5765fc02179
/src/java/Control/ReservaServ.java
cdcec5e0a4e0039cd13950d3bc1d23eacda22f8b
[]
no_license
AmarelleDiArgento/HotelBd
944856d3c87335231397e21dba763551836fdbd0
bb3501271e7944f0f8bd885014c86df6e4c4c50b
refs/heads/master
2020-03-08T18:21:27.166304
2018-04-18T19:55:00
2018-04-18T19:55:00
128,297,057
0
0
null
null
null
null
UTF-8
Java
false
false
12,116
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Control; import DAO.MySql.AdministradorSql; import Modelo.AsignaMod; import Modelo.AsignaPerMod; import Modelo.HabitaMod; import Modelo.ReservaMod; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; /** * * @author Sammy Guergachi <sguergachi at gmail.com> */ public class ReservaServ extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Resource(name = "poolHotel") private DataSource pool; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ response.setContentType("text/html;charset=UTF-8"); HttpSession Ses = request.getSession(true); String msj; String ruta; //if (Ses.getAttribute("log") != null) { String Accion = request.getParameter("accion"); List<AsignaPerMod> ap = (List<AsignaPerMod>) Ses.getAttribute("ApSes"); AsignaPerMod acc = null; for (AsignaPerMod a : ap) { if (a.getTabla().equalsIgnoreCase("Reserva")) { acc = a; } } if (Ses.getAttribute("msj") != null) { msj = (String) Ses.getAttribute("msj"); } else { msj = ""; } if (Ses.getAttribute("jsp") != null) { ruta = (String) Ses.getAttribute("jsp"); } else { ruta = "reserva.jsp"; } AsignaMod a = null; ReservaMod r = null; SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); int Codigo; String fIngreso; String fEgreso; String FFin; String Cedula; String Habita; int ni; int ad; int Num_personas; try { AdministradorSql Asql = new AdministradorSql(); switch (Accion) { case "Insertar": if (acc.isNuevo()) { fIngreso = f.format(new Date(request.getParameter("fIngreso"))); fEgreso = f.format(new Date(request.getParameter("fEgreso"))); Habita = request.getParameter("Habita"); Cedula = request.getParameter("cedula"); ni = Integer.parseInt(request.getParameter("ninos")); ad = Integer.parseInt(request.getParameter("adultos")); Num_personas = ni + ad; r = new ReservaMod(fIngreso, fEgreso, Cedula, Num_personas); Asql.getReserva().Registrar(r); a = new AsignaMod(Habita, r.getCodigo(), ad, ni); msj = Asql.getAsigna().insertar(a); } else { msj = "No tienes permisos para hacer registros"; } break; case "modificar": if (acc.isModificar()) { Codigo = Integer.parseInt(request.getParameter("Codigo")); fIngreso = f.format(new Date(request.getParameter("fIngreso"))); fEgreso = f.format(new Date(request.getParameter("fEgreso"))); Habita = request.getParameter("Habita"); Cedula = request.getParameter("cedula"); ni = Integer.parseInt(request.getParameter("ninos")); ad = Integer.parseInt(request.getParameter("adultos")); Num_personas = ni + ad; r = new ReservaMod(Codigo, fIngreso, fEgreso, Cedula, Num_personas); Asql.getReserva().modificar(r); a = new AsignaMod(Habita, r.getCodigo(), ad, ni); msj = Asql.getAsigna().modificar(a); } else { msj = "No tienes permisos para hacer modificaciones"; } break; case "eliminar": if (acc.isEliminar()) { Codigo = Integer.parseInt(request.getParameter("Codigo")); msj = Asql.getReserva().eliminar(Codigo); msj = Asql.getAsigna().eliminar(Codigo); } else { msj = "No tienes permisos para eliminar registros"; } break; case "obtener": if (acc.isLeer()) { } else { msj = "No tienes permisos para consultar registros"; } break; case "Listar": if (acc.isLeer()) { List<ReservaMod> rl = Asql.getReserva().listar(); Ses.setAttribute("arrR", rl); } else { msj = "No tienes permisos para consultar registros"; } break; default: ruta = "reserva.jsp"; } } catch (SQLException ex) { msj = "MySql Error: " + ex; } catch (Exception ex) { msj = "Error: " + ex; } //}else{ // ruta = "index.jsp"; // msj = "No has iniciado sesión"; //} Ses.setAttribute("msj", msj); request.getRequestDispatcher(ruta).forward(request, response); /*try { AdministradorSql man = new AdministradorSql(); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); String Action = request.getParameter("Action"); if (Action.equals("Nuevo")) { String codigoReg = request.getParameter("codigoReg"); String fIngresoReg = f.format(new Date(request.getParameter("fIngresoReg"))); String fEgresoReg = f.format(new Date(request.getParameter("fEgresoReg"))); String cedulaReg = request.getParameter("cedulaReg"); String nombreReg = request.getParameter("nombreReg"); int numPerReg = 0; try { numPerReg = Integer.parseInt(request.getParameter("numPerReg")); } catch (NumberFormatException ex) { msj = "Error NumberFormatException: " + ex; } ReservaMod mR = new ReservaMod(codigoReg, fIngresoReg, fEgresoReg, cedulaReg, nombreReg, numPerReg); msj = man.getReserva().insertar(mR); } else if (Action.equals("Modificar")) { String codigoReg = request.getParameter("codigoMod"); String fIngresoReg = request.getParameter("fIngresoMod"); String fEgresoReg = request.getParameter("fEgresoMod"); String cedulaReg = request.getParameter("cedulaMod"); String nombreReg = request.getParameter("nombreMod"); int numPerReg = 0; try { numPerReg = Integer.parseInt(request.getParameter("numPerMod")); } catch (NumberFormatException ex) { msj = "Error NumberFormatException: " + ex; } ReservaMod mR = new ReservaMod(codigoReg, fIngresoReg, fEgresoReg, cedulaReg, nombreReg, numPerReg); msj = man.getReserva().modificar(mR); } else if (Action.equals("Eliminar")) { String Id = request.getParameter("Id"); msj = man.getReserva().eliminar(Id); msj = "Se ha eliminado la reserva ID: " + Id; } else if (Action.equals("Listar")) { List<ReservaMod> r = man.getReserva().listar(); HttpSession Ses = request.getSession(true); Ses.setAttribute("arrR", r); } else if (Action.equals("Disponibles")) { String fIngresoDis = f.format(new Date(request.getParameter("fIngresoDis"))); String fEgresoDis = f.format(new Date(request.getParameter("fEgresoDis"))); //List<HabitaMod> hD = man.getHabita()..obtenerCon1(fEgresoDis, fIngresoDis); HttpSession Ses = request.getSession(true); //Ses.setAttribute("hDisp", hD); //msj = "habitaciones disponibles " + hD.size() + " " + fIngresoDis + " " + fEgresoDis; } else if (Action.equals("Obtener")) { String Id = request.getParameter("Id"); ReservaMod res = man.getReserva().obtener(Id); HttpSession Ses = request.getSession(true); Ses.setAttribute("res", res); msj = "Se ha obtenido la reserva ID: " + Id; } else { msj = "Que paso? " + Action; } } catch (SQLException ex) { msj = "Error SQL externo " + ex; } request.getRequestDispatcher("Reserva.jsp?msj=" + msj).forward(request, response); }*/ } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
43564bcab4d159b1fe34c58169be2eff6dfcebfa
26636840e8e2e114175c62e0a7f6f542d11444eb
/src/test/java/is/ru/stringcalculator/CalculatorTest.java
1ef6126f4ab0c5fb6f9fa7b81159fd92e88302a6
[]
no_license
audunnhrafn/StringCalculator-Hugb
378029f37a4312757740882e5d63d39942a14a0d
138509b4d7345a67ce34a7418f7d0b54ce049304
refs/heads/master
2021-03-19T16:23:38.247041
2017-10-15T20:45:31
2017-10-15T20:45:31
106,628,865
0
0
null
null
null
null
UTF-8
Java
false
false
1,403
java
package is.ru.stringcalculator; import static org.junit.Assert.assertEquals; import org.junit.Test; public class CalculatorTest{ @Test public void testEmptyString(){ assertEquals(0, Calculator.add("")); } @Test public void testAddOneNumber(){ assertEquals(1, Calculator.add("1")); } @Test public void testAddTwoNumbers(){ assertEquals(3, Calculator.add("1,2")); } @Test public void testMultipleNumbers(){ assertEquals(15, Calculator.add("1,2,3,4,5")); } @Test public void testNewline(){ assertEquals(6, Calculator.add("1\n2,3")); } @Test public void testSingleNegativeNumber() { try { Calculator.add("-1,2"); } catch (IllegalArgumentException e) { assertEquals("Negatives not allowed: -1", e.getMessage()); } } @Test public void testTwoNegativeNumbers() { try { Calculator.add("-1,2,-3"); } catch (IllegalArgumentException e) { assertEquals("Negatives not allowed: -1,-3", e.getMessage()); } } @Test public void testBigNumbers(){ assertEquals(2, Calculator.add("1001,2")); } @Test public void testBigNumber(){ assertEquals(0, Calculator.add("1001")); } @Test public void testDelimiter(){ assertEquals(3, Calculator.add("//;\n1;2")); } @Test public void testAnotherDelimiter(){ assertEquals(6, Calculator.add("//:-)\n1:-)2:-)3")); } }
7b12301e21bbfa5c5b04ae64d9df4bdfc6d7d582
36fe38b59d2c738670f2283975519019de717859
/mark.java
a91fda640504ff72e02a3774e811d067615705ba
[]
no_license
gregoryloden/undertale-text-tracker
341f74e1e2830b823f20426d5a1082bd795f033d
82e289fec1036c3a5923826dbc61da392f72f172
refs/heads/master
2021-01-12T08:35:22.549556
2016-12-17T05:04:34
2016-12-17T05:04:34
76,620,311
0
0
null
null
null
null
UTF-8
Java
false
false
41,861
java
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; //Functions as the everything-class to avoid generating lots of .class files public class mark implements DocumentListener, ActionListener, MouseListener, WindowListener, Comparable<mark> { public static final int MAX_SEARCH_RESULTS = 512; public static mark markListener = new mark(); //file management public static File extractedFileDir = new File("extracted data.win marked"); public static File backupFolder = new File("Backup"); public static File baseStringsFile = new File(extractedFileDir, "0.txt"); public static File latestStringsFile = new File(extractedFileDir, "strings.txt"); public static File stringTreeFile = new File("stringtree.txt"); public static File stringsUnusedFile = new File("strings_unused.txt"); public static File stringsPackedFile = new File("strings_packed.txt"); public static String[] backupFilesToCopy = new String[] { "file0", "file8", "file9", "undertale.ini", "system_information_962", "system_information_963"}; public static String fileHeaderString = "Hierarchy:\n"; public static int nextFileNum = 1; public static boolean needsSaving = false; public static boolean displaySaveSuccessMessages = false; //string searching public static char[][] searchableStrings; public static ArrayList<mark> searchableStringsFoundIndices = new ArrayList<mark>(MAX_SEARCH_RESULTS); public static ArrayList<Integer> foundStringsIndexList = new ArrayList<Integer>(); //UI components public static JFrame mainWindow; public static JTextField stringSearchTextField = new JTextField(); public static DefaultListModel<String> stringSearchResultsListModel = new DefaultListModel<String>(); public static JList<String> stringSearchResultsList = new JList<String>(stringSearchResultsListModel); public static JScrollPane stringSearchResultsListScrollPane = new JScrollPane(); public static JComboBox<String> lastSaveSelector = new JComboBox<String>(); public static DefaultComboBoxModel<String> lastSaveSelectorModel = (DefaultComboBoxModel<String>)(lastSaveSelector.getModel()); public static JButton newSaveButton = new JButton(); public static JButton newAttemptButton = new JButton(); public static DefaultListModel<String> allStringsListModel = new DefaultListModel<String>(); public static JList<String> allStringsList = new JList<String>(allStringsListModel); public static JScrollPane allStringsListScrollPane = new JScrollPane(); public static JButton backupButton = new JButton(); public static JButton exportStringsButton = new JButton(); public static JButton exportStringTreeButton = new JButton(); //for function outputs public static JComboBox<String> saveAndTextParentSavePicker = new JComboBox<String>(lastSaveSelectorModel); public static JTextField saveAndTextTextField = new JTextField(); public static String saveAndTextSave = ""; public static String saveAndTextText = ""; public static void main(String[] args) { setupWindow(); loadBaseStrings(); loadStrings(); saveMissingStringFiles(); displaySaveSuccessMessages = true; showWindow(); } public static void setupWindow() { JPanel mainPanel = new JPanel(); stringSearchTextField.getDocument().addDocumentListener(markListener); stringSearchResultsListScrollPane.setViewportView(stringSearchResultsList); stringSearchResultsListScrollPane.setMaximumSize(new Dimension(500, Short.MAX_VALUE)); stringSearchResultsList.addMouseListener(markListener); newSaveButton.setText("New Save"); newSaveButton.addActionListener(markListener); newAttemptButton.setText("New Attempt"); newAttemptButton.addActionListener(markListener); allStringsList.setVisibleRowCount(22); allStringsListScrollPane.setViewportView(allStringsList); allStringsListScrollPane.setMaximumSize(new Dimension(500, Short.MAX_VALUE)); allStringsList.addMouseListener(markListener); backupButton.setText("Backup"); backupButton.addActionListener(markListener); exportStringsButton.setText("Save Strings"); exportStringsButton.addActionListener(markListener); exportStringTreeButton.setText("Save String Tree"); exportStringTreeButton.addActionListener(markListener); Insets buttonInsets = backupButton.getMargin(); buttonInsets.left -= 4; buttonInsets.right -= 4; backupButton.setMargin(buttonInsets); exportStringsButton.setMargin(buttonInsets); exportStringTreeButton.setMargin(buttonInsets); newSaveButton.setMargin(buttonInsets); newAttemptButton.setMargin(buttonInsets); GroupLayout layout = new GroupLayout(mainPanel); mainPanel.setLayout(layout); layout.setHorizontalGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup() .addComponent(stringSearchResultsListScrollPane) .addComponent(stringSearchTextField) .addComponent(allStringsListScrollPane) .addComponent(lastSaveSelector) .addGroup(layout.createSequentialGroup() .addComponent(backupButton) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(exportStringsButton) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(exportStringTreeButton) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(newSaveButton) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(newAttemptButton))) .addContainerGap() ); layout.setVerticalGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(stringSearchTextField) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(stringSearchResultsListScrollPane) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(lastSaveSelector) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup() .addComponent(backupButton) .addComponent(exportStringsButton) .addComponent(exportStringTreeButton) .addComponent(newSaveButton) .addComponent(newAttemptButton)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(allStringsListScrollPane) .addContainerGap() ); mainPanel.setSize(mainPanel.getPreferredSize()); mainWindow = new JFrame("UNDERTALE String Marking"); mainWindow.addWindowListener(markListener); mainWindow.add(mainPanel); mainWindow.setContentPane(mainPanel); mainWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } public static void showWindow() { mainWindow.setVisible(true); mainWindow.setLocation(5, 5); mainWindow.toFront(); mainWindow.pack(); setStartingSaveAndString(); produceSaveAndText("Pick Starting Save", true, false); } public static boolean confirm(String message, String title) { return JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; } public mark() {} //////////////////////////////////////////////////////////////// //////// Extracting from strings or save names //////////////////////////////////////////////////////////////// public static String lettersAbbreviationAt(String s, int start) { int end = start; for (char c; (c = s.charAt(end)) >= 'A' && c <= 'Z'; end++) ; return s.substring(start, end); } //expects the string to be in 4-spaces form from allStringsListModel //returns the abbreviation with the attempt number public static String extractAbbreviationFromString(String s) { int abbreviationIndex = s.indexOf(' ', 5) + 4; return s.substring(abbreviationIndex, s.indexOf(' ', abbreviationIndex)); } public static String buildAbbreviation(String s, int start) { StringBuilder sb = new StringBuilder(); buildAbbreviationTo(s, start, sb); return sb.toString(); } public static void buildAbbreviationTo(String s, int start, StringBuilder sb) { String sUpper = s.toUpperCase(); for (int i = start; true;) { for (char c; true; i++) { if (i >= sUpper.length()) return; if ((c = sUpper.charAt(i)) >= 'A' && c <= 'Z') break; } sb.append(sUpper.charAt(i)); i++; for (char c; true; i++) { if (i >= sUpper.length()) return; if ((c = sUpper.charAt(i)) < 'A' || c > 'Z') break; } } } //////////////////////////////////////////////////////////////// //////// Retrieving strings or save names //////////////////////////////////////////////////////////////// public static String currentSaveAbbreviation() { String currentSave = (String)(lastSaveSelectorModel.getSelectedItem()); return currentSave.substring(currentSave.indexOf('-') + 1, currentSave.indexOf(':')); } public static String currentSaveName() { String currentSave = (String)(lastSaveSelectorModel.getSelectedItem()); return currentSave.substring(currentSave.indexOf(':') + 2); } //assumes (includeSave || includeText) is true public static boolean produceSaveAndText(String title, boolean includeSave, boolean includeText) { JComponent toShow; if (!includeText) toShow = saveAndTextParentSavePicker; else { if (!includeSave) toShow = saveAndTextTextField; else { toShow = new JPanel(); toShow.setLayout(new BoxLayout(toShow, BoxLayout.Y_AXIS)); toShow.add(saveAndTextParentSavePicker); toShow.add(saveAndTextTextField); } } if (JOptionPane.showConfirmDialog( null, toShow, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) { if (includeSave) saveAndTextSave = (String)(lastSaveSelectorModel.getSelectedItem()); if (includeText) saveAndTextText = saveAndTextTextField.getText(); return true; } return false; } //////////////////////////////////////////////////////////////// //////// Finding strings or save names //////////////////////////////////////////////////////////////// //finds the hierarchy index of a save that starts with the given abbreviation after the dash //abbreviation must include a colon public static int findAbbreviation(String abbreviation) { int saveCount = lastSaveSelector.getItemCount(); for (int i = 0; i < saveCount; i++) { String save = lastSaveSelector.getItemAt(i); if (save.startsWith(abbreviation, save.indexOf('-') + 1)) return i; } return -1; } //returns 1 if the abbreviation is not found public static int nextAvailableAbbreviationNum(String abbreviation) { int saveNum = 0; int saveCount = lastSaveSelector.getItemCount(); for (int i = 0; i < saveCount; i++) { String save = lastSaveSelector.getItemAt(i); int abbreviationIndex = save.indexOf('-') + 1; if (save.startsWith(abbreviation, abbreviationIndex)) { int abbreviationEndIndex = abbreviationIndex + abbreviation.length(); char c = save.charAt(abbreviationEndIndex); if (c >= '0' && c <= '9') saveNum = Math.max(saveNum, Integer.parseInt( save.substring(abbreviationEndIndex, save.indexOf(':', abbreviationEndIndex + 1)))); } } return saveNum + 1; } //childIndex is the hierarchy index of the theoretical first child //returns the first hierarchy index >= childIndex with a dash at or before dashIndex public static int skipChildren(int childIndex, int dashIndex) { while (childIndex < lastSaveSelector.getItemCount() && lastSaveSelector.getItemAt(childIndex).indexOf('-') > dashIndex) childIndex++; return childIndex; } //////////////////////////////////////////////////////////////// //////// Altering string views //////////////////////////////////////////////////////////////// public static void refreshStringSearchResults() { String fullSearchText = stringSearchTextField.getText(); int fullSearchTextLength = fullSearchText.length(); //get rid of any spaces, they're only good for loosening length verification char[] searchText = fullSearchText.replace(" ", "").toLowerCase().toCharArray(); int searchTextLength = searchText.length; if (searchTextLength < 1) stringSearchResultsList.setEnabled(false); else { stringSearchResultsListModel.removeAllElements(); searchableStringsFoundIndices.clear(); //go through every string and see if it matches the input int searchableStringsLength = searchableStrings.length; char startChar = searchText[0]; for (int i = 0; i < searchableStringsLength; i++) { char[] resultString = searchableStrings[i]; int resultStringLength = resultString.length; //it can't start at an index if it would go past the end of the string int maxSearchIndex = resultStringLength - searchTextLength; //keep track of stats so that we can sort boolean stringPasses = false; int matchedLength = Integer.MAX_VALUE; //first, look for this char in the string for (int k = 0; k <= maxSearchIndex; k++) { //we found a spot where it starts //now go through and see if we found our string here //if we find one, keep looking through the string to see if we can find a shorter match if (resultString[k] == startChar) { //1 character strings always match single characters if (searchTextLength == 1) { stringPasses = true; break; } else { for (int j = 1, newK = k + 1; newK < resultStringLength;) { if (searchText[j] == resultString[newK]) { j++; //if we got through all our characters, the string matches if (j == searchTextLength) { stringPasses = true; matchedLength = Math.min(matchedLength, newK - k + 1); break; } } newK++; //the string appears not to match, stop searching here if (newK - k >= fullSearchTextLength * 2) break; } } } } if (stringPasses) searchableStringsFoundIndices.add(new mark(i, matchedLength, resultStringLength)); } if (searchableStringsFoundIndices.size() <= MAX_SEARCH_RESULTS) { stringSearchResultsList.setEnabled(true); Collections.sort(searchableStringsFoundIndices); for (mark foundIndexStats : searchableStringsFoundIndices) stringSearchResultsListModel.addElement(allStringsListModel.get(foundIndexStats.searchableStringFoundIndex)); } else { stringSearchResultsList.setEnabled(false); stringSearchResultsListModel.addElement("Please narrow your search to no more than " + MAX_SEARCH_RESULTS + " results (got " + searchableStringsFoundIndices.size() + ")"); } } } public static void scrollToStringInList() { if (stringSearchResultsList.isEnabled()) selectSearchableString( searchableStringsFoundIndices .get(stringSearchResultsList.getSelectedIndex()) .searchableStringFoundIndex); } public static void selectSearchableString(int index) { allStringsList.setSelectedIndex(index); //make some room on both sides int spacing = (allStringsList.getVisibleRowCount() - 1) / 2; allStringsList.ensureIndexIsVisible(Math.max(0, index - spacing)); allStringsList.ensureIndexIsVisible(Math.min(searchableStrings.length - 1, index + spacing)); } public static void setStartingSaveAndString() { //default selection to the most recent string int newestStringIndex = foundStringsIndexList.size() - 1; if (newestStringIndex >= 0) { int foundIndex = foundStringsIndexList.get(newestStringIndex); lastSaveSelector.setSelectedIndex( findAbbreviation( extractAbbreviationFromString(allStringsListModel.get(foundIndex)) + ":")); selectSearchableString(foundIndex); } } //////////////////////////////////////////////////////////////// //////// Modifying strings or save names //////////////////////////////////////////////////////////////// public static void markString(String customAbbreviation) { int selectedIndex = allStringsList.getSelectedIndex(); String selectedString = allStringsList.getSelectedValue(); String newString = null; if (selectedString.startsWith("#")) { //update the string newString = " " + foundStringsIndexList.size() + " " + currentSaveAbbreviation() + " " + selectedString; foundStringsIndexList.add(selectedIndex); } else { saveAndTextTextField.setText(""); if (produceSaveAndText("Select a new index", true, true)) { int oldIndex = Integer.parseInt(selectedString.substring(4, selectedString.indexOf(' ', 4))); //if we didn't input an index, just use the old index int newIndex = saveAndTextText.length() == 0 ? oldIndex : Integer.parseInt(saveAndTextText); int cappedIndex; int diff; //if we're removing it, put it past the end instead //this way, everything gets shifted backwards properly if (newIndex < 0) newIndex = foundStringsIndexList.size(); if (newIndex > oldIndex) { cappedIndex = Math.min(foundStringsIndexList.size() - 1, newIndex); diff = 1; } else { cappedIndex = Math.max(0, newIndex); diff = -1; } //reorder and edit the other strings for (int toIndex = oldIndex; toIndex != cappedIndex;) { //this is where we will be getting the string+index from //we will then move it to oldIndex int fromIndex = toIndex + diff; //move the index int stringIndex = foundStringsIndexList.get(fromIndex); foundStringsIndexList.set(toIndex, stringIndex); //update the string String movedString = allStringsListModel.get(stringIndex) .replace(String.valueOf(fromIndex), String.valueOf(toIndex)); allStringsListModel.set(stringIndex, movedString); searchableStrings[stringIndex] = movedString.toLowerCase().toCharArray(); //and finally, update the index toIndex = fromIndex; } //if our index was in the bounds, insert it if (newIndex == cappedIndex) { foundStringsIndexList.set(newIndex, selectedIndex); //replace the index of the string newString = selectedString.replace(String.valueOf(oldIndex), String.valueOf(newIndex)); //always replace the abbreviation in the string with the one in the save int abbreviationIndex = newString.indexOf(' ', 5) + 4; newString = newString.replace( newString.substring(abbreviationIndex, newString.indexOf(' ', abbreviationIndex)), currentSaveAbbreviation()); //otherwise, strip it of its index //we made sure to shift everything backwards, so the last element is dead } else { foundStringsIndexList.remove(foundStringsIndexList.size() - 1); newString = selectedString.substring(selectedString.indexOf('#')); } } } //if we want to replace our string, replace it in the display list and the search list if (newString != null) { allStringsListModel.set(selectedIndex, newString); searchableStrings[selectedIndex] = newString.toLowerCase().toCharArray(); needsSaving = true; } } public static void newSave() { saveAndTextTextField.setText(currentSaveName()); //get the save name but make sure it has an unused abbreviation while (true) { //pick a save name if (!produceSaveAndText("Pick Parent Save + New Name", true, true) || saveAndTextText.length() == 0) break; //build the save abbreviation StringBuilder newSavePickerName = new StringBuilder(" "); int dashIndex = saveAndTextSave.indexOf('-'); newSavePickerName.append(saveAndTextSave, 0, dashIndex + 1); buildAbbreviationTo(saveAndTextText, 0, newSavePickerName); //add the abbreviation num; 1 if it's new, something else if it's not String abbreviation = newSavePickerName.substring(dashIndex + 2); int newSaveNum = nextAvailableAbbreviationNum(abbreviation); if (newSaveNum > 1 && !confirm( "The abbreviation " + abbreviation + " is already in use. Create a new attempt?", "Already In Use")) continue; newSavePickerName.append(String.valueOf(newSaveNum)); newSavePickerName.append(": "); newSavePickerName.append(saveAndTextText); //skip past any children of the parent save int newSaveIndex = skipChildren(saveAndTextParentSavePicker.getSelectedIndex() + 1, dashIndex); //insert it lastSaveSelectorModel.insertElementAt(newSavePickerName.toString(), newSaveIndex); lastSaveSelector.setSelectedIndex(newSaveIndex); mainWindow.pack(); needsSaving = true; break; } } public static void newAttempt() { //find the abbreviation we'll use String lastSaveName = (String)(lastSaveSelectorModel.getSelectedItem()); int colonIndex = lastSaveName.indexOf(':'); if (confirm("Create a new attempt of " + lastSaveName.substring(colonIndex + 2) + "?", "Confirm New Attempt")) { int abbreviationIndex = lastSaveName.indexOf('-') + 1; String abbreviation = lettersAbbreviationAt(lastSaveName, abbreviationIndex); //insert it with the next number up int newSaveIndex = skipChildren(lastSaveSelector.getSelectedIndex() + 1, abbreviationIndex - 2); lastSaveSelectorModel.insertElementAt( lastSaveName.replace( lastSaveName.substring(abbreviationIndex + abbreviation.length(), colonIndex), String.valueOf(nextAvailableAbbreviationNum(abbreviation))), newSaveIndex); lastSaveSelector.setSelectedIndex(newSaveIndex); mainWindow.pack(); needsSaving = true; } } //////////////////////////////////////////////////////////////// //////// File load/save management //////////////////////////////////////////////////////////////// public static void loadBaseStrings() { //ensure the base strings file exists if (!extractedFileDir.exists()) extractedFileDir.mkdir(); if (!baseStringsFile.exists()) extractDataWin(); //find the latest numbered strings file int lastFileNum = 0; while ((new File(extractedFileDir, nextFileNum + ".txt")).exists()) { lastFileNum = nextFileNum; nextFileNum *= 2; } while (nextFileNum > lastFileNum + 1) { int mid = (nextFileNum + lastFileNum) / 2; if ((new File(extractedFileDir, mid + ".txt")).exists()) lastFileNum = mid; else nextFileNum = mid; } } public static void loadStrings() { ArrayList<String> loadedStrings; //load the strings from the file we want to use if (latestStringsFile.exists()) loadedStrings = loadStrings(latestStringsFile, true); else if (stringsPackedFile.exists()) loadedStrings = loadStrings(stringsPackedFile, true); else loadedStrings = loadStrings(new File(extractedFileDir, (nextFileNum - 1) + ".txt"), true); for (String s : loadedStrings) allStringsListModel.addElement(s); } public static ArrayList<String> loadStrings(File f, boolean isPrimaryLoad) { //load the file and hierarchy ArrayList<String> fileStrings = loadFileStrings(f); int stringsListIndex = loadHierarchy(fileStrings, !isPrimaryLoad); //track which saves got used and which ones didn't boolean[] usedSaves = new boolean[lastSaveSelector.getItemCount()]; //load the strings ArrayList<String> loadedStrings; if (f == stringsPackedFile) loadedStrings = loadFromPackedStringsFile(stringsListIndex, fileStrings, usedSaves); else loadedStrings = loadFromStringsFile(stringsListIndex, fileStrings, usedSaves); //verify the strings we got unless this is the base strings being loaded for the packed strings if (isPrimaryLoad) { logUnusedSaves(usedSaves); verifyStringsAreInOrder(loadedStrings); } return loadedStrings; } public static void saveMissingStringFiles() { //if we haven't found any strings to save, then there's nothing to save if (foundStringsIndexList.size() < 1) return; if (!latestStringsFile.exists()) exportStrings(); if (!stringsPackedFile.exists()) exportStringsPacked(); if (!stringTreeFile.exists()) exportStringTree(); } //////////////////////////////////////////////////////////////// //////// Loading files //////////////////////////////////////////////////////////////// public static ArrayList<String> loadFileStrings(File f) { ArrayList<String> fileStrings = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new FileReader(f)); String line; while ((line = br.readLine()) != null) fileStrings.add(line); br.close(); } catch(Exception e) { e.printStackTrace(); System.exit(0); } return fileStrings; } //returns the index after the blank line after the hierarchy public static int loadHierarchy(ArrayList<String> fileStrings, boolean discardSaveHierarchy) { //build the saves hierarchy //skip the "Hierarchy:" line int saveStringsIndex = 1; int lastSaveIndent = 0; for (; true; saveStringsIndex++) { String saveName = fileStrings.get(saveStringsIndex); //we're done if we get an empty line, return the line after it if (saveName.length() == 0) return saveStringsIndex + 1; //when loading the packed strings, we load the base strings first and drop its hierarchy if (discardSaveHierarchy) continue; //add the string, but quit if hand-editing the strings file messed it up lastSaveIndent = verifySaveStringIsValid(saveName, lastSaveIndent); lastSaveSelector.addItem(saveName); } } public static ArrayList<String> loadFromStringsFile(int stringsListIndex, ArrayList<String> fileStrings, boolean[] usedSaves) { ArrayList<String> loadedStrings = new ArrayList<String>(); //now fill the searchable strings list searchableStrings = new char[fileStrings.size() - stringsListIndex][]; for (int i = 0; i < searchableStrings.length; i++) { //add the string to the list String s = fileStrings.get(i + stringsListIndex); //save its index if it has one if (s.charAt(0) != '#') { int secondTabIndex = s.indexOf('\t', 1); int foundStringsIndexListIndex = Integer.parseInt(s.substring(1, secondTabIndex)); while (foundStringsIndexList.size() <= foundStringsIndexListIndex) foundStringsIndexList.add(null); foundStringsIndexList.set(foundStringsIndexListIndex, i); //also mark the save that it uses String abbreviation = s.substring(secondTabIndex + 1, s.indexOf('\t', secondTabIndex + 1)); markAbbreviationUsed(abbreviation, usedSaves); //use spaces instead of tabs for the strings list s = s.replaceFirst("\t([^\t]*)\t([^\t]*)\t#", " $1 $2 #"); } loadedStrings.add(s); searchableStrings[i] = s.toLowerCase().toCharArray(); } return loadedStrings; } public static ArrayList<String> loadFromPackedStringsFile(int stringsListIndex, ArrayList<String> fileStrings, boolean[] usedSaves) { //load the base strings before continuing ArrayList<String> loadedStrings = loadStrings(baseStringsFile, false); for (int i = stringsListIndex; i < fileStrings.size(); i++) { String[] indexAndAbbreviation = fileStrings.get(i).split("\t"); String indexString = indexAndAbbreviation[0]; String abbreviation = indexAndAbbreviation[1]; int index = Integer.parseInt(indexString); foundStringsIndexList.add(index); markAbbreviationUsed(abbreviation, usedSaves); String newString = " " + (i - stringsListIndex) + " " + abbreviation + " " + loadedStrings.get(index); loadedStrings.set(index, newString); searchableStrings[index] = newString.toLowerCase().toCharArray(); } return loadedStrings; } //////////////////////////////////////////////////////////////// //////// Verify loaded information //////////////////////////////////////////////////////////////// public static void markAbbreviationUsed(String abbreviation, boolean[] usedSaves) { int saveIndex = findAbbreviation(abbreviation + ":"); if (saveIndex >= 0) usedSaves[saveIndex] = true; else { System.out.println("Could not find save name for " + abbreviation); System.exit(0); } } public static int verifySaveStringIsValid(String saveName, int lastSaveIndent) { //verify the save isn't too indented int dashIndex = saveName.indexOf('-'); if (dashIndex > lastSaveIndent + 1) { System.out.println("Formatting error: need to de-indent " + saveName.substring(dashIndex)); System.exit(0); } //verify the save doesn't have the same abbreviation as another save int colonIndex = saveName.indexOf(':'); String abbreviation = saveName.substring(dashIndex + 1, colonIndex + 1); if (findAbbreviation(abbreviation) >= 0) { System.out.println("Copy error: duplicate use of " + abbreviation.substring(0, abbreviation.length() - 1)); System.exit(0); } //check if its abbreviation matches its string String lettersAbbreviation = lettersAbbreviationAt(abbreviation, 0); if (!lettersAbbreviationAt(abbreviation, 0).equals(buildAbbreviation(saveName, colonIndex + 2))) { System.out.println("Save \"" + saveName.substring(colonIndex + 2) + "\" does not match abbreviation " + lettersAbbreviation); } //verify that it has a number if (lettersAbbreviation.length() == abbreviation.length() - 1) { System.out.println("Formatting error: abbreviation " + abbreviation + " is missing attempt number"); System.exit(0); } return dashIndex; } public static void logUnusedSaves(boolean[] usedSaves) { for (int i = 0; i < usedSaves.length; i++) { if (!usedSaves[i]) { String s = lastSaveSelector.getItemAt(i); System.out.println("Unused save " + s.substring(s.indexOf('-'))); } } } public static void verifyStringsAreInOrder(ArrayList<String> loadedStrings) { //now go through all the strings in export order and verify that the saves are in order HashMap<String, Integer> lastAbbreviationNums = new HashMap<String, Integer>(); String lastAbbreviation = ""; for (int i : foundStringsIndexList) { String abbreviation = extractAbbreviationFromString(loadedStrings.get(i)); if (!abbreviation.equals(lastAbbreviation)) { String lettersAbbreviation = lettersAbbreviationAt(abbreviation, 0); int abbreviationNum = Integer.parseInt(abbreviation.substring(lettersAbbreviation.length())); Integer lastAbbreviationNum = lastAbbreviationNums.get(lettersAbbreviation); if (lastAbbreviationNum == null) { if (abbreviationNum != 1) System.out.println(abbreviation + " not preceded by any abbreviation"); } else { if (abbreviationNum != lastAbbreviationNum + 1) System.out.println(abbreviation + " preceded by " + lettersAbbreviation + lastAbbreviationNum); } lastAbbreviationNums.put(lettersAbbreviation, abbreviationNum); lastAbbreviation = abbreviation; } } } //////////////////////////////////////////////////////////////// //////// Saving files //////////////////////////////////////////////////////////////// public static void extractDataWin() { try { //find data.win System.out.println("Choosing data.win file..."); LookAndFeel defaultLookAndFeel = UIManager.getLookAndFeel(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Open your \"data.win\" file"); if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) throw new IOException("Could not retrieve data.win for extracting"); UIManager.setLookAndFeel(defaultLookAndFeel); System.out.println("Extracting data.win"); //read the file to a byte array File fIn = chooser.getSelectedFile(); byte[] charsIn = new byte[(int)(fIn.length())]; FileInputStream fis = new FileInputStream(fIn); int read = fis.read(charsIn); fis.close(); //prepare the output byte[] charsOut = new byte[charsIn.length]; int charsOutCount = 0; int length = charsIn.length; int linesWritten = 0; //these are the first and last strings in the region of strings we might care about byte[] startString = "Greetings.".getBytes(); byte[] endString = "* (Looks like Mettaton is& undergoing repairs.)/%%".getBytes(); //search for the start string byte startChar = startString[0]; int i = 0; while (charsIn[i] != startChar || !byteArrayAtIndexEquals(charsIn, i, startString)) i++; //i is now the index of the first string //search through the list until we find our last string startChar = endString[0]; while (true) { int startI = i; charsOut[charsOutCount] = '#'; charsOut[charsOutCount + 1] = '#'; charsOutCount += 2; //undertale strings are c-strings, find the \0 while (charsIn[i] != 0) { charsOut[charsOutCount] = charsIn[i]; charsOutCount++; i++; } charsOut[charsOutCount] = '\n'; charsOutCount++; linesWritten++; if (charsIn[startI] == startChar && byteArrayAtIndexEquals(charsIn, startI, endString)) break; //advance 5 bytes to get to the next string i += 5; } FileOutputStream fos = new FileOutputStream(baseStringsFile); fos.write(fileHeaderString.getBytes()); fos.write("-NPS1: No Previous Save\n\n".getBytes()); fos.write(charsOut, 0, charsOutCount); fos.close(); System.out.println("Extracted data.win with " + linesWritten + " lines and " + charsOutCount + " bytes"); } catch(Exception e) { e.printStackTrace(); System.exit(0); } } public static boolean byteArrayAtIndexEquals(byte[] source, int index, byte[] searchingFor) { int searchingForLength = searchingFor.length; //start at 1, assume that we've already compared the first character for (int i = 1; i < searchingForLength; i++) { if (source[index + i] != searchingFor[i]) return false; } return true; } public static void exportStrings() { try { //if we have a strings.txt file, rename it to the next num //if we don't, we can write straight to it if (latestStringsFile.exists()) { String nextNumFileName = nextFileNum + ".txt"; if (latestStringsFile.renameTo(new File(extractedFileDir, nextNumFileName))) nextFileNum++; else throw new IOException("Unable to rename " + latestStringsFile.getName() + " to " + nextNumFileName); } FileWriter writer = new FileWriter(latestStringsFile); FileWriter unusedWriter = new FileWriter(stringsUnusedFile); writeHeadersAndHierarchy(writer); for (int i = 0; i < allStringsListModel.getSize(); i++) { String line = allStringsListModel.get(i); if (line.charAt(0) == '#') { writer.write(line); unusedWriter.write(line); unusedWriter.write('\n'); } else writer.write(line.replaceFirst(" ([^ ]*) ([^ ]*) #", "\t$1\t$2\t#")); writer.write('\n'); } writer.close(); unusedWriter.close(); needsSaving = false; if (displaySaveSuccessMessages) JOptionPane.showMessageDialog(null, "Your file has been saved!"); } catch(Exception e) { e.printStackTrace(); } } public static void writeHeadersAndHierarchy(FileWriter writer) throws Exception { writer.write(fileHeaderString.toString()); int itemCount = lastSaveSelector.getItemCount(); for (int i = 0; i < itemCount; i++) { writer.write(lastSaveSelector.getItemAt(i)); writer.write('\n'); } writer.write('\n'); } public static void exportStringsPacked() { try { FileWriter writer = new FileWriter(stringsPackedFile); writeHeadersAndHierarchy(writer); for (int i = 0; i < foundStringsIndexList.size(); i++) { int foundStringIndex = foundStringsIndexList.get(i); writer.write(String.valueOf(foundStringIndex)); writer.write('\t'); writer.write(extractAbbreviationFromString(allStringsListModel.get(foundStringIndex))); writer.write('\n'); } writer.close(); } catch(Exception e) { e.printStackTrace(); } } public static void exportStringTree() { try { FileWriter writer = new FileWriter(stringTreeFile); writeHeadersAndHierarchy(writer); writer.write("Found text strings:\n"); String lastAbbreviation = ""; ArrayList<String> lastParentSaves = new ArrayList<String>(); int lastAbbreviationIndex = -1; String lastPrefix = null; for (int i = 0; i < foundStringsIndexList.size(); i++) { String foundString = allStringsListModel.get(foundStringsIndexList.get(i)); String abbreviation = extractAbbreviationFromString(foundString); if (!abbreviation.equals(lastAbbreviation)) { //we want to find the parent list of saves up to and including the one from the abbreviation //start by finding the save name with the abbreviation ArrayList<String> parentSaves = new ArrayList<String>(); int saveIndex = 0; int dashIndex = 0; for (; true; saveIndex++) { String saveName = lastSaveSelector.getItemAt(saveIndex); dashIndex = saveName.indexOf('-'); //we found the save that goes with this abbreviation if (saveName.startsWith(abbreviation, dashIndex + 1)) { parentSaves.add(saveName); lastPrefix = saveName.substring(0, dashIndex) + " -|"; lastAbbreviation = abbreviation; break; } } //now that we have our index, go find all the saves above it while (dashIndex > 0) { dashIndex--; String saveName; for (saveIndex--; (saveName = lastSaveSelector.getItemAt(saveIndex)) .indexOf('-') > dashIndex; saveIndex--) ; parentSaves.add(saveName); } //now we have all our saves //skip past all common parents //but even if the new save is a parent of the last save, we want to keep it int parentSavesIndex = parentSaves.size() - 1; for (int lastParentSavesIndex = lastParentSaves.size() - 1; lastParentSavesIndex >= 0 && parentSavesIndex >= 1 && lastParentSaves .get(lastParentSavesIndex) .equals(parentSaves.get(parentSavesIndex)); parentSavesIndex--) lastParentSavesIndex--; //add the rest to the output for (; parentSavesIndex >= 0; parentSavesIndex--) { writer.write(parentSaves.get(parentSavesIndex)); writer.write('\n'); } //and don't forget to save the last parent saves list lastParentSaves = parentSaves; } writer.write(lastPrefix); //skip the "##" writer.write(foundString.substring(foundString.indexOf('#') + 2)); writer.write('\n'); } writer.close(); if (displaySaveSuccessMessages) JOptionPane.showMessageDialog(null, "Your tree has been exported!"); } catch(Exception e) { e.printStackTrace(); } } public static void backupSaves() { saveAndTextTextField.setText(currentSaveName()); while (true) { if (!produceSaveAndText("Enter Backup Name", false, true)) break; if (!backupFolder.exists()) backupFolder.mkdir(); File saveFolder = new File(backupFolder, saveAndTextText); if (saveFolder.exists()) { JOptionPane.showMessageDialog(null, "Backup folder " + saveAndTextText + " already exists"); continue; } saveFolder.mkdir(); for (int i = 0; i < backupFilesToCopy.length; i++) { File saveFile = new File(backupFilesToCopy[i]); if (!saveFile.exists()) { System.out.println("Could not find " + backupFilesToCopy[i]); continue; } try { byte[] fileBytes = new byte[(int)(saveFile.length())]; FileInputStream fis = new FileInputStream(saveFile); fis.read(fileBytes); if (fis.read() != -1) throw new IOException("Unable to read entire file for " + saveFile.getName()); fis.close(); FileOutputStream fos = new FileOutputStream(new File(saveFolder, backupFilesToCopy[i])); fos.write(fileBytes, 0, fileBytes.length); fos.close(); } catch(Exception ex) { ex.printStackTrace(); System.out.println("Could not backup " + saveFile.getName()); } } break; } } //////////////////////////////////////////////////////////////// //////// Events //////////////////////////////////////////////////////////////// public void insertUpdate(DocumentEvent e) { refreshStringSearchResults(); } public void changedUpdate(DocumentEvent e) { refreshStringSearchResults(); } public void removeUpdate(DocumentEvent e) { refreshStringSearchResults(); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == newSaveButton) newSave(); else if (source == newAttemptButton) newAttempt(); else if (source == backupButton) backupSaves(); else if (source == exportStringsButton) { if (needsSaving ? confirm("Save your changes?", "Save Changes") : confirm("No changes detected. Save anyway?", "Save Not Needed")) exportStrings(); } else if (source == exportStringTreeButton) { if (confirm("Export String Tree?", "Export Tree")) exportStringTree(); } else System.out.println("Unknown action performed"); } public void mousePressed(MouseEvent evt) { Object source = evt.getSource(); if (source == stringSearchResultsList) scrollToStringInList(); else if (source == allStringsList) { if (evt.getClickCount() == 2) markString(null); } } public void windowClosing(WindowEvent evt) { if (needsSaving) { int response = JOptionPane.showConfirmDialog(null, "You have unsaved changes.\nWould you like to save them before exiting?"); if (response == JOptionPane.YES_OPTION) exportStrings(); else if (response == JOptionPane.CANCEL_OPTION) return; } System.exit(0); } public void windowActivated(WindowEvent evt) {} public void windowClosed(WindowEvent evt) {} public void windowDeactivated(WindowEvent evt) {} public void windowDeiconified(WindowEvent evt) {} public void windowIconified(WindowEvent evt) {} public void windowOpened(WindowEvent evt) {} public void mouseClicked(MouseEvent evt) {} public void mouseReleased(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {} //////////////////////////////////////////////////////////////// //////// Class for sorting string results //////////////////////////////////////////////////////////////// public int searchableStringFoundIndex; public int sortableMatchedLength; public int sortableTotalLength; public mark(int ssfi, int sml, int stl) { searchableStringFoundIndex = ssfi; sortableMatchedLength = sml; sortableTotalLength = stl; } public int compareTo(mark m) { if (sortableMatchedLength != m.sortableMatchedLength) return sortableMatchedLength - m.sortableMatchedLength; else return sortableTotalLength - m.sortableTotalLength; } }
f8ad5b9cc4ed6d6b3eebb7e94fbbe29b1a467c8d
a2c0c7b352d7fe002261c70d2e21a6bbf69e17b3
/app/src/main/java/co/cvdcc/brojekcustomer/gmap/GMapDirection.java
a278999359336a141fc14dc89780c31cc1475578
[]
no_license
apullo/customer-master
2f71bdf6ba346baa0453caa4621888352447d4fa
ab106f7602fea6b26cac404dd5be65ba7940d684
refs/heads/master
2022-11-05T22:12:32.077912
2020-06-25T10:21:52
2020-06-25T10:21:52
274,886,737
0
0
null
null
null
null
UTF-8
Java
false
false
12,654
java
package co.cvdcc.brojekcustomer.gmap; import com.google.android.gms.maps.model.LatLng; import co.cvdcc.brojekcustomer.model.MboxLocation; import co.cvdcc.brojekcustomer.utils.Log; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class GMapDirection { public final static String MODE_DRIVING = "driving"; public final static String MODE_WALKING = "walking"; public GMapDirection() { } public String getUrl(LatLng start, LatLng end, String mode, boolean isAlternative) { String url = "http://maps.googleapis.com/maps/api/directions/json?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.latitude + "," + end.longitude + "&sensor=false&units=metric&mode="+mode; if (isAlternative) url += "&alternatives=true"; Log.e("getUrl", url); return url; } public String getUrlVia(String mode, boolean isAlternative, LatLng start, LatLng... end) { String via = "&waypoints="; if(end.length > 1){ for(LatLng end_latLng:end){ via += "via:"+end_latLng.latitude+"%2C"+end_latLng.longitude+"%7C"; } }else { via = ""; } String url = "http://maps.googleapis.com/maps/api/directions/json?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end[end.length-1].latitude + "," + end[end.length-1].longitude + via + "&sensor=false&units=metric&mode="+mode; if (isAlternative) url += "&alternatives=true"; Log.e("getUrl", url); return url; } public String getViaUrl(MboxLocation start, ArrayList<MboxLocation> end, String mode, boolean isAlternative) { String via = "&waypoints="; if(end.size() > 1){ for(MboxLocation end_latLng:end){ via += "via:"+end_latLng.latitude+"%2C"+end_latLng.longitude+"%7C"; } }else { via = ""; } String url = "http://maps.googleapis.com/maps/api/directions/json?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.get(end.size()-1).latitude + "," + end.get(end.size()-1).longitude + via + "&sensor=false&units=metric&mode="+mode; if (isAlternative) url += "&alternatives=true"; Log.e("getUrl", url); return url; } public Document getDocument(LatLng start, LatLng end, String mode) { String url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.latitude + "," + end.longitude + "&sensor=false&units=metric&mode=driving"; // String url = "http://maps.googleapis.com/maps/api/directions/xml?" // + "origin=" + start.latitude + "," + start.longitude // + "&destination=" + end.latitude + "," + end.longitude // + "&sensor=false&units=metric&mode=driving"+"alternatives=true"; url = url.replace(" ", "+"); Log.e("URL", url); try { URL ur = new URL(url); URLConnection connection = ur.openConnection(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(connection.getInputStream()); return doc; } catch (Exception e) { e.printStackTrace(); } return null; } public Document getDocument(String origin, String destination, String mode) { String url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + origin + "&destination=" + destination + "&sensor=false&units=metric&mode=driving"; url = url.replace(" ", "+"); Log.e("Query URL", url); try { URL ur = new URL(url); URLConnection connection = ur.openConnection(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(connection.getInputStream()); return doc; } catch (Exception e) { e.printStackTrace(); } return null; } public String getDurationText(Document doc) { NodeList nl1 = doc.getElementsByTagName("duration"); Node node1 = nl1.item(0); NodeList nl2 = node1.getChildNodes(); Node node2 = nl2.item(getNodeIndex(nl2, "text")); Log.i("DurationText", node2.getTextContent()); return node2.getTextContent(); } public int getDurationValue(Document doc) { NodeList nl1 = doc.getElementsByTagName("duration"); Node node1 = nl1.item(0); NodeList nl2 = node1.getChildNodes(); Node node2 = nl2.item(getNodeIndex(nl2, "value")); Log.i("DurationValue", node2.getTextContent()); return Integer.parseInt(node2.getTextContent()); } public String getDistanceText(Document doc) { NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 = nl1.item(0); NodeList nl2 = node1.getChildNodes(); Node node2 = nl2.item(getNodeIndex(nl2, "text")); Log.i("DistanceText", node2.getTextContent()); return node2.getTextContent(); } public int getDistanceValue(Document doc) { NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 = nl1.item(0); NodeList nl2 = node1.getChildNodes(); Node node2 = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue", node2.getTextContent()); return Integer.parseInt(node2.getTextContent()); } public List<Float> getDistanceValueInMeters(Document doc) { List<Float> list = new ArrayList<Float>(); NodeList nl1 = doc.getElementsByTagName("distance"); for (int x = 0; x < nl1.getLength(); x++) { Node node1 = nl1.item(x); NodeList nl2 = node1.getChildNodes(); Node node2 = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue", node2.getTextContent()); float val = Integer.parseInt(node2.getTextContent()); list.add(val); } return list; } public String getStartAddress(Document doc) { NodeList nl1 = doc.getElementsByTagName("start_address"); Node node1 = nl1.item(0); Log.i("StartAddress", node1.getTextContent()); return node1.getTextContent(); } public String getEndAddress(Document doc) { NodeList nl1 = doc.getElementsByTagName("end_address"); Node node1 = nl1.item(0); Log.i("StartAddress", node1.getTextContent()); return node1.getTextContent(); } public String getCopyRights(Document doc) { NodeList nl1 = doc.getElementsByTagName("copyrights"); Node node1 = nl1.item(0); Log.i("CopyRights", node1.getTextContent()); return node1.getTextContent(); } public LatLng getStartLocation(Document doc) { NodeList nl1 = doc.getElementsByTagName("start_location"); Node node1 = nl1.item(0); NodeList nl2 = node1.getChildNodes(); Node node2 = nl2.item(getNodeIndex(nl2, "lat")); Node node21 = nl2.item(getNodeIndex(nl2, "lng")); Log.i("DistanceValue", node2.getTextContent()); return new LatLng(Float.parseFloat(node2.getTextContent()), Float.parseFloat(node21.getTextContent())); } public LatLng getEndLocation(Document doc) { NodeList nl1 = doc.getElementsByTagName("end_location"); Node node1 = nl1.item(0); NodeList nl2 = node1.getChildNodes(); Node node2 = nl2.item(getNodeIndex(nl2, "lat")); Node node21 = nl2.item(getNodeIndex(nl2, "lng")); Log.i("DistanceValue", node2.getTextContent()); return new LatLng(Float.parseFloat(node2.getTextContent()), Float.parseFloat(node21.getTextContent())); } public ArrayList<LatLng> getDirection(Document doc) { NodeList nl1, nl2, nl3; ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>(); nl1 = doc.getElementsByTagName("step"); if (nl1.getLength() > 0) { for (int i = 0; i < nl1.getLength(); i++) { Node node1 = nl1.item(i); nl2 = node1.getChildNodes(); Node locationNode = nl2.item(getNodeIndex(nl2, "start_location")); nl3 = locationNode.getChildNodes(); Node latNode = nl3.item(getNodeIndex(nl3, "lat")); double lat = Double.parseDouble(latNode.getTextContent()); Node lngNode = nl3.item(getNodeIndex(nl3, "lng")); double lng = Double.parseDouble(lngNode.getTextContent()); listGeopoints.add(new LatLng(lat, lng)); locationNode = nl2.item(getNodeIndex(nl2, "polyline")); nl3 = locationNode.getChildNodes(); latNode = nl3.item(getNodeIndex(nl3, "points")); ArrayList<LatLng> arr = decodePoly(latNode.getTextContent()); for (int j = 0; j < arr.size(); j++) { listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude)); } locationNode = nl2.item(getNodeIndex(nl2, "end_location")); nl3 = locationNode.getChildNodes(); latNode = nl3.item(getNodeIndex(nl3, "lat")); lat = Double.parseDouble(latNode.getTextContent()); lngNode = nl3.item(getNodeIndex(nl3, "lng")); lng = Double.parseDouble(lngNode.getTextContent()); listGeopoints.add(new LatLng(lat, lng)); } } return listGeopoints; } public ArrayList<Direction> getDirections(Document doc) { NodeList nl1, nl2, nl3; ArrayList<Direction> listDirections = new ArrayList<Direction>(); nl1 = doc.getElementsByTagName("step"); if (nl1.getLength() > 0) { for (int i = 0; i < nl1.getLength(); i++) { Direction d = new Direction(); Node node1 = nl1.item(i); nl2 = node1.getChildNodes(); Node locationNode = nl2.item(getNodeIndex(nl2, "duration")); nl3 = locationNode.getChildNodes(); Node latNode = nl3.item(getNodeIndex(nl3, "text")); d.durationText = latNode.getTextContent(); locationNode = nl2.item(getNodeIndex(nl2, "html_instructions")); d.html_instructions = locationNode.getTextContent(); locationNode = nl2.item(getNodeIndex(nl2, "distance")); nl3 = locationNode.getChildNodes(); latNode = nl3.item(getNodeIndex(nl3, "text")); d.distanceText = latNode.getTextContent(); listDirections.add(d); } } return listDirections; } private int getNodeIndex(NodeList nl, String nodename) { for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equals(nodename)) return i; } return -1; } private ArrayList<LatLng> decodePoly(String encoded) { ArrayList<LatLng> poly = new ArrayList<LatLng>(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5); poly.add(position); } return poly; } }
77530ba2043d637f0828bdc69da7444365f2cf15
6ff30eff6b44d5d1fb2aa9119e3d8ad564493e20
/ch01/src/main/java/sorting/StringSorter.java
133afa25141020305c62184ed28c18ca94a90e96
[]
no_license
gbagony-zyxy/groovy-script
37eaa58f57ce1451f7cdf85051d970c4b188bdd0
d248891af82fa36fd2712fd01e90800c131b76e8
refs/heads/master
2021-01-22T02:43:13.688198
2017-03-27T09:53:35
2017-03-27T09:53:35
81,068,906
0
0
null
null
null
null
UTF-8
Java
false
false
665
java
package sorting; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by gbagony on 2017/2/6. */ public class StringSorter { //通过字母表排序 public List<String> sortLexicographically(List<String> strings) { Collections.sort(strings); return strings; } //通过字符串长度排序 public List<String> sortByDecreasingLength(List<String> strings) { Collections.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { return s2.length() - s1.length(); } }); return strings; } }
855621b9a7342e048f0b6f9077dbfee33e12259d
55ee47ff8746af6bb89fd0fdd21a801f61746b40
/JiechengSum.java
16b20ab3811198ba7c79aa680ad76370a0313f99
[]
no_license
guoxinyu/JiechengSum
d3ff5b7bc3c35e26780b612024a32fa7b0068f53
421771fd7968c66af227a7d15eb2701b26b76554
refs/heads/master
2016-09-09T19:44:25.287926
2014-08-10T07:41:57
2014-08-10T07:41:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
359
java
public class JiechengSum { public static void main(String[] args) { // TODO Auto-generated method stub int start = 1; int result = 0; int sum = 1; int n = 10; for(int i=start; i<=n; i++) { for(int j=1; j<=i; j++) { sum*=j; } result += sum; sum = 1; } System.out.println("result= "+result); } }
503153c3056100320c1f48c3b3b66a6d1764a595
638c5f3953f1dc69237ba9ee8da3090f2e0fd0a4
/Java/src/dwlab/shapes/sprites/Wedge.java
44e06d83f91ebfceff8d70404fd816b78e0bdf44
[]
no_license
BlitzMaxModules/dwlab.mod
952ccabdcf4bf6812ed2fa6fe702f5584ee02398
3f57c7e9660a117a979fc48e0869e9bf6dccb70c
refs/heads/master
2016-09-05T14:41:31.612467
2013-03-28T07:07:26
2013-03-28T07:07:26
2,295,354
0
0
null
null
null
null
UTF-8
Java
false
false
10,240
java
/* Digital Wizard's Lab - game development framework * Copyright (C) 2012, Matt Merkulov * All rights reserved. Use of this code is allowed under the * Artistic License 2.0 terms, as specified in the license.txt * file distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ package dwlab.shapes.sprites; import dwlab.base.Service; import dwlab.shapes.Line; import dwlab.base.Vector; import dwlab.shapes.sprites.Sprite.ShapeType; public class Wedge { private static Vector serviceVector1 = new Vector(); private static Vector serviceVector2 = new Vector(); private static Sprite servicePivots[] = { new Sprite(), new Sprite(), new Sprite(), new Sprite() }; private static Sprite serviceOval1 = new Sprite( ShapeType.OVAL ); private static Sprite serviceOval2 = new Sprite( ShapeType.OVAL ); private static Line serviceLines[] = { new Line(), new Line(), new Line() }; public static void pivotAndOval( Sprite pivot, Sprite oval, Vector impulse ) { oval = oval.toCircle( pivot, serviceOval1 ); double k = 0.5 * oval.getDiameter() / oval.distanceTo( pivot ) - 1.0; impulse.x = ( pivot.getX() - oval.getX() ) * k; impulse.y = ( pivot.getY() - oval.getY() ) * k; } public static void pivotAndRectangle( Sprite pivot, Sprite rectangle, Vector impulse ) { if( Math.abs( pivot.getY() - rectangle.getY() ) * rectangle.getWidth() >= Math.abs( pivot.getX() - rectangle.getX() ) * rectangle.getHeight() ) { impulse.y = rectangle.getY() + 0.5 * rectangle.getHeight() * Math.signum( pivot.getY() - rectangle.getY() ) - pivot.getY(); } else { impulse.x = rectangle.getX() + 0.5 * rectangle.getWidth() * Math.signum( pivot.getX() - rectangle.getX() ) - pivot.getX(); } } public static void pivotAndTriangle( Sprite pivot, Sprite triangle, Vector impulse ) { impulse.y = serviceLines[ 0 ].getY( pivot.getX() ) - pivot.getY(); pivotAndRectangle( pivot, triangle, serviceVector1 ); if( Service.distance2( serviceVector1.x, serviceVector1.y ) < serviceVector1.y * serviceVector1.y ) { impulse.x = serviceVector1.x; impulse.y = serviceVector1.y; } } public static void ovalAndOval( Sprite oval1, Sprite oval2, Vector impulse ) { oval1 = oval1.toCircle( oval2, serviceOval1 ); oval2 = oval2.toCircle( oval1, serviceOval2 ); double k = 0.5 * ( oval1.getWidth() + oval2.getWidth() ) / oval1.distanceTo( oval2 ) - 1.0; impulse.x = ( oval1.getX() - oval2.getX() ) * k; impulse.y = ( oval1.getY() - oval2.getY() ) * k; } public static void ovalAndRectangle( Sprite oval, Sprite rectangle, Vector impulse ) { boolean a = ( Math.abs( oval.getY() - rectangle.getY() ) * rectangle.getWidth() >= Math.abs( oval.getX() - rectangle.getX() ) * rectangle.getHeight() ); if( ( oval.getX() > rectangle.leftX() && oval.getX() < rectangle.rightX() ) && a ) { impulse.x = 0; impulse.y = ( 0.5 * ( rectangle.getHeight() + oval.getHeight() ) - Math.abs( rectangle.getY() - oval.getY() ) ) * Math.signum( oval.getY() - rectangle.getY() ); } else if( oval.getY() > rectangle.topY() && oval.getY() < rectangle.bottomY() && ! a ) { impulse.x = ( 0.5 * ( rectangle.getWidth() + oval.getWidth() ) - Math.abs( rectangle.getX() - oval.getX() ) ) * Math.signum( oval.getX() - rectangle.getX() ); impulse.y = 0; } else { servicePivots[ 0 ].setCoords( rectangle.getX() + 0.5 * rectangle.getWidth() * Math.signum( oval.getX() - rectangle.getX() ), rectangle.getY() + 0.5 * rectangle.getHeight() * Math.signum( oval.getY() - rectangle.getY() ) ); oval = oval.toCircle( servicePivots[ 0 ], serviceOval1 ); double k = 1.0 - 0.5 * oval.getWidth() / oval.distanceTo( servicePivots[ 0 ] ); impulse.x = ( servicePivots[ 0 ].getX() - oval.getX() ) * k; impulse.y = ( servicePivots[ 0 ].getY() - oval.getY() ) * k; } } public static void ovalAndTriangle( Sprite oval, Sprite triangle, Vector impulse ) { triangle.getRightAngleVertex( servicePivots[ 2 ] ); triangle.getOtherVertices( servicePivots[ 0 ], servicePivots[ 1 ] ); serviceOval1 = oval.toCircle( servicePivots[ 2 ], serviceOval1 ); double vDistance = 0.5 * Service.distance( triangle.getWidth(), triangle.getHeight() ) * serviceOval1.getWidth() / triangle.getWidth(); double dHeight = 0.5 * ( oval.getHeight() - serviceOval1.getHeight() ); double dDX = 0.5 * serviceOval1.getWidth() / vDistance * Service.cathetus( vDistance, 0.5 * serviceOval1.getWidth() ); double dir = -1d; if( triangle.shapeType == ShapeType.BOTTOM_LEFT_TRIANGLE || triangle.shapeType == ShapeType.BOTTOM_RIGHT_TRIANGLE ) dir = 1d; if( triangle.shapeType == ShapeType.TOP_RIGHT_TRIANGLE || triangle.shapeType == ShapeType.BOTTOM_RIGHT_TRIANGLE ) dDX = -dDX; if( serviceOval1.getX() < triangle.leftX() + dDX ) { impulse.y = servicePivots[ 0 ].getY() - dir * Service.cathetus( serviceOval1.getWidth() * 0.5, serviceOval1.getX() - servicePivots[ 0 ].getX() ) - serviceOval1.getY(); } else if( serviceOval1.getX() > triangle.rightX() + dDX ) { impulse.y = servicePivots[ 1 ].getY() - dir * Service.cathetus( serviceOval1.getWidth() * 0.5, serviceOval1.getX() - servicePivots[ 1 ].getX() ) - serviceOval1.getY(); } else { impulse.y = serviceLines[ 0 ].getY( serviceOval1.getX() ) - dir * ( vDistance + dHeight ) - oval.getY(); } ovalAndRectangle( oval, triangle, serviceVector1 ); if( Service.distance2( serviceVector1.x, serviceVector1.y ) < impulse.y * impulse.y ) { impulse.x = serviceVector1.x; impulse.y = serviceVector1.y; } } public static void rectangleAndRectangle( Sprite rectangle1, Sprite rectangle2, Vector impulse ) { impulse.x = 0.5 * ( rectangle1.getWidth() + rectangle2.getWidth() ) - Math.abs( rectangle1.getX() - rectangle2.getX() ); impulse.y = 0.5 * ( rectangle1.getHeight() + rectangle2.getHeight() ) - Math.abs( rectangle1.getY() - rectangle2.getY() ); if( impulse.x < impulse.y ) { impulse.x *= Math.signum( rectangle1.getX() - rectangle2.getX() ); impulse.y = 0; } else { impulse.x = 0; impulse.y *= Math.signum( rectangle1.getY() - rectangle2.getY() ); } } public static void rectangleAndTriangle( Sprite rectangle, Sprite triangle, Vector impulse ) { double x; if( triangle.shapeType == ShapeType.TOP_LEFT_TRIANGLE || triangle.shapeType == ShapeType.BOTTOM_LEFT_TRIANGLE ) { x = rectangle.leftX(); } else { x = rectangle.rightX(); } triangle.getHypotenuse( serviceLines[ 0 ] ); if( triangle.shapeType == ShapeType.TOP_LEFT_TRIANGLE || triangle.shapeType == ShapeType.TOP_RIGHT_TRIANGLE ) { impulse.y = Math.min( serviceLines[ 0 ].getY( x ), triangle.bottomY() ) - rectangle.topY(); } else { impulse.y = Math.max( serviceLines[ 0 ].getY( x ), triangle.topY() ) - rectangle.bottomY(); } rectangleAndRectangle( rectangle, triangle, serviceVector1 ); if( Service.distance2( serviceVector1.x, serviceVector1.y ) < impulse.y * impulse.y ) { impulse.x = serviceVector1.x; impulse.y = serviceVector1.y; } } public static double popAngle( Sprite triangle1, Sprite triangle2, double dY ) { triangle2.getRightAngleVertex( servicePivots[ 0 ] ); triangle2.getHypotenuse( serviceLines[ 0 ] ); triangle1.getOtherVertices( servicePivots[ 1 ], servicePivots[ 2 ] ); int o = serviceLines[ 0 ].pivotOrientation( servicePivots[ 0 ] ); for( int n=1; n <= 2; n++ ) { if( o == serviceLines[ 0 ].pivotOrientation( servicePivots[ n ] ) ) { if( Service.inLimits( servicePivots[ n ].getX(), triangle2.leftX(), triangle2.rightX() ) ) { return Math.max( dY, Math.abs( serviceLines[ 0 ].getY( servicePivots[ n ].getX() ) - servicePivots[ n ].getY() ) ); } } } return dY; } public static void triangleAndTriangle( Sprite triangle1, Sprite triangle2, Vector impulse ) { rectangleAndTriangle( triangle1, triangle2, serviceVector1 ); double d1 = serviceVector1.length2(); rectangleAndTriangle( triangle2, triangle1, serviceVector2 ); double d2 = serviceVector2.length2(); cycle: while( true ) { switch( triangle1.shapeType ) { case TOP_LEFT_TRIANGLE: if( triangle2.shapeType != ShapeType.BOTTOM_RIGHT_TRIANGLE ) break cycle; break; case TOP_RIGHT_TRIANGLE: if( triangle2.shapeType != ShapeType.BOTTOM_LEFT_TRIANGLE ) break cycle; break; case BOTTOM_LEFT_TRIANGLE: if( triangle2.shapeType != ShapeType.TOP_RIGHT_TRIANGLE ) break cycle; break; case BOTTOM_RIGHT_TRIANGLE: if( triangle2.shapeType != ShapeType.TOP_LEFT_TRIANGLE ) break cycle; break; } double dY3 = 0; dY3 = popAngle( triangle1, triangle2, dY3 ); dY3 = popAngle( triangle2, triangle1, dY3 ); if( dY3 == 0 ) break; double dY32 = dY3 * dY3; if( dY32 < d1 && dY32 < d2 ) { triangle1.getRightAngleVertex( servicePivots[ 0 ] ); triangle2.getRightAngleVertex( servicePivots[ 1 ] ); impulse.x = 0; impulse.y = dY3 * Math.signum( servicePivots[ 0 ].getY() - servicePivots[ 1 ].getY() ); return; } else { break; } } if( d1 < d2 ) { impulse.x = serviceVector1.x; impulse.y = serviceVector1.y; } else { impulse.x = -serviceVector2.x; impulse.y = -serviceVector2.y; } } public static void separate( Sprite pivot1, Sprite pivot2, Vector impulse, double pivot1movingResistance, double pivot2movingResistance ) { if( pivot1movingResistance < 0 ) { if( pivot2movingResistance < 0 ) return; pivot1movingResistance = 1.0; pivot2movingResistance = 0.0; } else if( pivot2movingResistance < 0 ) { pivot1movingResistance = 0.0; pivot2movingResistance = 1.0; } double k1, k2; double movingResistanceSum = pivot1movingResistance + pivot2movingResistance; if( movingResistanceSum != 0 ) { k1 = pivot2movingResistance / movingResistanceSum; k2 = pivot1movingResistance / movingResistanceSum; } else { k1 = 0.5d; k2 = 0.5d; } if( k1 != 0.0 ) pivot1.alterCoords( k1 * impulse.x, k1 * impulse.y ); if( k2 != 0.0 ) pivot2.alterCoords( -k2 * impulse.x, -k2 * impulse.y ); } }
[ "[email protected]@1f63a6fe-6007-92bf-7612-2633ac8b7beb" ]
[email protected]@1f63a6fe-6007-92bf-7612-2633ac8b7beb
8b18382316bf463e3f7152c05475a04f06e3a689
661137624f53f2911437aa4fb32fce871d98f3be
/src/main/java/com/voquz/vcrawl/config/DatabaseConfiguration.java
072ac5ee2d0b4519aed365dea8c4f8835f141576
[]
no_license
alinturbut/vcrawl
d660eb4387df6f1f333422a1ace440fd74c3aa50
c13cf0341974592af6d0d143b5f6be2ed87275cc
refs/heads/master
2020-04-10T07:30:03.659756
2016-02-23T13:38:43
2016-02-23T13:38:43
52,267,686
0
0
null
null
null
null
UTF-8
Java
false
false
5,417
java
package com.voquz.vcrawl.config; import com.voquz.vcrawl.config.liquibase.AsyncSpringLiquibase; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.context.ApplicationContextException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.inject.Inject; import javax.sql.DataSource; import java.util.Arrays; @Configuration @EnableJpaRepositories("com.voquz.vcrawl.repository") @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement public class DatabaseConfiguration { private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); @Inject private Environment env; @Autowired(required = false) private MetricRegistry metricRegistry; @Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}") public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) { log.debug("Configuring Datasource"); if (dataSourceProperties.getUrl() == null) { log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles())); throw new ApplicationContextException("Database connection pool is not configured correctly"); } HikariConfig config = new HikariConfig(); config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", dataSourceProperties.getUrl()); if (dataSourceProperties.getUsername() != null) { config.addDataSourceProperty("user", dataSourceProperties.getUsername()); } else { config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user } if (dataSourceProperties.getPassword() != null) { config.addDataSourceProperty("password", dataSourceProperties.getPassword()); } else { config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password } //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) { config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts()); config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize()); config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit()); } if (metricRegistry != null) { config.setMetricRegistry(metricRegistry); } return new HikariDataSource(config); } @Bean public SpringLiquibase liquibase(DataSource dataSource, DataSourceProperties dataSourceProperties, LiquibaseProperties liquibaseProperties) { // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously SpringLiquibase liquibase = new AsyncSpringLiquibase(); liquibase.setDataSource(dataSource); liquibase.setChangeLog("classpath:config/liquibase/master.xml"); liquibase.setContexts(liquibaseProperties.getContexts()); liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); liquibase.setDropFirst(liquibaseProperties.isDropFirst()); liquibase.setShouldRun(liquibaseProperties.isEnabled()); if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) { if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourceProperties.getDriverClassName())) { liquibase.setShouldRun(true); log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST); } else { liquibase.setShouldRun(false); } } else { log.debug("Configuring Liquibase"); } return liquibase; } @Bean public Hibernate4Module hibernate4Module() { return new Hibernate4Module(); } }
fa3a0d427d83ba2d69a93a692621ac41aaaf597b
ed3cb95dcc590e98d09117ea0b4768df18e8f99e
/project_1_3/src/b/c/a/g/Calc_1_3_12065.java
01a02a9db9895f41708e12e53a5d3d4114d90365
[]
no_license
chalstrick/bigRepo1
ac7fd5785d475b3c38f1328e370ba9a85a751cff
dad1852eef66fcec200df10083959c674fdcc55d
refs/heads/master
2016-08-11T17:59:16.079541
2015-12-18T14:26:49
2015-12-18T14:26:49
48,244,030
0
0
null
null
null
null
UTF-8
Java
false
false
134
java
package b.c.a.g; public class Calc_1_3_12065 { /** @return the sum of a and b */ public int add(int a, int b) { return a+b; } }
1e4bea5539bcc26f9158627a83f009c589ca8949
c17dab4c9618fff30c37f23afe87321aba70f9e2
/technical/src/main/java/technicaltest/com/TechnicalApplication.java
8a5453330ff89e01b8577c21f2bc785d2aa1681a
[]
no_license
ssavess/taskmanage
314c9470a5ebd1229be737bbf98bcdb9767c901b
ed7ee72dc49f92e73330fd7c515faa40021913d1
refs/heads/master
2021-05-15T22:55:25.546436
2017-10-12T22:52:53
2017-10-12T22:52:53
106,751,967
0
0
null
null
null
null
UTF-8
Java
false
false
315
java
package technicaltest.com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TechnicalApplication { public static void main(String[] args) { SpringApplication.run(TechnicalApplication.class, args); } }
91afc06f0f3c13a82ed7237fbc9da262d78e861a
d7c5121237c705b5847e374974b39f47fae13e10
/airspan.netspan/src/main/java/Netspan/NBI_16_0/Software/SoftwareStatusGet.java
2105c3a85508877068c8d91488368260c9f734cd
[]
no_license
AirspanNetworks/SWITModules
8ae768e0b864fa57dcb17168d015f6585d4455aa
7089a4b6456621a3abd601cc4592d4b52a948b57
refs/heads/master
2022-11-24T11:20:29.041478
2020-08-09T07:20:03
2020-08-09T07:20:03
184,545,627
1
0
null
2022-11-16T12:35:12
2019-05-02T08:21:55
Java
UTF-8
Java
false
false
1,909
java
package Netspan.NBI_16_0.Software; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="NodeName" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "nodeName" }) @XmlRootElement(name = "SoftwareStatusGet") public class SoftwareStatusGet { @XmlElement(name = "NodeName") protected List<String> nodeName; /** * Gets the value of the nodeName property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nodeName property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNodeName().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNodeName() { if (nodeName == null) { nodeName = new ArrayList<String>(); } return this.nodeName; } }
[ "build.Airspan.com" ]
build.Airspan.com
8c2e32436d1f0da683c3c2d821712cbed73d18dc
30959f823c2fd11df46a4937e5a0cdb001da1298
/app/src/main/java/com/vsga/login/LoginActivity.java
8fcb7d8d286d1f3594b90c5f4a6fa5aae4d8922d
[]
no_license
raditya021/login
2ecd0f15331a8bba7494c7e6eac3cfe5fc0b050f
b992cca892ebde9c3503cb462ef7129859323c67
refs/heads/master
2023-07-11T09:23:49.472729
2021-08-16T14:00:48
2021-08-16T14:00:48
396,819,832
0
0
null
null
null
null
UTF-8
Java
false
false
3,291
java
package com.vsga.login; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; public class LoginActivity extends AppCompatActivity { public static final String FILENAME = "login"; EditText editUsername, editPassword; Button btnLogin, btnRegister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); editUsername = findViewById(R.id.editUsername); editPassword = findViewById(R.id.editPassword); btnLogin = findViewById(R.id.action_login); btnRegister = findViewById(R.id.action_register); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view){ simpanFileLogin(); } }); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(intent); } }); } void simpanFileLogin(){ String isiFile = editUsername.getText().toString() + ";" + editPassword.getText().toString(); File file = new File(getFilesDir(),FILENAME); FileOutputStream outputStream = null; try { file.createNewFile(); outputStream = new FileOutputStream(file, false); outputStream.write(isiFile.getBytes()); outputStream.flush(); outputStream.close(); }catch (Exception e){ e.printStackTrace(); } Toast.makeText(this, "Login Berhasil", Toast.LENGTH_SHORT).show(); void login{ File sdcard = getFilesDir(); File file1 = new File(sdcard, editUsername.getText().toString()); if (file.exists()){ StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line = br.readLine(); while (line != null){ text.append(line); line = br.readLine(); } br.close(); }catch (Exception e){ System.out.println("Error " + e.getMessage()); } String data = text.toString(); String[] dataUser = data.split(";"); if (dataUser[1].equals(editPassword.getText().toString())) simpanFileLogin(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); }else{ Toast.makeText(this, "Password Tidak Sesuai", Toast.LENGTH_SHORT).show(); } } } }
3d735c153c5481140ac0753a40030c565627f4f3
730aca6c9a87ad0c1c72075f4b01656d3020afac
/example3/Java/com/ihaiu/test/BookOuterClass.java
7867d5886e6f9bb773bb5dea48df06e529be5455
[]
no_license
ihaiucom/protobuff
b6caeb682072a9b22d8070752dcf91d1f2eca832
d1cf04fd7de8ba8bcfa7e5541ae92162e5314fda
refs/heads/master
2020-07-05T14:43:25.622068
2016-11-18T09:33:25
2016-11-18T09:33:25
74,114,896
0
0
null
null
null
null
UTF-8
Java
false
true
26,491
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: book.proto package com.ihaiu.test; public final class BookOuterClass { private BookOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface BookOrBuilder extends // @@protoc_insertion_point(interface_extends:google.protobuf.Book) com.google.protobuf.MessageOrBuilder { /** * <code>optional int32 id = 1;</code> */ int getId(); /** * <code>optional string name = 2;</code> */ java.lang.String getName(); /** * <code>optional string name = 2;</code> */ com.google.protobuf.ByteString getNameBytes(); /** * <code>optional .BookTag tag = 3;</code> */ boolean hasTag(); /** * <code>optional .BookTag tag = 3;</code> */ com.ihaiu.test.Booktag.BookTag getTag(); /** * <code>optional .BookTag tag = 3;</code> */ com.ihaiu.test.Booktag.BookTagOrBuilder getTagOrBuilder(); } /** * Protobuf type {@code google.protobuf.Book} */ public static final class Book extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.protobuf.Book) BookOrBuilder { // Use Book.newBuilder() to construct. private Book(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Book() { id_ = 0; name_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private Book( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 8: { id_ = input.readInt32(); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 26: { com.ihaiu.test.Booktag.BookTag.Builder subBuilder = null; if (tag_ != null) { subBuilder = tag_.toBuilder(); } tag_ = input.readMessage(com.ihaiu.test.Booktag.BookTag.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(tag_); tag_ = subBuilder.buildPartial(); } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.ihaiu.test.BookOuterClass.internal_static_google_protobuf_Book_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.ihaiu.test.BookOuterClass.internal_static_google_protobuf_Book_fieldAccessorTable .ensureFieldAccessorsInitialized( com.ihaiu.test.BookOuterClass.Book.class, com.ihaiu.test.BookOuterClass.Book.Builder.class); } public static final int ID_FIELD_NUMBER = 1; private int id_; /** * <code>optional int32 id = 1;</code> */ public int getId() { return id_; } public static final int NAME_FIELD_NUMBER = 2; private volatile java.lang.Object name_; /** * <code>optional string name = 2;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <code>optional string name = 2;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TAG_FIELD_NUMBER = 3; private com.ihaiu.test.Booktag.BookTag tag_; /** * <code>optional .BookTag tag = 3;</code> */ public boolean hasTag() { return tag_ != null; } /** * <code>optional .BookTag tag = 3;</code> */ public com.ihaiu.test.Booktag.BookTag getTag() { return tag_ == null ? com.ihaiu.test.Booktag.BookTag.getDefaultInstance() : tag_; } /** * <code>optional .BookTag tag = 3;</code> */ public com.ihaiu.test.Booktag.BookTagOrBuilder getTagOrBuilder() { return getTag(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (id_ != 0) { output.writeInt32(1, id_); } if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, name_); } if (tag_ != null) { output.writeMessage(3, getTag()); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (id_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, id_); } if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, name_); } if (tag_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, getTag()); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.ihaiu.test.BookOuterClass.Book)) { return super.equals(obj); } com.ihaiu.test.BookOuterClass.Book other = (com.ihaiu.test.BookOuterClass.Book) obj; boolean result = true; result = result && (getId() == other.getId()); result = result && getName() .equals(other.getName()); result = result && (hasTag() == other.hasTag()); if (hasTag()) { result = result && getTag() .equals(other.getTag()); } return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptorForType().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (hasTag()) { hash = (37 * hash) + TAG_FIELD_NUMBER; hash = (53 * hash) + getTag().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.ihaiu.test.BookOuterClass.Book parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.ihaiu.test.BookOuterClass.Book parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.ihaiu.test.BookOuterClass.Book parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.ihaiu.test.BookOuterClass.Book parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.ihaiu.test.BookOuterClass.Book parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.ihaiu.test.BookOuterClass.Book parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.ihaiu.test.BookOuterClass.Book parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.ihaiu.test.BookOuterClass.Book parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.ihaiu.test.BookOuterClass.Book parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.ihaiu.test.BookOuterClass.Book parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.ihaiu.test.BookOuterClass.Book prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code google.protobuf.Book} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.protobuf.Book) com.ihaiu.test.BookOuterClass.BookOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.ihaiu.test.BookOuterClass.internal_static_google_protobuf_Book_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.ihaiu.test.BookOuterClass.internal_static_google_protobuf_Book_fieldAccessorTable .ensureFieldAccessorsInitialized( com.ihaiu.test.BookOuterClass.Book.class, com.ihaiu.test.BookOuterClass.Book.Builder.class); } // Construct using com.ihaiu.test.BookOuterClass.Book.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); id_ = 0; name_ = ""; if (tagBuilder_ == null) { tag_ = null; } else { tag_ = null; tagBuilder_ = null; } return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.ihaiu.test.BookOuterClass.internal_static_google_protobuf_Book_descriptor; } public com.ihaiu.test.BookOuterClass.Book getDefaultInstanceForType() { return com.ihaiu.test.BookOuterClass.Book.getDefaultInstance(); } public com.ihaiu.test.BookOuterClass.Book build() { com.ihaiu.test.BookOuterClass.Book result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.ihaiu.test.BookOuterClass.Book buildPartial() { com.ihaiu.test.BookOuterClass.Book result = new com.ihaiu.test.BookOuterClass.Book(this); result.id_ = id_; result.name_ = name_; if (tagBuilder_ == null) { result.tag_ = tag_; } else { result.tag_ = tagBuilder_.build(); } onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.ihaiu.test.BookOuterClass.Book) { return mergeFrom((com.ihaiu.test.BookOuterClass.Book)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.ihaiu.test.BookOuterClass.Book other) { if (other == com.ihaiu.test.BookOuterClass.Book.getDefaultInstance()) return this; if (other.getId() != 0) { setId(other.getId()); } if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (other.hasTag()) { mergeTag(other.getTag()); } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.ihaiu.test.BookOuterClass.Book parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.ihaiu.test.BookOuterClass.Book) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int id_ ; /** * <code>optional int32 id = 1;</code> */ public int getId() { return id_; } /** * <code>optional int32 id = 1;</code> */ public Builder setId(int value) { id_ = value; onChanged(); return this; } /** * <code>optional int32 id = 1;</code> */ public Builder clearId() { id_ = 0; onChanged(); return this; } private java.lang.Object name_ = ""; /** * <code>optional string name = 2;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string name = 2;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string name = 2;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <code>optional string name = 2;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>optional string name = 2;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private com.ihaiu.test.Booktag.BookTag tag_ = null; private com.google.protobuf.SingleFieldBuilderV3< com.ihaiu.test.Booktag.BookTag, com.ihaiu.test.Booktag.BookTag.Builder, com.ihaiu.test.Booktag.BookTagOrBuilder> tagBuilder_; /** * <code>optional .BookTag tag = 3;</code> */ public boolean hasTag() { return tagBuilder_ != null || tag_ != null; } /** * <code>optional .BookTag tag = 3;</code> */ public com.ihaiu.test.Booktag.BookTag getTag() { if (tagBuilder_ == null) { return tag_ == null ? com.ihaiu.test.Booktag.BookTag.getDefaultInstance() : tag_; } else { return tagBuilder_.getMessage(); } } /** * <code>optional .BookTag tag = 3;</code> */ public Builder setTag(com.ihaiu.test.Booktag.BookTag value) { if (tagBuilder_ == null) { if (value == null) { throw new NullPointerException(); } tag_ = value; onChanged(); } else { tagBuilder_.setMessage(value); } return this; } /** * <code>optional .BookTag tag = 3;</code> */ public Builder setTag( com.ihaiu.test.Booktag.BookTag.Builder builderForValue) { if (tagBuilder_ == null) { tag_ = builderForValue.build(); onChanged(); } else { tagBuilder_.setMessage(builderForValue.build()); } return this; } /** * <code>optional .BookTag tag = 3;</code> */ public Builder mergeTag(com.ihaiu.test.Booktag.BookTag value) { if (tagBuilder_ == null) { if (tag_ != null) { tag_ = com.ihaiu.test.Booktag.BookTag.newBuilder(tag_).mergeFrom(value).buildPartial(); } else { tag_ = value; } onChanged(); } else { tagBuilder_.mergeFrom(value); } return this; } /** * <code>optional .BookTag tag = 3;</code> */ public Builder clearTag() { if (tagBuilder_ == null) { tag_ = null; onChanged(); } else { tag_ = null; tagBuilder_ = null; } return this; } /** * <code>optional .BookTag tag = 3;</code> */ public com.ihaiu.test.Booktag.BookTag.Builder getTagBuilder() { onChanged(); return getTagFieldBuilder().getBuilder(); } /** * <code>optional .BookTag tag = 3;</code> */ public com.ihaiu.test.Booktag.BookTagOrBuilder getTagOrBuilder() { if (tagBuilder_ != null) { return tagBuilder_.getMessageOrBuilder(); } else { return tag_ == null ? com.ihaiu.test.Booktag.BookTag.getDefaultInstance() : tag_; } } /** * <code>optional .BookTag tag = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.ihaiu.test.Booktag.BookTag, com.ihaiu.test.Booktag.BookTag.Builder, com.ihaiu.test.Booktag.BookTagOrBuilder> getTagFieldBuilder() { if (tagBuilder_ == null) { tagBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.ihaiu.test.Booktag.BookTag, com.ihaiu.test.Booktag.BookTag.Builder, com.ihaiu.test.Booktag.BookTagOrBuilder>( getTag(), getParentForChildren(), isClean()); tag_ = null; } return tagBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } // @@protoc_insertion_point(builder_scope:google.protobuf.Book) } // @@protoc_insertion_point(class_scope:google.protobuf.Book) private static final com.ihaiu.test.BookOuterClass.Book DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.ihaiu.test.BookOuterClass.Book(); } public static com.ihaiu.test.BookOuterClass.Book getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Book> PARSER = new com.google.protobuf.AbstractParser<Book>() { public Book parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Book(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Book> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Book> getParserForType() { return PARSER; } public com.ihaiu.test.BookOuterClass.Book getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_google_protobuf_Book_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_protobuf_Book_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\nbook.proto\022\017google.protobuf\032\rbooktag.p" + "roto\"7\n\004Book\022\n\n\002id\030\001 \001(\005\022\014\n\004name\030\002 \001(\t\022\025" + "\n\003tag\030\003 \001(\0132\010.BookTagB,\n\016com.ihaiu.testP" + "\000\370\001\001\242\002\003GPB\252\002\016com.ihaiu.testb\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.ihaiu.test.Booktag.getDescriptor(), }, assigner); internal_static_google_protobuf_Book_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_protobuf_Book_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_protobuf_Book_descriptor, new java.lang.String[] { "Id", "Name", "Tag", }); com.ihaiu.test.Booktag.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
49128125a7e0630e5406de2653a156c0c923e921
9c1d2610e2f95eaac3ed7238e64b2c37503cf5ac
/src/com/ifeng/liulu/hotboostLog/MongoUtil.java
34cf45c618f9e2f71ef51e1706959b7ea8276389
[]
no_license
FiveJoy/LogRelated
ab18d46f118eb2b9da909ff7397ba8f3986794b1
fc0ab0f3c14c04179cfa39fb74701dd79d501e8a
refs/heads/master
2021-09-01T05:54:11.201664
2017-12-25T06:50:55
2017-12-25T06:50:55
114,831,532
0
0
null
null
null
null
GB18030
Java
false
false
2,697
java
package com.ifeng.liulu.hotboostLog; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; public class MongoUtil { private static final Log LOG = LogFactory.getLog(MongoUtil.class); public static MongoClient client = null; public static DB mongoDatabase = null; public static DBCollection collection = null; // 等同于SQL中的表 public static String dbName = "hotboosthistory";// 等同于SQL中的数据库 public static String colName = "hotboost0"; /** * 获得链接 * * @param ServerIP * @param ServerPort * @param DBName * @param collectionName */ public static void getConnect() { // 添加主从节点 List<ServerAddress> addresses = new ArrayList<ServerAddress>(); ServerAddress hostAddr = new ServerAddress("10.80.2.150", 10001); ServerAddress slaveAddr1 = new ServerAddress("10.80.3.150", 10001); ServerAddress slaveAddr2 = new ServerAddress("10.80.4.150", 10001); addresses.add(hostAddr); addresses.add(slaveAddr1); addresses.add(slaveAddr2); // 添加认证 List<MongoCredential> credentialList = new ArrayList<MongoCredential>(); MongoCredential credential = MongoCredential.createCredential("root", "admin", "!@#$%^&*".toCharArray()); credentialList.add(credential); // 设置client client = new MongoClient(addresses, credentialList); // 设置数据库 mongoDatabase = client.getDB(dbName); // 设置collection collection = mongoDatabase.getCollection(colName); LOG.info("Mongo connect successfully."); } /* * 为Mongo创建索引,每个collection只需执行一次 */ public static void createIndex(String index_name) { // 建立时间索引-设置30天删除TTL /* * int EXPIRETIME=60*60*30; DBObject index = new BasicDBObject(index_name, 1); * DBObject expireTime = new BasicDBObject("expireAfterSeconds", EXPIRETIME); * MongoUtil.collection.createIndex(index,expireTime); */ // 创建普通索引 DBObject index = new BasicDBObject(index_name, 1); MongoUtil.collection.createIndex(index); } /** * 关闭连接(确定当前进程不会再使用该连接才使用,否则会报错) 实际情况下并不需要调取该方法 当该进程结束后会自动释放连接 */ public static void close() { if (client != null) { client.close(); client = null; } } }
4586d2fb9aea6b74568cc238b26f9cfa3536113b
ebea5491ad8faffb2c8e02f93fbcfbf7c8e5cd76
/src/LC_382_Linked_List_Random_Node.java
ff98b34f2fb1824f1279b90e9075031b1ee3ed72
[]
no_license
arnabs542/leetcode-13
695e592eca325a84a03f573c80254ecfcdb8af0a
87e57434c1a03d5c606c5c81b7a58c94321bd7c2
refs/heads/master
2022-09-16T07:45:11.732596
2020-05-31T03:50:13
2020-05-31T03:50:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,543
java
/* * Copyright (c) 2020 maoyan.com * All rights reserved. * */ import java.util.ArrayList; import java.util.Random; /** * 在这里编写类的功能描述 * * @author guozhaoliang * @created 20/3/5 */ public class LC_382_Linked_List_Random_Node { /* https://leetcode.com/tag/reservoir-sampling/ https://robinliu.gitbooks.io/leetcode/content/reservoir_sampling.html https://en.jinzhao.wiki/wiki/Reservoir_sampling */ /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */ class Solution { private ListNode head; private Random rand; public Solution(ListNode head) { this.head = head; this.rand = new Random(); } public int getRandom() { int k = 1; ListNode node = this.head; int res = node.val; int i = 0; ArrayList<Integer> reservoir = new ArrayList<>(); while(i<k && node !=null){ reservoir.add(node.val); node = node.next; i++; } i++; while ( node !=null){ int randomIndex = rand.nextInt(i); if(randomIndex < k){ reservoir.set(randomIndex,node.val); } i++; node = node.next; } return reservoir.get(0); } } }
71c6c8b4b7cdce832fa5afea520eaef922b21126
55ae21722eeb3c14cc8f5df482177a1228b18356
/paas/src/main/java/cn/xpms/paas/api/dao/generator/repository/PaasCustomAutomationTemplateMapper.java
bb8ed58fed44f575f2c4e0f035db43e01bb0e04e
[]
no_license
kemuchen/XPMS
5f9709b14b531d072031666b9e17b919a07f02aa
0499d04df40b1ecc16658d71316b182998b26e32
refs/heads/master
2023-04-02T07:54:32.901901
2021-04-15T03:56:27
2021-04-15T03:56:27
358,116,947
0
0
null
null
null
null
UTF-8
Java
false
false
4,045
java
package cn.xpms.paas.api.dao.generator.repository; import cn.xpms.paas.api.dao.generator.entity.PaasCustomAutomationTemplate; import cn.xpms.paas.api.dao.generator.entity.PaasCustomAutomationTemplateExample; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Repository; @Repository public interface PaasCustomAutomationTemplateMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ long countByExample(PaasCustomAutomationTemplateExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int deleteByExample(PaasCustomAutomationTemplateExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int insert(PaasCustomAutomationTemplate record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int insertSelective(PaasCustomAutomationTemplate record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ List<PaasCustomAutomationTemplate> selectByExampleWithRowbounds(PaasCustomAutomationTemplateExample example, RowBounds rowBounds); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ List<PaasCustomAutomationTemplate> selectByExample(PaasCustomAutomationTemplateExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ PaasCustomAutomationTemplate selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int updateByExampleSelective(@Param("record") PaasCustomAutomationTemplate record, @Param("example") PaasCustomAutomationTemplateExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int updateByExample(@Param("record") PaasCustomAutomationTemplate record, @Param("example") PaasCustomAutomationTemplateExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int updateByPrimaryKeySelective(PaasCustomAutomationTemplate record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table paas_custom_automation_template * * @mbg.generated Wed Apr 14 10:55:22 CST 2021 */ int updateByPrimaryKey(PaasCustomAutomationTemplate record); }
ec17c5e317909abd58d533249da12c6b01b17658
d4e2b8632fd144852c3f193a6a597b92ef18dc98
/Hanto2014-Master/test/hanto/studentgrimshaw_mckenna/alpha/AlphaHantoCoordinateTest.java
5eb5469578dcb996ee6e3e97a6f6ba9b2d17eeb6
[]
no_license
magwitch324/CS4233-Hanto
856be73e342d033dd7942eea50500790c061253a
210bf0c77656571275b2a5e0bd7ad0802dc62af7
refs/heads/master
2021-01-21T23:58:48.512387
2014-10-16T04:46:48
2014-10-16T04:46:48
23,884,316
0
0
null
null
null
null
UTF-8
Java
false
false
2,844
java
/******************************************************************************* * This files was developed for CS4233: Object-Oriented Analysis & Design. * The course was taken at Worcester Polytechnic Institute. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package hanto.studentgrimshaw_mckenna.alpha; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import hanto.common.HantoCoordinate; import java.util.GregorianCalendar; import org.junit.Test; /** * Tests for AlphaHantoCoordinate * * @author Twgrimshaw * @author Remckenna * */ public class AlphaHantoCoordinateTest { @Test public void coordinateReturns0s() { HantoCoordinate coordinate = new AlphaHantoCoordinate(0, 0); assertEquals(0, coordinate.getX()); assertEquals(0, coordinate.getY()); } @Test public void coordinateReturns11() { HantoCoordinate coordinate = new AlphaHantoCoordinate(1, 1); assertEquals(1, coordinate.getX()); assertEquals(1, coordinate.getY()); } @Test public void coordinateReturns23() { HantoCoordinate coordinate = new AlphaHantoCoordinate(2, 3); assertEquals(2, coordinate.getX()); assertEquals(3, coordinate.getY()); } @Test public void shouldHaveHash961() { AlphaHantoCoordinate coord = new AlphaHantoCoordinate(0, 0); assertEquals(961, coord.hashCode()); } @Test public void testGetNeighborCoordinates() { AlphaHantoCoordinate coord = new AlphaHantoCoordinate(0, 0); AlphaHantoCoordinate[] coordArray = coord.getNeighborCoordinates(); assertEquals(coordArray[0], new AlphaHantoCoordinate(0, 1)); assertEquals(coordArray[1], new AlphaHantoCoordinate(1, 0)); assertEquals(coordArray[2], new AlphaHantoCoordinate(1, -1)); assertEquals(coordArray[3], new AlphaHantoCoordinate(0, -1)); assertEquals(coordArray[4], new AlphaHantoCoordinate(-1, 0)); assertEquals(coordArray[5], new AlphaHantoCoordinate(-1, 1)); } @Test public void testEqualsObject() { AlphaHantoCoordinate coord = new AlphaHantoCoordinate(0, 0); GregorianCalendar gc = new GregorianCalendar(); assertNotEquals(coord, gc); } @Test public void testEqualsWithSelf() { AlphaHantoCoordinate coord = new AlphaHantoCoordinate(0, 0); assertEquals(coord, coord); } @Test public void testEqualsWithOtherCoord() { AlphaHantoCoordinate coord1 = new AlphaHantoCoordinate(0, 0); AlphaHantoCoordinate coord2 = new AlphaHantoCoordinate(0, 1); assertNotEquals(coord1, coord2); AlphaHantoCoordinate coord3 = new AlphaHantoCoordinate(1, 0); assertNotEquals(coord1, coord3); } }
f9f248977ae65bf6ac4eb1f596e71947d12c9c0e
d53a4ebcfdb505a46f768cf1fe5cbf607c97f659
/src/main/java/org/gwtjoda/time/ReadablePartial.java
10a860b378709bb6aa32f991adfacc03fa5fb3f1
[]
no_license
thanglt/gwt-joda-time
a4c30aaa04b3884744d203052e6b403e280b833c
ec9f8ff1ff9fa0ed046319df99b7c720835fef24
refs/heads/master
2021-01-10T03:00:33.024671
2010-03-01T16:10:52
2010-03-01T16:10:52
36,610,933
0
0
null
null
null
null
UTF-8
Java
false
false
6,740
java
/* * Copyright 2001-2005 Stephen Colebourne * * 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.gwtjoda.time; /** * Defines a partial time that does not support every datetime field, and is * thus a local time. * <p> * A <code>ReadablePartial</code> supports a subset of those fields on the chronology. * It cannot be compared to a <code>ReadableInstant</code>, as it does not fully * specify an instant in time. The time it does specify is a local time, and does * not include a time zone. * <p> * A <code>ReadablePartial</code> can be converted to a <code>ReadableInstant</code> * using the <code>toDateTime</code> method. This works by providing a full base * instant that can be used to 'fill in the gaps' and specify a time zone. * * @author Stephen Colebourne * @since 1.0 */ public interface ReadablePartial { /** * Gets the number of fields that this partial supports. * * @return the number of fields supported */ int size(); /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeFieldType getFieldType(int index); /** * Gets the field at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeField getField(int index); /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value of the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ int getValue(int index); /** * Gets the chronology of the partial which is never null. * <p> * The {@link Chronology} is the calculation engine behind the partial and * provides conversion and validation of the fields in a particular calendar system. * * @return the chronology, never null */ Chronology getChronology(); /** * Gets the value of one of the fields. * <p> * The field type specified must be one of those that is supported by the partial. * * @param field a DateTimeFieldType instance that is supported by this partial * @return the value of that field * @throws IllegalArgumentException if the field is null or not supported */ int get(DateTimeFieldType field); /** * Checks whether the field type specified is supported by this partial. * * @param field the field to check, may be null which returns false * @return true if the field is supported */ boolean isSupported(DateTimeFieldType field); /** * Converts this partial to a full datetime by resolving it against another * datetime. * <p> * This method takes the specified datetime and sets the fields from this * instant on top. The chronology from the base instant is used. * <p> * For example, if this partial represents a time, then the result of this * method will be the datetime from the specified base instant plus the * time from this partial. * * @param baseInstant the instant that provides the missing fields, null means now * @return the combined datetime */ DateTime toDateTime(ReadableInstant baseInstant); //----------------------------------------------------------------------- /** * Compares this partial with the specified object for equality based * on the supported fields, chronology and values. * <p> * Two instances of ReadablePartial are equal if they have the same * chronology, same field types (in same order) and same values. * * @param partial the object to compare to * @return true if equal */ boolean equals(Object partial); /** * Gets a hash code for the partial that is compatible with the * equals method. * <p> * The formula used must be: * <pre> * int total = 157; * for (int i = 0; i < fields.length; i++) { * total = 23 * total + values[i]; * total = 23 * total + fieldTypes[i].hashCode(); * } * total += chronology.hashCode(); * return total; * </pre> * * @return a suitable hash code */ int hashCode(); // NOTE: This method should have existed in Joda-Time v1.0. // We STRONGLY recommend that all implementations of ReadablePartial // implement this method, as per AbstractPartial. // The simplest way to do this is to extend AbstractPartial. // v2.0 of Joda-Time will include this method in this interface. // //----------------------------------------------------------------------- // /** // * Compares this partial with another returning an integer // * indicating the order. // * <p> // * The fields are compared in order, from largest to smallest. // * The first field that is non-equal is used to determine the result. // * Thus a YearHour partial will first be compared on the year, and then // * on the hour. // * <p> // * The specified object must be a partial instance whose field types // * match those of this partial. If the parial instance has different // * fields then a ClassCastException is thrown. // * // * @param partial an object to check against // * @return negative if this is less, zero if equal, positive if greater // * @throws ClassCastException if the partial is the wrong class // * or if it has field types that don't match // * @throws NullPointerException if the partial is null // * @since 2.0 // */ // int compareTo(Object partial); //----------------------------------------------------------------------- /** * Get the value as a String in a recognisable ISO8601 format, only * displaying supported fields. * <p> * The string output is in ISO8601 format to enable the String * constructor to correctly parse it. * * @return the value as an ISO8601 string */ String toString(); }
fe9d9702eb10f140bb922a9b8b1ed13984255376
8462aa509cb72a2ad36131f453acd827cdfb1f7e
/app/src/main/java/com/sauno/androiddeveloper/chewstudiodemo/TuneFiveMealFragment.java
62ba0006847377ed348b793e9ffea0418c390462
[]
no_license
VillipJohn/SmartChew
f86dbea0fdb45182be79c2c4cfbc2b190640f91c
de19affe89ed698ee04c33f24e528e47b95ad95b
refs/heads/master
2020-03-15T22:36:19.421646
2019-10-31T02:18:23
2019-10-31T02:18:23
131,718,739
0
0
null
null
null
null
UTF-8
Java
false
false
13,521
java
package com.sauno.androiddeveloper.chewstudiodemo; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.formatter.PercentFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import java.util.ArrayList; public class TuneFiveMealFragment extends Fragment { private static String TAG = "TuneFiveMealFragment"; public int breakfastPercentFiveMeal; public int firstSnackPercentFiveMeal; public int lunchPercentFiveMeal; public int secondSnackPercentFiveMeal; public int dinnerPercentFiveMeal; TextView chosenMealTextView; TextView percentTextView; ImageView minusImageView; ImageView plusImageView; Button okButton; TextView countCaloriesTextView; TextView countProteinsTextView; TextView countFatsTextView; TextView countCarbohydratesTextView; TextView countXETextView; PieChart pieChart; private int[] yData = new int[5]; private String[] xData = {"Завтрак", "Первый перекус", "Обед", "Второй перекус", "Ужин"}; int chosenMeal = 0; int calories; int proteins; int fats; int carbs; int xe; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_tune_four_meal, container, false); SharedPreferences mSharedPreferences = getActivity().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE); breakfastPercentFiveMeal = mSharedPreferences.getInt("breakfastPercentFiveMeal", 25); firstSnackPercentFiveMeal = mSharedPreferences.getInt("firstSnackPercentFiveMeal", 10); lunchPercentFiveMeal = mSharedPreferences.getInt("lunchPercentFiveMeal", 30); secondSnackPercentFiveMeal = mSharedPreferences.getInt("secondSnackPercentFiveMeal", 10); dinnerPercentFiveMeal = mSharedPreferences.getInt("dinnerPercentFiveMeal", 25); setDataPercents(); chosenMealTextView = rootView.findViewById(R.id.chosenMealTextView); percentTextView = rootView.findViewById(R.id.percentTextView); minusImageView = rootView.findViewById(R.id.minusImageView); plusImageView = rootView.findViewById(R.id.plusImageView); okButton = rootView.findViewById(R.id.okButton); /*animatedPieView = rootView.findViewById(R.id.pieView); setPie();*/ countCaloriesTextView = rootView.findViewById(R.id.countCaloriesTextView); countProteinsTextView = rootView.findViewById(R.id.countProteinsTextView); countFatsTextView = rootView.findViewById(R.id.countFatsTextView); countCarbohydratesTextView = rootView.findViewById(R.id.countCarbohydratesTextView); countXETextView = rootView.findViewById(R.id.countXETextView); minusImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (chosenMeal) { case 0: if(breakfastPercentFiveMeal > 3) { breakfastPercentFiveMeal = breakfastPercentFiveMeal - 1; firstSnackPercentFiveMeal = firstSnackPercentFiveMeal + 1; setData(breakfastPercentFiveMeal); } break; case 1: if(firstSnackPercentFiveMeal > 3) { firstSnackPercentFiveMeal = firstSnackPercentFiveMeal - 1; lunchPercentFiveMeal = lunchPercentFiveMeal + 1; setData(firstSnackPercentFiveMeal); } break; case 2: if(lunchPercentFiveMeal > 3) { lunchPercentFiveMeal = lunchPercentFiveMeal -1; secondSnackPercentFiveMeal = secondSnackPercentFiveMeal + 1; setData(lunchPercentFiveMeal); } break; case 3: if(secondSnackPercentFiveMeal > 0) { secondSnackPercentFiveMeal = secondSnackPercentFiveMeal -1; dinnerPercentFiveMeal = dinnerPercentFiveMeal + 1; setData(secondSnackPercentFiveMeal); } break; case 4: if(dinnerPercentFiveMeal > 3) { dinnerPercentFiveMeal = dinnerPercentFiveMeal -1; breakfastPercentFiveMeal = breakfastPercentFiveMeal + 1; setData(dinnerPercentFiveMeal); } break; default: break; } setDataPercents(); addDataSet(); } }); plusImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (chosenMeal) { case 0: if(breakfastPercentFiveMeal < 91 && dinnerPercentFiveMeal > 3) { breakfastPercentFiveMeal = breakfastPercentFiveMeal + 1; dinnerPercentFiveMeal = dinnerPercentFiveMeal -1; setData(breakfastPercentFiveMeal); } break; case 1: if(firstSnackPercentFiveMeal < 91 && breakfastPercentFiveMeal > 3) { firstSnackPercentFiveMeal = firstSnackPercentFiveMeal + 1; breakfastPercentFiveMeal = breakfastPercentFiveMeal - 1; setData(firstSnackPercentFiveMeal); } break; case 2: if(lunchPercentFiveMeal < 91 && firstSnackPercentFiveMeal > 3) { lunchPercentFiveMeal = lunchPercentFiveMeal + 1; firstSnackPercentFiveMeal = firstSnackPercentFiveMeal - 1; setData(lunchPercentFiveMeal); } break; case 3: if(secondSnackPercentFiveMeal < 91 && lunchPercentFiveMeal > 3) { secondSnackPercentFiveMeal = secondSnackPercentFiveMeal + 1; lunchPercentFiveMeal = lunchPercentFiveMeal - 1; setData(secondSnackPercentFiveMeal); } break; case 4: if(dinnerPercentFiveMeal < 91 && secondSnackPercentFiveMeal > 3) { dinnerPercentFiveMeal = dinnerPercentFiveMeal + 1; secondSnackPercentFiveMeal = secondSnackPercentFiveMeal - 1; setData(dinnerPercentFiveMeal); } break; default: break; } setDataPercents(); addDataSet(); } }); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SelectDesiredMealActivity selectDesiredMealActivity = (SelectDesiredMealActivity)getActivity(); selectDesiredMealActivity.restartFromTuneFiveMealFragment(); } }); //setCurrentMeal(); pieChart = rootView.findViewById(R.id.pieChart); pieChart.setDescription(null); //pieChart.setDescription("Sales by employee (In Thousands $) "); pieChart.setRotationEnabled(true); //pieChart.setUsePercentValues(true); //pieChart.setHoleColor(Color.BLUE); //pieChart.setCenterTextColor(Color.BLACK); pieChart.setHoleRadius(0); pieChart.setTransparentCircleAlpha(0); /*pieChart.setCenterText("Super Cool Chart"); pieChart.setCenterTextSize(10);*/ addDataSet(); pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { chosenMeal = (int)(h.getX()); switch (chosenMeal) { case 0: setData(breakfastPercentFiveMeal); break; case 1: setData(firstSnackPercentFiveMeal); break; case 2: setData(lunchPercentFiveMeal); break; case 3: setData(secondSnackPercentFiveMeal); break; case 4: setData(dinnerPercentFiveMeal); break; default: break; } //Log.d(TAG, "index: " + index); /* int pos1 = e.toString().indexOf("y: "); String sales = e.toString().substring(pos1 + 3); for(int i = 0; i < yData.length; i++){ if(yData[i] == Float.parseFloat(sales)){ pos1 = i; break; } } String employee = xData[pos1 + 1]; Toast.makeText(getContext(), "Employee " + employee + "\n" + "Sales: $" + sales + "K", Toast.LENGTH_LONG).show();*/ } @Override public void onNothingSelected() { } }); setData(breakfastPercentFiveMeal); return rootView; } // установление реальных процентов private void setDataPercents() { yData[0] = breakfastPercentFiveMeal; yData[1] = firstSnackPercentFiveMeal; yData[2] = lunchPercentFiveMeal; yData[3] = secondSnackPercentFiveMeal; yData[4] = dinnerPercentFiveMeal; } private void addDataSet() { ArrayList<PieEntry> yEntrys = new ArrayList<>(); ArrayList<String> xEntrys = new ArrayList<>(); for(int i = 0; i < yData.length; i++) { yEntrys.add(new PieEntry(yData[i], i)); } for(int i = 0; i < xData.length; i++) { xEntrys.add(xData[i]); } // создание dataset PieDataSet pieDataSet = new PieDataSet(yEntrys, null); pieDataSet.setSliceSpace(2); pieDataSet.setValueTextSize(12); // добавление цветов в dataset ArrayList<Integer> colors = new ArrayList<>(); colors.add(Color.RED); colors.add(Color.BLUE); colors.add(Color.YELLOW); colors.add(Color.BLUE); colors.add(Color.GREEN); pieDataSet.setColors(colors); // добавление надписей Legend legend = pieChart.getLegend(); legend.setEnabled(false); /*legend.setForm(Legend.LegendForm.CIRCLE); legend.setPosition(Legend.LegendPosition.LEFT_OF_CHART);*/ // создание объекта pieData PieData pieData = new PieData(pieDataSet); pieData.setValueFormatter(new PercentFormatter()); pieChart.setData(pieData); pieChart.invalidate(); } private void setData(int percent) { chosenMealTextView.setText(xData[chosenMeal]); percentTextView.setText("" + percent + "%"); float percentFloat = percent * 0.01f; calories = (int)(SelectDesiredMealActivity.calories * percentFloat); proteins = (int)(SelectDesiredMealActivity.proteins * percentFloat); fats = (int)(SelectDesiredMealActivity.fats * percentFloat); carbs = (int)(SelectDesiredMealActivity.carbohydrates * percentFloat); xe = (int)(SelectDesiredMealActivity.xe * percentFloat); countCaloriesTextView.setText(calories + ""); countProteinsTextView.setText(proteins + "г"); countFatsTextView.setText(fats + "г"); countCarbohydratesTextView.setText(carbs + "г"); countXETextView.setText(xe + ""); } @Override public void onDetach() { super.onDetach(); SelectDesiredMealActivity selectDesiredMealActivity = (SelectDesiredMealActivity)getActivity(); selectDesiredMealActivity.restartFromTuneFiveMealFragment(); } }
bba435cbc5e21da1beec78f69852473c303a8489
d16604bb916ab282c03acec8f40d100b249f653c
/app/src/main/java/study/lzy/studymodle/touch/Parent.java
47a26dbf3cb44026e344d219d1795852366a170d
[]
no_license
CrazyRabbitCCC/StudyModle
38db5c8fa4396ff16bac531a203e78d3f50506bb
0cec3562b316772c9194eb4868a3ecf80975f819
refs/heads/master
2021-05-04T04:47:23.304761
2017-07-10T07:34:26
2017-07-10T07:34:30
70,892,849
0
0
null
null
null
null
UTF-8
Java
false
false
1,355
java
package study.lzy.studymodle.touch; // @author: lzy time: 2016/11/11. import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.LinearLayout; public class Parent extends LinearLayout{ public Parent(Context context) { super(context); } public Parent(Context context, AttributeSet attrs) { super(context, attrs); } public Parent(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.e("Parent "," dispatchTouchEvent "+"start"); boolean event = super.dispatchTouchEvent(ev); Log.e("Parent "," dispatchTouchEvent "+event); return event; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { Log.e("Parent "," onInterceptTouchEvent "+ "start"); boolean event = super.onInterceptTouchEvent(ev); Log.e("Parent "," onInterceptTouchEvent "+ event); return event; } @Override public boolean onTouchEvent(MotionEvent event) { Log.e("Parent "," onTouchEvent "+ "start"); boolean ev = super.onTouchEvent(event); Log.e("Parent "," onTouchEvent "+ ev); return ev; } }
7fad058dcd8baff52fb358ff617f88c26644f08e
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/6/6_b8f437a583b195e6303ffa7f4c579397dffc5366/Util/6_b8f437a583b195e6303ffa7f4c579397dffc5366_Util_t.java
e92119926ed6a3b6b8a85bc77942fc27691f7c29
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
14,012
java
package hudson; import hudson.model.TaskListener; import hudson.util.IOException2; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.Chmod; import org.apache.tools.ant.taskdefs.Copy; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.SimpleTimeZone; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Kohsuke Kawaguchi */ public class Util { /** * Creates a filtered sublist. */ public static <T> List<T> filter( List<?> base, Class<T> type ) { List<T> r = new ArrayList<T>(); for (Object i : base) { if(type.isInstance(i)) r.add(type.cast(i)); } return r; } /** * Replaces the occurrence of '$key' by <tt>properties.get('key')</tt>. * * <p> * This is a rather naive implementation that causes somewhat unexpected * behavior when the expansion contains other macros. */ public static String replaceMacro(String s, Map<String,String> properties) { int idx=0; while((idx=s.indexOf('$',idx))>=0) { // identify the key int end=idx+1; while(end<s.length()) { char ch = s.charAt(end); if(!Character.isJavaIdentifierPart(ch)) break; else end++; } String key = s.substring(idx+1,end); String value = properties.get(key); if(value==null) { idx++; // skip this '$' mark } else { s = s.substring(0,idx)+value+s.substring(end); } } return s; } /** * Loads the contents of a file into a string. */ public static String loadFile(File logfile) throws IOException { if(!logfile.exists()) return ""; StringBuffer str = new StringBuffer((int)logfile.length()); BufferedReader r = new BufferedReader(new FileReader(logfile)); char[] buf = new char[1024]; int len; while((len=r.read(buf,0,buf.length))>0) str.append(buf,0,len); r.close(); return str.toString(); } /** * Deletes the contents of the given directory (but not the directory itself) * recursively. * * @throws IOException * if the operation fails. */ public static void deleteContentsRecursive(File file) throws IOException { File[] files = file.listFiles(); if(files==null) return; // the directory didn't exist in the first place for (File child : files) { if (child.isDirectory()) deleteContentsRecursive(child); deleteFile(child); } } private static void deleteFile(File f) throws IOException { if (!f.delete()) { if(!f.exists()) // we are trying to delete a file that no longer exists, so this is not an error return; // perhaps this file is read-only? // try chmod. this becomes no-op if this is not Unix. try { Chmod chmod = new Chmod(); chmod.setProject(new org.apache.tools.ant.Project()); chmod.setFile(f); chmod.setPerm("u+w"); chmod.execute(); } catch (BuildException e) { LOGGER.log(Level.INFO,"Failed to chmod "+f,e); } throw new IOException("Unable to delete " + f.getPath()); } } public static void deleteRecursive(File dir) throws IOException { deleteContentsRecursive(dir); deleteFile(dir); } /** * Creates a new temporary directory. */ public static File createTempDir() throws IOException { File tmp = File.createTempFile("hudson", "tmp"); if(!tmp.delete()) throw new IOException("Failed to delete "+tmp); if(!tmp.mkdirs()) throw new IOException("Failed to create a new directory "+tmp); return tmp; } private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*"); /** * On Windows, error messages for IOException aren't very helpful. * This method generates additional user-friendly error message to the listener */ public static void displayIOException( IOException e, TaskListener listener ) { String msg = getWin32ErrorMessage(e); if(msg!=null) listener.getLogger().println(msg); } /** * Extracts the Win32 error message from {@link IOException} if possible. * * @return * null if there seems to be no error code or if the platform is not Win32. */ public static String getWin32ErrorMessage(IOException e) { Matcher m = errorCodeParser.matcher(e.getMessage()); if(!m.matches()) return null; // failed to parse try { ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors"); return rb.getString("error"+m.group(1)); } catch (Exception _) { // silently recover from resource related failures return null; } } /** * Guesses the current host name. */ public static String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "localhost"; } } public static void copyStream(InputStream in,OutputStream out) throws IOException { byte[] buf = new byte[8192]; int len; while((len=in.read(buf))>0) out.write(buf,0,len); } public static String[] tokenize(String s) { StringTokenizer st = new StringTokenizer(s); String[] a = new String[st.countTokens()]; for (int i = 0; st.hasMoreTokens(); i++) a[i] = st.nextToken(); return a; } public static String[] mapToEnv(Map<String,String> m) { String[] r = new String[m.size()]; int idx=0; for (final Map.Entry<String,String> e : m.entrySet()) { r[idx++] = e.getKey() + '=' + e.getValue(); } return r; } public static int min(int x, int... values) { for (int i : values) { if(i<x) x=i; } return x; } public static String nullify(String v) { if(v!=null && v.length()==0) v=null; return v; } /** * Write-only buffer. */ private static final byte[] garbage = new byte[8192]; /** * Computes MD5 digest of the given input stream. * * @param source * The stream will be closed by this method at the end of this method. */ public static String getDigestOf(InputStream source) throws IOException { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); DigestInputStream in =new DigestInputStream(source,md5); try { while(in.read(garbage)>0) ; // simply discard the input } finally { in.close(); } return toHexString(md5.digest()); } catch (NoSuchAlgorithmException e) { throw new IOException2("MD5 not installed",e); // impossible } } public static String toHexString(byte[] data, int start, int len) { StringBuffer buf = new StringBuffer(); for( int i=0; i<len; i++ ) { int b = data[start+i]&0xFF; if(b<16) buf.append('0'); buf.append(Integer.toHexString(b)); } return buf.toString(); } public static String toHexString(byte[] bytes) { return toHexString(bytes,0,bytes.length); } public static String getTimeSpanString(long duration) { duration /= 1000; if(duration<60) return combine(duration,"second"); duration /= 60; if(duration<60) return combine(duration,"minute"); duration /= 60; if(duration<24) return combine(duration,"hour"); duration /= 24; if(duration<30) return combine(duration,"day"); duration /= 30; if(duration<12) return combine(duration,"month"); duration /= 12; return combine(duration,"year"); } /** * Combines number and unit, with a plural suffix if needed. */ public static String combine(long n, String suffix) { String s = Long.toString(n)+' '+suffix; if(n!=1) s += 's'; return s; } /** * Create a sub-list by only picking up instances of the specified type. */ public static <T> List<T> createSubList( Collection<?> source, Class<T> type ) { List<T> r = new ArrayList<T>(); for (Object item : source) { if(type.isInstance(item)) r.add(type.cast(item)); } return r; } /** * Escapes non-ASCII characters. */ public static String encode(String s) { try { boolean escaped = false; StringBuffer out = new StringBuffer(s.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(buf,"UTF-8"); for (int i = 0; i < s.length(); i++) { int c = (int) s.charAt(i); if (c<128 && c!=' ') { out.append((char) c); } else { // 1 char -> UTF8 w.write(c); w.flush(); for (byte b : buf.toByteArray()) { out.append('%'); out.append(toDigit((b >> 4) & 0xF)); out.append(toDigit(b & 0xF)); } buf.reset(); escaped = true; } } return escaped ? out.toString() : s; } catch (IOException e) { throw new Error(e); // impossible } } /** * Escapes HTML unsafe characters like &lt;, &amp;to the respective character entities. */ public static String escape(String text) { StringBuffer buf = new StringBuffer(text.length()+64); for( int i=0; i<text.length(); i++ ) { char ch = text.charAt(i); if(ch=='\n') buf.append("<br>"); else if(ch=='<') buf.append("&lt;"); else if(ch=='&') buf.append("&amp;"); else if(ch==' ') buf.append("&nbsp;"); else buf.append(ch); } return buf.toString(); } private static char toDigit(int n) { char ch = Character.forDigit(n,16); if(ch>='a') ch = (char)(ch-'a'+'A'); return ch; } /** * Creates an empty file. */ public static void touch(File file) throws IOException { new FileOutputStream(file).close(); } /** * Copies a single file by using Ant. */ public static void copyFile(File src, File dst) throws BuildException { Copy cp = new Copy(); cp.setProject(new org.apache.tools.ant.Project()); cp.setTofile(dst); cp.setFile(src); cp.setOverwrite(true); cp.execute(); } /** * Convert null to "". */ public static String fixNull(String s) { if(s==null) return ""; else return s; } /** * Convert empty string to null. */ public static String fixEmpty(String s) { if(s==null || s.length()==0) return null; return s; } /** * Cuts all the leading path portion and get just the file name. */ public static String getFileName(String filePath) { int idx = filePath.lastIndexOf('\\'); if(idx>=0) return getFileName(filePath.substring(idx+1)); idx = filePath.lastIndexOf('/'); if(idx>=0) return getFileName(filePath.substring(idx+1)); return filePath; } public static final SimpleDateFormat XS_DATETIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // Note: RFC822 dates must not be localized! public static final SimpleDateFormat RFC822_DATETIME_FORMATTER = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); static { XS_DATETIME_FORMATTER.setTimeZone(new SimpleTimeZone(0,"GMT")); } private static final Logger LOGGER = Logger.getLogger(Util.class.getName()); }
f4a6d1c41b9b83617004c3e12e99b41849bf67e8
3735a07d455d7b40613c3c4160aa8b1cb1b3472a
/plugins/lombok/testData/highlighting/LombokBasics.java
41f4519a818f0fb56300a525673dbf30c2d34741
[ "Apache-2.0" ]
permissive
caofanCPU/intellij-community
ede9417fc4ccb4b5efefb099906e4abe6871f3b4
5ad3e2bdf3c83d86e7c4396f5671929768d76999
refs/heads/master
2023-02-27T21:38:33.416107
2021-02-05T06:37:40
2021-02-05T06:37:40
321,209,485
1
0
Apache-2.0
2021-02-05T06:37:41
2020-12-14T02:22:32
null
UTF-8
Java
false
false
2,124
java
import lombok.*; @ToString @EqualsAndHashCode @AllArgsConstructor public final class LombokBasics { @Getter @Setter // should not be marked as unused private int age = <warning descr="Variable 'age' initializer '10' is redundant">10</warning>; void test(LombokBasics other) { setAge(20); // setter should be resolved System.out.println(getAge()); // getter should be resolved System.out.println(this.toString()); // toString is defined if (this <warning descr="Object values are compared using '==', not 'equals()'">==</warning> other) {} // equals is implicitly defined } public static void main(String[] args) { new LombokBasics(10).test(new LombokBasics(12)); } } @AllArgsConstructor class FinalCheck { @Getter private int <warning descr="Field 'a' may be 'final'">a</warning>; @Setter private int <warning descr="Private field 'b' is assigned but never accessed">b</warning>; @Getter @Setter private int c; } final class Foo { @Getter String bar; public void <warning descr="Method 'test()' is never used">test</warning>() { bar = null; System.out.println(getBar().trim()); } } class <warning descr="Class 'Outer' is never used">Outer</warning> { void <warning descr="Method 'foo()' is never used">foo</warning>() { @EqualsAndHashCode class <warning descr="Local class 'Inner' is never used">Inner</warning> { int x; } } } class IntellijInspectionNPEDemo { @Builder public static class SomeDataClass { public static class <warning descr="Class 'SomeDataClassBuilder' is never used">SomeDataClassBuilder</warning> { private void <warning descr="Private method 'buildWithJSON()' is never used">buildWithJSON</warning>() { this.jsonObject = "test"; } } public final String jsonObject; } } class <warning descr="Class 'InitializerInVar' is never used">InitializerInVar</warning> { public void <warning descr="Method 'foo()' is never used">foo</warning>() { var x = 1; // expect no "not used initializer" warning try { x = 3; } catch (NullPointerException e) { x = 1; } System.out.println(x); } }
e33e6fb366fea9b26a34cfc0c9e654370143ebb9
8bb6a7a172ff41585346320e5910542796616be1
/src/main/java/com/isa/spring/beans/javaconfig/Beak.java
9de5fee82e25d8dfdfcbf716f7a155413baf7c8a
[]
no_license
isaolmez/spring-dependency-injection
85dbd18c9d57689b34b9266d807b50168d376a4c
67fee85eb974557813c505e555c74a56a21373d7
refs/heads/master
2020-07-06T21:44:25.637452
2017-04-10T20:09:14
2017-04-10T20:09:14
67,162,041
0
0
null
null
null
null
UTF-8
Java
false
false
91
java
package com.isa.spring.beans.javaconfig; public interface Beak { void printBeak(); }
3bfb2a67a7742ccd955e9834b0c5362aeb841295
f83b2236687ce2a036c9eac1becf1796e8b0e657
/coachingsoftware-ejb/src/main/java/com/coachingeleven/coachingsoftware/persistence/entity/LineUpPlayer.java
e2cdcba6feafacfaabb654b9c39212414c3deb47
[]
no_license
notmeatall/coachingsoftware
6eec498c16c4cf235e72eaecb59a900c3f91c5c7
2bbd83d2a6070b6595986725cc28a3341a4263d7
refs/heads/master
2021-10-10T22:04:30.655448
2019-01-18T03:03:20
2019-01-18T03:03:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,253
java
package com.coachingeleven.coachingsoftware.persistence.entity; import com.coachingeleven.coachingsoftware.persistence.enumeration.LineUpType; import com.coachingeleven.coachingsoftware.persistence.enumeration.MissingType; import com.coachingeleven.coachingsoftware.persistence.enumeration.Position; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.io.Serializable; @Entity @Table(name = "LINEUP_PLAYERS") public class LineUpPlayer implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "LINEUP_PLAYER_ID") private int ID; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "LINEUP_ID") private Game game; @ManyToOne @JoinColumn(name = "PLAYER_ID") private Player player; @Column(name = "LINEUP_TYPE") @Enumerated(EnumType.STRING) private LineUpType lineUpType; @Column(name = "MISSING_TYPE") @Enumerated(EnumType.STRING) private MissingType missingType; @Column(name = "POSITION") @Enumerated(EnumType.STRING) private Position position; /** * JPA required default constructor */ public LineUpPlayer() { } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public Game getGame() { return game; } public void setGame(Game game) { this.game = game; } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public LineUpType getLineUpType() { return lineUpType; } public void setLineUpType(LineUpType lineUpType) { this.lineUpType = lineUpType; } public MissingType getMissingType() { return missingType; } public void setMissingType(MissingType missingType) { this.missingType = missingType; } public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } }
9a987c3247eb61dc9a9db22a499a4ce8944e0a49
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/12/12_3ed4353b3faa35fa68e109a1175b412f5d99339c/RentalSystem/12_3ed4353b3faa35fa68e109a1175b412f5d99339c_RentalSystem_s.java
ab250706557c0d0d1611d5cdb2aa6e2ffbc39d62
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
814
java
//Import all models package Controller; import Model.*; import Model.CustomerPackage.*; import Model.ItemPackage.*; import Model.NewsletterPackage.*; public class RentalSystem { CustomerHandler CustomerH; ItemHandler ItemH; NewsletterHandler NewsletterH; RentalHandler RentalH; SearchHandler SearchH; Database databse; //Construct public RentalSystem(){ //Handlers and Database this.CustomerH = new CustomerHandler(); this.ItemH = new ItemHandler(); this.NewsletterH = new NewsletterHandler(); this.RentalH = new RentalHandler(); this.SearchH = new SearchHandler(); this.databse = new Database(); //--------------------------------------- } public static void main(String[] args) { RentalSystem test = new RentalSystem(); } }
a24bfeef988f69fd3ef4e7968f49af6e0bc888c4
8dd7e2772708775f6fd1c665b354609f0ea522cd
/ArrayAssigment/CTriangleBMax.java
c110a8115af84238e8cf5bf0f4993a92709265d8
[]
no_license
isSushilSingh/java-practice-master
a7447b54bb76908ab5aeb1e3723a1e23e575b706
36609d665306e8147f79cc4662ea339b66d1bdc3
refs/heads/master
2020-04-02T21:49:39.063246
2018-10-26T09:30:30
2018-10-26T09:30:30
154,812,529
0
0
null
null
null
null
UTF-8
Java
false
false
450
java
class CTriangleBMax{ static void triangleBMax(int x[][]){ for(int i=0;i<x.length;i++) if(x.length!=x[i].length) return; int maxval=x[0][0],k=1,l=1; for(int i=0;i<x.length;i++) for(int j=0;j<=i;j++) if(x[i][j]>maxval){ maxval=x[i][j]; k=i+1;l=j+1; } System.out.println(maxval+" at "+l+" position of "+ k+" row"); }public static void main(String... args){ triangleBMax(new int[][]{{1,2,3},{4,5,6},{7,8,9}}); } }
32bbea3cd163a8baf36690f23135d8650471520a
34a75d0b0d5868886e36511c40e6b0b5282c4e7e
/src/main/java/com/carRental/client/RentalClient.java
d12f4420b51e901895885a5b1be76667810ca98f
[]
no_license
hubertgorczynski/Car-Rental-Service-Frontend
d1fa1a79acb28f1e9c412322c835aee790986350
575986a1b6adbb3e8bced3175a1cc2c3168eb238
refs/heads/master
2023-06-23T10:29:28.671278
2021-07-19T18:41:18
2021-07-19T18:41:18
292,923,749
2
0
null
null
null
null
UTF-8
Java
false
false
2,998
java
package com.carRental.client; import com.carRental.config.BackEndConfiguration; import com.carRental.domain.RentalComplexDto; import com.carRental.domain.RentalDto; import com.carRental.domain.RentalExtensionDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.Optional.ofNullable; @Component public class RentalClient { private final RestTemplate restTemplate; private final BackEndConfiguration backEndConfiguration; @Autowired public RentalClient(RestTemplate restTemplate, BackEndConfiguration backEndConfiguration) { this.restTemplate = restTemplate; this.backEndConfiguration = backEndConfiguration; } public List<RentalComplexDto> getRentals() { try { URI url = UriComponentsBuilder.fromHttpUrl(backEndConfiguration.getRentalEndpoint()).build().encode().toUri(); RentalComplexDto[] response = restTemplate.getForObject(url, RentalComplexDto[].class); return Arrays.asList(ofNullable(response).orElse(new RentalComplexDto[0])); } catch (RestClientException e) { return new ArrayList<>(); } } public List<RentalComplexDto> getRentalsByUserId(Long userId) { try { URI url = UriComponentsBuilder.fromHttpUrl(backEndConfiguration.getRentalEndpoint() + "/by_user_id/" + userId) .build().encode().toUri(); RentalComplexDto[] response = restTemplate.getForObject(url, RentalComplexDto[].class); return Arrays.asList(ofNullable(response).orElse(new RentalComplexDto[0])); } catch (RestClientException e) { return new ArrayList<>(); } } public void createRental(RentalDto rentalDto) { URI url = UriComponentsBuilder.fromHttpUrl(backEndConfiguration.getRentalEndpoint()).build().encode().toUri(); restTemplate.postForObject(url, rentalDto, RentalComplexDto.class); } public void extendRental(RentalExtensionDto rentalExtensionDto) { URI url = UriComponentsBuilder.fromHttpUrl(backEndConfiguration.getRentalEndpoint() + "/extend_rental") .build().encode().toUri(); restTemplate.put(url, rentalExtensionDto); } public void modifyRental(RentalDto rentalDto) { URI url = UriComponentsBuilder.fromHttpUrl(backEndConfiguration.getRentalEndpoint()).build().encode().toUri(); restTemplate.put(url, rentalDto); } public void closeRental(Long id) { URI url = UriComponentsBuilder.fromHttpUrl(backEndConfiguration.getRentalEndpoint() + "/" + id) .build().encode().toUri(); restTemplate.delete(url); } }
d1dcb4c96ee237a512caf475b0c6ee348d4a5209
9a4b46669513a4757efa05a0f6eedfa8b3891e03
/src/edu/harvard/mcb/leschziner/remote/RemoteMain.java
7a50c782017f989e90683849f67b5eb92cdafd85
[ "BSD-2-Clause" ]
permissive
spartango/EMExperiments
22a56ea50dd344885c4b67c7a87c98b4daf47d40
cc3b37dcd5b90a5e66093db4d74a63093a8202b2
refs/heads/master
2021-01-21T19:28:52.207153
2012-09-24T20:18:57
2012-09-24T20:18:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
package edu.harvard.mcb.leschziner.remote; import com.hazelcast.core.Hazelcast; public class RemoteMain { /** * @param args */ public static void main(String[] args) { System.out.println("[RemoteMain]: Connecting to cluster"); System.out.println("[RemoteMain]: Cluster Members -> " + Hazelcast.getCluster().getMembers().toString()); System.out.println("[RemoteMain]: Ready"); while (true) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
473d69771f462644bd2c24b819b06cc377adbaee
810b44864e4f6b84bf003039aac507a8b840733e
/app/models/Watch.java
ecb902d0f99aaa531b8058f85f86619f0b7b3026
[]
no_license
Venture-TheSphinxTeam/Sphinx
b1f322408dec7967621853380abdc7ebe44e152b
458f57c89e288c6e18059e3a810343405f59dab7
refs/heads/master
2020-04-05T22:08:09.501289
2014-05-20T17:32:49
2014-05-20T17:32:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,888
java
package models; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import helpers.OutgoingJSON; import play.Play; import javax.ws.rs.ProcessingException; import javax.ws.rs.core.Response; /** * Created by Stephen Yingling on 3/4/14. */ public class Watch { protected String entityType; protected long entityId; protected String userName; public Watch(String entityType, long entityId, String userName){ this.entityId = entityId; this.entityType = entityType; this.userName = userName; } public Watch(){} public Response sendWatch() throws JsonProcessingException, ProcessingException{ String voteStrTemp = Play.application().configuration().getString("watch.post_target"); voteStrTemp = voteStrTemp.replace(":entityType", entityType); voteStrTemp = voteStrTemp.replace(":entityId", Long.toString(entityId)); voteStrTemp = voteStrTemp.replace(":userName", userName); voteStrTemp = voteStrTemp.replace(":watchStatus","watch"); return sendWatch(voteStrTemp); } public Response sendWatch(String url) throws JsonProcessingException, ProcessingException{ OutgoingJSON out = new OutgoingJSON(url, this.JSONRep()); Response response = out.sendJson(); return response; } public Response sendUnWatch() throws JsonProcessingException, ProcessingException { String voteStrTemp = Play.application().configuration().getString("watch.post_target"); voteStrTemp = voteStrTemp.replace(":entityType", entityType); voteStrTemp = voteStrTemp.replace(":entityId", Long.toString(entityId)); voteStrTemp = voteStrTemp.replace(":userName", userName); voteStrTemp = voteStrTemp.replace(":voteStatus","unwatch"); return sendUnWatch(voteStrTemp); } public Response sendUnWatch(String url){ OutgoingJSON out = new OutgoingJSON(url, this.JSONRep()); Response response = out.sendJson(); return response; } public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public long getEntityId() { return entityId; } public void setEntityId(long entityId) { this.entityId = entityId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String JSONRep(){ ObjectMapper om = new ObjectMapper(); String result = ""; try { result = om.writeValueAsString(this); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } }
3fdedba260519cf93da6212ad525b9ece9ab8227
573d321d994b2b6179202d85f6371815dc09c996
/spring-quartz/src/main/java/com/stackroute/domain/Theatre.java
aebbc1f942bd29f23c37950915de7e55101e4fb3
[]
no_license
ayush-09meshram/eventbuzz
aab6ba0afe05ad631afb9deeffee9ee27c4ba146
525e840a86aba67f9e934c407aa4253d9b2abd9b
refs/heads/master
2020-04-10T18:33:02.034974
2018-12-10T16:57:20
2018-12-10T16:57:20
161,207,311
0
0
null
null
null
null
UTF-8
Java
false
false
1,854
java
package com.stackroute.domain; import java.util.List; //@Data //@NoArgsConstructor //@AllArgsConstructor public class Theatre { private int theatreId; private String theatreName; private String theatreCity; private String theatreAddress; private List<Timing> timings; public Theatre() { } public Theatre(int theatreId, String theatreName, String theatreCity, String theatreAddress, List<Timing> timings) { this.theatreId = theatreId; this.theatreName = theatreName; this.theatreCity = theatreCity; this.theatreAddress = theatreAddress; this.timings = timings; } public int getTheatreId() { return theatreId; } public void setTheatreId(int theatreId) { this.theatreId = theatreId; } public String getTheatreName() { return theatreName; } public void setTheatreName(String theatreName) { this.theatreName = theatreName; } public String getTheatreCity() { return theatreCity; } public void setTheatreCity(String theatreCity) { this.theatreCity = theatreCity; } public String getTheatreAddress() { return theatreAddress; } public void setTheatreAddress(String theatreAddress) { this.theatreAddress = theatreAddress; } public List<Timing> getTimings() { return timings; } public void setTimings(List<Timing> timings) { this.timings = timings; } @Override public String toString() { return "Theatre{" + "theatreId=" + theatreId + ", theatreName='" + theatreName + '\'' + ", theatreCity='" + theatreCity + '\'' + ", theatreAddress='" + theatreAddress + '\'' + ", timings=" + timings + '}'; } }
fedfef4fde0a38e1be4e130b0ca5ea882b264ee4
876820356eeb1b602b1888e5f9f053a462174574
/modules/system/src/main/java/com/linln/modules/system/domain/Dept.java
d7fc257e17eb3396863c785bbefd89ecbb32442a
[ "Apache-2.0" ]
permissive
chengliang1/djproject
fd7d0004b21a3a36c656109e3370185f722521be
4e6296b72bf0f7cd492c7e4e230d352a5c28d169
refs/heads/master
2022-10-25T00:43:43.919295
2020-05-13T01:54:54
2020-05-13T01:54:54
233,251,710
1
0
Apache-2.0
2022-10-12T20:36:34
2020-01-11T15:20:17
JavaScript
UTF-8
Java
false
false
1,873
java
package com.linln.modules.system.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.linln.common.enums.StatusEnum; import com.linln.common.utils.StatusUtil; import lombok.Data; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import org.hibernate.annotations.Where; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * @date 12/02 */ @Data @Entity @Table(name = "sys_dept") @EntityListeners(AuditingEntityListener.class) @Where(clause = StatusUtil.NOT_DELETE) public class Dept implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** 部门名称 */ private String title; /** 父级编号 */ private Long pid; /** 所有父级编号 */ private String pids; /** 排序 */ private Integer sort; /** 备注 */ private String remark; /** 创建时间 */ @CreatedDate private Date createDate; /** 更新时间 */ @LastModifiedDate private Date updateDate; /** 创建者 */ @CreatedBy @ManyToOne(fetch = FetchType.LAZY) @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(name = "create_by") @JsonIgnore private User createBy; /** 更新者 */ @LastModifiedBy @ManyToOne(fetch = FetchType.LAZY) @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(name = "update_by") @JsonIgnore private User updateBy; /** 数据状态 */ private Byte status = StatusEnum.OK.getCode(); }
d5b743390bb0ee19b653b745eef29714e6071a64
4766cd53dbef6b7db931044945ce2116b2020b94
/app/src/main/java/com/training/apps/makeup/Adaptre/expandableRecView/ParentAdapter.java
91034a3159f223171f6ea204ae5e96969389eb64
[]
no_license
android-trianinig/HomeMakeup
d8c712761f250247ee038fa5a47e4d9d79a082c7
75580c280c62265f6ffff30d7696f280e079f264
refs/heads/master
2020-12-21T07:02:41.849086
2020-02-16T13:37:58
2020-02-16T13:37:58
236,347,846
0
0
null
null
null
null
UTF-8
Java
false
false
3,339
java
package com.training.apps.makeup.Adaptre.expandableRecView; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.training.apps.makeup.R; import com.training.apps.makeup.model.SelectedService; import com.training.apps.makeup.model.MyService; import net.cachapa.expandablelayout.ExpandableLayout; import java.util.List; public class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.ParentViewHolder> { private Context mContext; private List<MyService> myServices; private SelectedService selectedService; public ParentAdapter(Context context, List<MyService> myServices, SelectedService selectedService) { this.mContext = context; this.myServices = myServices; this.selectedService = selectedService; } @NonNull @Override public ParentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.expandable_list_parent_item, parent, false); return new ParentViewHolder(view); } @Override public void onBindViewHolder(@NonNull ParentViewHolder holder, int position) { MyService myService = myServices.get(position); holder.parentText.setText(myService.getServiceName()); holder.childRec.setAdapter(new ChildRecAdapter(mContext, myService.getChildServices(), selectedService)); holder.childRec.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)); holder.childRec.setHasFixedSize(true); } @Override public int getItemCount() { if (myServices == null || myServices.size() == 0) return 0; return myServices.size(); } public class ParentViewHolder extends RecyclerView.ViewHolder { TextView parentText; RecyclerView childRec; ImageView arrowImage; ExpandableLayout expandableLayout; ConstraintLayout parentLayout; public ParentViewHolder(@NonNull View itemView) { super(itemView); parentText = itemView.findViewById(R.id.parent_title); childRec = itemView.findViewById(R.id.child_rec_view); arrowImage = itemView.findViewById(R.id.arrow_img); expandableLayout = itemView.findViewById(R.id.expandable_layout); parentLayout = itemView.findViewById(R.id.parent_layout); parentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { expandOrCollapse(); } }); } private void expandOrCollapse() { if (expandableLayout.isExpanded()) { arrowImage.setImageResource(R.drawable.ic_purple_arrow); expandableLayout.collapse(true); } else { arrowImage.setImageResource(R.drawable.ic_purple_arrow_up); expandableLayout.expand(true); } } } }
1ea54bde44506b7390b4de79c5dcc201b844e6b0
db0e977a0da26be2c016d4a7bbd6b802f3e49dc3
/src/week3/Week3.java
519b347b0d3beee6941e4517c388f8e488884621
[]
no_license
thang1405/oop2018
76f6d5da28d6805ebb606f3c57d91d3882b7e299
3c75941982a38e64358d30f109d57bdb5e00607f
refs/heads/master
2020-03-28T16:09:05.519048
2018-11-22T16:34:28
2018-11-22T16:34:28
148,664,565
1
0
null
2018-09-21T05:12:31
2018-09-13T16:13:28
Java
UTF-8
Java
false
false
1,228
java
package week3; public class Week3 { public static int max(int m, int n) { // TODO: Tìm giá trị lớn nhất của hai số nguyên, giá trị trả về của hàm là số lớn nhất if(m>n) return m; else return n; } public static int minOfArray(int[] array) { // TODO: Tìm giá trị nhỏ nhất của của một mảng số nguyên (kích thước mảng <= 100 phần tử) int min=array[0]; for(int i=0;i<array.length;i++){ if(array[i]<min) min = array[i]; } return min; } /** * Chương trình tính chỉ số BMI và in ra kết quả đánh giá * @param weight cân nặng * @param height chiều cao * @return Thiếu cân, Bình thường, Thừa cân, Béo phì */ public static String calculateBMI(double weight, double height) { // TODO: Viết chương trình tính chỉ số BMI và in ra kết quả đánh giá double bmi = weight/(height*height); if(bmi < 18.5) return "Thieu can"; else if(bmi>=18.5 && bmi <=22.99) return "Binh thuong"; else if(bmi>=23 && bmi <=24.99) return "Thua can"; else return "Beo phi"; } }
92769fe958454124082dc47a15653164926ec6a9
f1c3812086e813ae9561d966ec4f8d72e2019bfd
/cargaDeDatos/src/main/java/Book.java
3eadf966a2d98505b5eb9596c7721fec1697b3bb
[]
no_license
rdambrosioz/pruebas
e580bfc4ab167de9c55464fe372c045be3ebab12
87abf61c0e01d8ea81dd30801de16101c7b9278c
refs/heads/master
2022-09-24T12:23:21.393129
2020-06-03T18:38:41
2020-06-03T18:38:41
265,826,132
0
0
null
null
null
null
UTF-8
Java
false
false
1,708
java
public class Book { private Long book_id; private String isbn; private String[] authors; private Integer original_publication_year; private String original_title; private String title; private String language_code; private String image_url; public Book(long book_id, String isbn, String[] authors, int original_publication_year, String original_title, String title, String language_code, String image_url) { this.book_id = book_id; this.isbn = isbn; this.authors = authors; this.original_publication_year = original_publication_year; this.original_title = original_title; this.title = title; this.language_code = language_code; this.image_url = image_url; } public Book (String[] args){ if (args.length == 8){ this.book_id = Long.parseLong(args[0]); this.isbn = args[1]; this.authors[0] = args[2]; this.original_publication_year = Integer.parseInt(args[3]); this.original_title = args[4]; this.title = args[5]; this.language_code = args[6]; this.image_url = args[7]; } } @Override public String toString() { return "book_id: " + book_id + "\n" + "isbn: " + isbn + "\n" + "authors: " + authors + "\n" + "original_publication_year: " + original_publication_year+ "\n" + "original_title: " + original_title + "\n" + "title: " + title + "\n" + "language_code: " + language_code + "\n" + "image_url: " + image_url + "\n" + "\n\n"; } }
b0499de5eb9b9aa4127c5b6bb989c9eb34e87a1a
85061ebb2d5f43f5b8bbc781d6dd667b892b1a8f
/FlinkAlarmOpsSys-JavaWorkspace/Flink_Counter/src/main/java/com/ktvmi/flinkops/counter/entity/WordWithCount.java
ba7062753f7b7385bc9b5c9b825b034422791a66
[]
no_license
zyclove/FlinkAlarmOpsSys
771e2f3e45f444729ecd43a95d2a50fbe1e9ef7b
5d3918d8fe78301f2107eaf8505aad25c1f1394e
refs/heads/master
2023-05-12T09:37:26.553213
2019-08-19T09:19:44
2019-08-19T09:19:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
615
java
package com.ktvmi.flinkops.counter.entity; public class WordWithCount { private String word; private int count; public WordWithCount() {} public WordWithCount(String word, int count) { this.word = word; this.count = count; } public int getCount() { return count; } public String getWord() { return word; } public void setCount(int count) { this.count = count; } public void setWord(String word) { this.word = word; } @Override public String toString() { return word + " : " + count; } }
62f4d3a91ac1797b44924c3569f0a90c3041c0f0
a57a63100d60ff094518568e1d0fc445ab279553
/1.JavaSyntax/src/com/javarush/task/task04/task0438/Solution.java
acedd486ee193b272df4694aa0788a7e0e3533c1
[]
no_license
dananita/TasksfromJavaRush
cc4c5a5c37a131948becd12dc3a8ea4d3b9234b2
456c714b7dfb8212ac7ea1200044a1d1e118c5fa
refs/heads/master
2021-09-11T19:37:26.166085
2018-04-11T15:03:22
2018-04-11T15:03:22
111,551,640
0
0
null
null
null
null
UTF-8
Java
false
false
419
java
package com.javarush.task.task04.task0438; /* Рисуем линии */ public class Solution { public static void main(String[] args) throws Exception { //напишите тут ваш код for (int i = 0; i <=9 ; i++) { System.out.print(8); } System.out.println("\n"); for (int j = 0; j <=9 ; j++) { System.out.println(8); } } }
63c90e2e1aef0404205d73a76ff32d2751955503
77eabfb69056924f2a471cc47670d3c9314e2531
/eInventory/src/sprint6/US672_AbilityToCreateManualPurchaseVendors.java
f06be3a04e3056b4e60906d7ba205e582f65b4f9
[]
no_license
QsrSoftAutomation/QsrSoftAutomation
5f915ad70beba94cf3ed3ee62bf7f64e874fd6da
a09d80572daf5157176493015d395e00c57c2c4b
refs/heads/master
2021-01-10T16:08:28.299400
2016-01-22T16:49:08
2016-01-22T16:49:08
50,193,687
0
0
null
null
null
null
UTF-8
Java
false
false
14,010
java
package sprint6; import java.io.IOException; import jxl.read.biff.BiffException; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Test; import common.Base; import common.GlobalVariable; import common.ReadTestData; import common.Reporter; import eInventoryPageClasses.HomePage; import eInventoryPageClasses.ManualInvoiceNewPage; import eInventoryPageClasses.ManualVendorsPage; import eInventoryPageClasses.PurchasesPage; import eInventoryPageClasses.RawItemInformationPage; import sprint2.AbstractTest; public class US672_AbilityToCreateManualPurchaseVendors extends AbstractTest { // Verify the user is able to select "Manual vendors " option from inventory drop down and move to "Manual Vendors" landing page. @Test() public void Sprint6_US672_TC1212() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { String storeId=GlobalVariable.StoreId; String userId = GlobalVariable.userId; HomePage homePage=PageFactory.initElements(driver, HomePage.class); //Go to purchase landing page and verify that it is redirected boolean result=homePage.selectUser(userId).selectLocation(storeId).navigateToInventoryManagement().goToManualVendorsPage().ManualVendors_Label.isDisplayed(); if(result) { Reporter.reportPassResult(browser, "Sprint6_US672_TC1212", "User should be redirected to Manual Vendor page", "Pass"); } else { Reporter.reportTestFailure(browser, "Sprint6_US672_TC1212", "Sprint6_US672_TC1212", "User should be redirected to Manual Vendor page", "Fail"); AbstractTest.takeSnapShot("Sprint6_US672_TC1212"); } } // Verify the user is able to enter vendor name while creating a manual vendor from manual vendors landing page. @Test() public void Sprint6_US672_TC1213() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { HSSFSheet manualVendorPageSheet = ReadTestData.getTestDataSheet("Sprint6_US672_TC1213", "Object1"); String vendorName = ReadTestData.getTestData(manualVendorPageSheet, "VendorName"); String storeId=GlobalVariable.StoreId; String userId = GlobalVariable.userId; HomePage homePage=PageFactory.initElements(driver, HomePage.class); ManualVendorsPage manualVendorPage=PageFactory.initElements(driver, ManualVendorsPage.class); //Go to Manual vendors page and click on Add vendor button homePage.selectUser(userId).selectLocation(storeId).navigateToInventoryManagement().goToManualVendorsPage().AddVendor_BT.click(); wait.until(ExpectedConditions.visibilityOf(manualVendorPage.AddvendorDetailsPopUp_VendorName_TB)); //enter the vendor name in vendor name text box manualVendorPage.AddvendorDetailsPopUp_VendorName_TB.clear(); manualVendorPage.AddvendorDetailsPopUp_VendorName_TB.sendKeys(vendorName); //verify the entered text if(manualVendorPage.AddvendorDetailsPopUp_VendorName_TB.getAttribute("value").equalsIgnoreCase(vendorName)) { Reporter.reportPassResult(browser, "Sprint6_US672_TC1213", "User should be able to enter the vendor name", "Pass"); } else { Reporter.reportTestFailure(browser, "Sprint6_US672_TC1213", "Sprint6_US672_TC1213", "User should be able to enter the vendor name", "Fail"); AbstractTest.takeSnapShot("Sprint6_US672_TC1213"); } } // Verify the impact on manual purchase detail screens once new manual purchase vendor is created. @Test() public void Sprint6_US672_TC1220() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { String vendorName=null; String storeId=GlobalVariable.StoreId; String userId = GlobalVariable.userId; HomePage homePage=PageFactory.initElements(driver, HomePage.class); PurchasesPage purchasesPage=PageFactory.initElements(driver, PurchasesPage.class); ManualInvoiceNewPage manualInvoiceNewPage=PageFactory.initElements(driver, ManualInvoiceNewPage.class); //go to Manual Vendor page and click on Add Vendor button vendorName=homePage.selectUser(userId).selectLocation(storeId).navigateToInventoryManagement().goToManualVendorsPage().vendorName_List.get(0).getText(); //Go to purchase landing page and verify that vendor is present or not homePage.Menu_DD_BT.click(); wait.until(ExpectedConditions.visibilityOf(homePage.Menu_OtherInventoryFunction_Back_BT)); Thread.sleep(2000); homePage.Menu_OtherInventoryFunction_Back_BT.click(); wait.until(ExpectedConditions.visibilityOf(homePage.Purchases_BT)); homePage.Purchases_BT.click(); wait.until(ExpectedConditions.visibilityOf(purchasesPage.Purchases_Label)); int vendorNumber=purchasesPage.goToManualInvoiceNewPage().VendorName_List.size(); for(int i=0;i<=vendorNumber;i++) { if(manualInvoiceNewPage.VendorName_List.get(i).getText().equalsIgnoreCase(vendorName)) { Reporter.reportPassResult(browser, "Sprint6_US672_TC1220", "Vendor name should display in vendor name drop down", "Pass"); break; } else if(i==vendorNumber) { Reporter.reportTestFailure(browser, "Sprint6_US672_TC1220", "Sprint6_US672_TC1220", "Vendor name should display in vendor name drop down", "Fail"); AbstractTest.takeSnapShot("Sprint6_US672_TC1220"); } else { continue; } } } // Verify the association of WRINS to created manual vendor from raw item information page @Test() public void Sprint6_US672_TC1282() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { String casePrice="144.4444"; String storeId=GlobalVariable.StoreId; String userId = GlobalVariable.userId; HomePage homePage=PageFactory.initElements(driver, HomePage.class); RawItemInformationPage rawiteminformation=PageFactory.initElements(driver, RawItemInformationPage.class); //Navigate to raw item information page homePage.selectUser(userId).selectLocation(storeId).navigateToInventoryManagement().goToRawItemInformationPage(); //Enter sample wRIN ID in search box and select one raw item rawiteminformation.Search_TB.sendKeys(GlobalVariable.rawItemInformationWrin); action.sendKeys(Keys.SPACE).build().perform(); Thread.sleep(1500); action.sendKeys(Keys.BACK_SPACE).build().perform(); driver.findElement(By.xpath("//strong[text()='"+GlobalVariable.rawItemInformationWrin+"']")).click(); //Enter case price in case price field rawiteminformation.CasePrice_TB.clear(); rawiteminformation.CasePrice_TB.sendKeys(casePrice); //Select monthly from list type drop down Select select = new Select(rawiteminformation.ListType_DD); select.selectByVisibleText("Monthly"); //Select a option from the McDonalds GL Account drop down Select select1=new Select(rawiteminformation.McDonaldsGLAccount_DD); select1.selectByIndex(2); //Select the vendor from the primary vendor drop down Select select2=new Select(rawiteminformation.PrimaryVendor_DD); select2.selectByVisibleText(GlobalVariable.vendorName); //click on save button rawiteminformation.Save_BT.click(); Thread.sleep(4000); if(driver.getPageSource().contains("Changes Saved")) { Reporter.reportPassResult(browser, "Sprint6_US672_TC1282", "Confirmation message should be displayed", "Pass"); } else { Reporter.reportTestFailure(browser, "Sprint6_US672_TC1282", "Sprint6_US672_TC1282", "Confirmation message should be displayed", "Fail"); AbstractTest.takeSnapShot("Sprint6_US672_TC1282"); } } //Verify the user is able to enter Manual number while creating a manual vendor from manual vendors landing page. @Test() public void Sprint6_US672_TC1292() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { String storeId=GlobalVariable.StoreId; String userId = GlobalVariable.userId; String manualNumber=Base.randomNumberFiveDigit(); String vendorName="Test"+Base.randomNumberFiveDigit(); HomePage homePage=PageFactory.initElements(driver, HomePage.class); ManualVendorsPage manualVendorPage=PageFactory.initElements(driver, ManualVendorsPage.class); //Go to Manual vendors page and click on Add vendor button homePage.selectUser(userId).selectLocation(storeId).navigateToInventoryManagement().goToManualVendorsPage().AddVendor_BT.click(); wait.until(ExpectedConditions.visibilityOf(manualVendorPage.AddvendorDetailsPopUp_ManualNumber_TB)); manualVendorPage.AddvendorDetailsPopUp_VendorName_TB.sendKeys(vendorName); manualVendorPage.AddvendorDetailsPopUp_ManualNumber_TB.sendKeys(manualNumber); manualVendorPage.AddvendorDetailsPopUp_SaveVendor_BT.click(); wait.until(ExpectedConditions.visibilityOf(manualVendorPage.Confirmation_Message)); //fetch the size of vendor list Thread.sleep(5000); int size=driver.findElements(By.xpath("//table[@id='vendor_info']/tbody/tr")).size(); String text=driver.findElement(By.xpath("//table[@id='vendor_info']/tbody/tr["+size+"]/td[2]")).getText(); if(text.equalsIgnoreCase(manualNumber)) { Reporter.reportPassResult(browser, "Sprint6_US672_TC1292", "User should be able to enter the manual number", "Pass"); } else { Reporter.reportTestFailure(browser, "Sprint6_US672_TC1292", "Sprint6_US672_TC1292", "User should be able to enter the manual number", "Fail"); AbstractTest.takeSnapShot("Sprint6_US672_TC1292"); } } // Verify the completion of new vendor from "Manual Vendors" Landing page. @Test() public void Sprint6_US672_TC1295() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { String storeId = GlobalVariable.StoreId; String userId = GlobalVariable.userId; String vendorName = "Test" + Base.randomNumberFiveDigit(); String manualNumber = Base.randomNumberFiveDigit(); HomePage homePage = PageFactory.initElements(driver, HomePage.class); ManualVendorsPage manualVendorPage = PageFactory.initElements(driver,ManualVendorsPage.class); // Go to Manual Vendor page and click on Add Vendor button homePage.selectUser(userId).selectLocation(storeId) .navigateToInventoryManagement().goToManualVendorsPage().AddVendor_BT.click(); // Enter the vendor name in vendor name text box wait.until(ExpectedConditions.visibilityOf(manualVendorPage.AddvendorDetailsPopUp_VendorName_TB)); Thread.sleep(1500); manualVendorPage.AddvendorDetailsPopUp_VendorName_TB.sendKeys(vendorName); // Enter the value in the manual number text box manualVendorPage.AddvendorDetailsPopUp_ManualNumber_TB.sendKeys(manualNumber); // click on save button manualVendorPage.AddvendorDetailsPopUp_SaveVendor_BT.click(); wait.until(ExpectedConditions.visibilityOf(manualVendorPage.Confirmation_Message)); Thread.sleep(2000); if (manualVendorPage.VendorName_Row(vendorName).isDisplayed()) { Reporter.reportPassResult( browser, "Sprint6_US672_TC1295", "Added Vendor should display in Manage vendor page", "Pass"); } else { Reporter.reportTestFailure( browser, "Sprint6_US672_TC1295","Sprint6_US672_TC1295", "Added Vendor should display in Manage vendor page", "Fail"); AbstractTest.takeSnapShot("Sprint6_US672_TC1295"); } } // Verify the impact on raw item information page once new manual purchase vendor is created. @Test() public void Sprint6_US672_TC1297() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { String storeId = GlobalVariable.StoreId; String userId = GlobalVariable.userId; String vendorName = "Test" + Base.randomNumberFiveDigit(); HomePage homePage = PageFactory.initElements(driver, HomePage.class); ManualVendorsPage manualVendorPage = PageFactory.initElements(driver,ManualVendorsPage.class); RawItemInformationPage rawItemInformationPage = PageFactory.initElements(driver, RawItemInformationPage.class); // Go to Manual Vendor page and click on Add Vendor button homePage.selectUser(userId).selectLocation(storeId) .navigateToInventoryManagement().goToManualVendorsPage().AddVendor_BT.click(); // Enter the vendor name in vendor name text box manualVendorPage.AddvendorDetailsPopUp_VendorName_TB.sendKeys(vendorName); // click on save button manualVendorPage.AddvendorDetailsPopUp_SaveVendor_BT.click(); wait.until(ExpectedConditions.visibilityOf(manualVendorPage.Confirmation_Message)); Thread.sleep(3000); // Go to raw item information page homePage.Menu_DD_BT.click(); wait.until(ExpectedConditions.visibilityOf(homePage.RawItemInformation_BT)); homePage.RawItemInformation_BT.click(); wait.until(ExpectedConditions.visibilityOf(rawItemInformationPage.RawItemInformation_Label)); // Enter sample wRIN ID in search box and select one raw item rawItemInformationPage.Search_TB.sendKeys(GlobalVariable.rawItemInformationWrin); action.sendKeys(Keys.SPACE).build().perform(); Thread.sleep(1500); action.sendKeys(Keys.BACK_SPACE).build().perform(); driver.findElement(By.xpath("//strong[text()='"+ GlobalVariable.rawItemInformationWrin + "']")).click(); // Verify that added vendor is showing in the Primary Vendor drop down for (int i = 0; i <= rawItemInformationPage.PrimaryVendor_VendorName_List.size(); i++) { if (rawItemInformationPage.PrimaryVendor_VendorName_List.get(i).getText().equalsIgnoreCase(vendorName)) { Reporter.reportPassResult( browser,"Sprint6_US672_TC1297", "Added Vendor should display in Primary Vendor dropdown", "Pass"); break; } else if (i == rawItemInformationPage.PrimaryVendor_VendorName_List.size()) { Reporter.reportTestFailure( browser,"Sprint6_US672_TC1297","Sprint6_US672_TC1297", "Added Vendor should display in Primary Vendor dropdown", "Fail"); AbstractTest.takeSnapShot("Sprint6_US672_TC1297"); } else { continue; } } } }
a75819ddef24c0af343ec492499bc742cf95e369
2ffa22037fff88d79632f8bbef2ed29cbc397204
/app/src/test/java/com/example/developer/atourinsulaimany/ExampleUnitTest.java
fecb2db6ba45472db53c2b4c44f9e5c53ada5522
[]
no_license
binar1/ATourinSulaimany
52698e31b4c20e4b9e0974ff6b7b456a64ab2946
14d29a1dade974adb798e7ad78c3647611430ce9
refs/heads/master
2020-05-17T14:39:43.196477
2019-04-27T12:21:54
2019-04-27T12:21:54
183,769,306
0
0
null
null
null
null
UTF-8
Java
false
false
416
java
package com.example.developer.atourinsulaimany; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
7c9d5ab63ba115b311779a7abaa30b47a1fc6b1b
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/16/16_ccca82be1b05accfca5a032237dc94f39e1ccfa5/StandaloneMockMvcBuilder/16_ccca82be1b05accfca5a032237dc94f39e1ccfa5_StandaloneMockMvcBuilder_s.java
1e5150ed92937fab0c5d7851d776ed9d4b6521a3
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
16,434
java
/* * Copyright 2002-2012 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 org.springframework.test.web.servlet.setup; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.mock.web.MockServletContext; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.validation.Validator; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationObjectSupport; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.FlashMapManager; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.handler.MappedInterceptor; import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.servlet.support.SessionFlashMapManager; import org.springframework.web.servlet.theme.FixedThemeResolver; import org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * A MockMvcBuilder that accepts {@code @Controller} registrations thus allowing * full control over the instantiation and the initialization of controllers and * their dependencies similar to plain unit tests, and also making it possible * to test one controller at a time. * * <p>This builder creates the minimum infrastructure required by the * {@link DispatcherServlet} to serve requests with annotated controllers and * also provides methods to customize it. The resulting configuration and * customizations possible are equivalent to using the MVC Java config except * using builder style methods. * * <p>To configure view resolution, either select a "fixed" view to use for every * performed request (see {@link #setSingleView(View)}) or provide a list of * {@code ViewResolver}'s, see {@link #setViewResolvers(ViewResolver...)}. * * @author Rossen Stoyanchev * @since 3.2 */ public class StandaloneMockMvcBuilder extends DefaultMockMvcBuilder<StandaloneMockMvcBuilder> { private final Object[] controllers; private List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); private List<HandlerMethodArgumentResolver> customArgumentResolvers = new ArrayList<HandlerMethodArgumentResolver>(); private List<HandlerMethodReturnValueHandler> customReturnValueHandlers = new ArrayList<HandlerMethodReturnValueHandler>(); private final List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>(); private Validator validator = null; private ContentNegotiationManager contentNegotiationManager; private FormattingConversionService conversionService = null; private List<HandlerExceptionResolver> handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(); private Long asyncRequestTimeout; private List<ViewResolver> viewResolvers; private LocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); private FlashMapManager flashMapManager = null; private boolean useSuffixPatternMatch = true; private boolean useTrailingSlashPatternMatch = true; /** * Protected constructor. Not intended for direct instantiation. * @see MockMvcBuilders#standaloneSetup(Object...) */ protected StandaloneMockMvcBuilder(Object... controllers) { super(new StubWebApplicationContext(new MockServletContext())); Assert.isTrue(!ObjectUtils.isEmpty(controllers), "At least one controller is required"); this.controllers = controllers; } /** * Set the message converters to use in argument resolvers and in return value * handlers, which support reading and/or writing to the body of the request * and response. If no message converters are added to the list, a default * list of converters is added instead. */ public StandaloneMockMvcBuilder setMessageConverters(HttpMessageConverter<?>...messageConverters) { this.messageConverters = Arrays.asList(messageConverters); return this; } /** * Provide a custom {@link Validator} instead of the one created by default. * The default implementation used, assuming JSR-303 is on the classpath, is * {@link org.springframework.validation.beanvalidation.LocalValidatorFactoryBean}. */ public StandaloneMockMvcBuilder setValidator(Validator validator) { this.validator = validator; return this; } /** * Provide a conversion service with custom formatters and converters. * If not set, a {@link DefaultFormattingConversionService} is used by default. */ public StandaloneMockMvcBuilder setConversionService(FormattingConversionService conversionService) { this.conversionService = conversionService; return this; } /** * Add interceptors mapped to all incoming requests. */ public StandaloneMockMvcBuilder addInterceptors(HandlerInterceptor... interceptors) { addMappedInterceptors(null, interceptors); return this; } /** * Add interceptors mapped to a set of path patterns. */ public StandaloneMockMvcBuilder addMappedInterceptors(String[] pathPatterns, HandlerInterceptor... interceptors) { for (HandlerInterceptor interceptor : interceptors) { this.mappedInterceptors.add(new MappedInterceptor(pathPatterns, interceptor)); } return this; } /** * Set a ContentNegotiationManager. */ protected StandaloneMockMvcBuilder setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { this.contentNegotiationManager = contentNegotiationManager; return this; } /** * Specify the timeout value for async execution. In Spring MVC Test, this * value is used to determine how to long to wait for async execution to * complete so that a test can verify the results synchronously. * @param timeout the timeout value in milliseconds */ public StandaloneMockMvcBuilder setAsyncRequestTimeout(long timeout) { this.asyncRequestTimeout = timeout; return this; } /** * Provide custom resolvers for controller method arguments. */ public StandaloneMockMvcBuilder setCustomArgumentResolvers(HandlerMethodArgumentResolver... argumentResolvers) { this.customArgumentResolvers = Arrays.asList(argumentResolvers); return this; } /** * Provide custom handlers for controller method return values. */ public StandaloneMockMvcBuilder setCustomReturnValueHandlers(HandlerMethodReturnValueHandler... handlers) { this.customReturnValueHandlers = Arrays.asList(handlers); return this; } /** * Set the HandlerExceptionResolver types to use. */ public StandaloneMockMvcBuilder setHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { this.handlerExceptionResolvers = exceptionResolvers; return this; } /** * Set up view resolution with the given {@link ViewResolver}s. * If not set, an {@link InternalResourceViewResolver} is used by default. */ public StandaloneMockMvcBuilder setViewResolvers(ViewResolver...resolvers) { this.viewResolvers = Arrays.asList(resolvers); return this; } /** * Sets up a single {@link ViewResolver} that always returns the provided * view instance. This is a convenient shortcut if you need to use one * View instance only -- e.g. rendering generated content (JSON, XML, Atom). */ public StandaloneMockMvcBuilder setSingleView(View view) { this.viewResolvers = Collections.<ViewResolver>singletonList(new StaticViewResolver(view)); return this; } /** * Provide a LocaleResolver instance. * If not provided, the default one used is {@link AcceptHeaderLocaleResolver}. */ public StandaloneMockMvcBuilder setLocaleResolver(LocaleResolver localeResolver) { this.localeResolver = localeResolver; return this; } /** * Provide a custom FlashMapManager instance. * If not provided, {@code SessionFlashMapManager} is used by default. */ public StandaloneMockMvcBuilder setFlashMapManager(FlashMapManager flashMapManager) { this.flashMapManager = flashMapManager; return this; } /** * Whether to use suffix pattern match (".*") when matching patterns to * requests. If enabled a method mapped to "/users" also matches to "/users.*". * <p>The default value is {@code true}. */ public StandaloneMockMvcBuilder setUseSuffixPatternMatch(boolean useSuffixPatternMatch) { this.useSuffixPatternMatch = useSuffixPatternMatch; return this; } /** * Whether to match to URLs irrespective of the presence of a trailing slash. * If enabled a method mapped to "/users" also matches to "/users/". * <p>The default value is {@code true}. */ public StandaloneMockMvcBuilder setUseTrailingSlashPatternMatch(boolean useTrailingSlashPatternMatch) { this.useTrailingSlashPatternMatch = useTrailingSlashPatternMatch; return this; } protected void initWebAppContext(WebApplicationContext cxt) { StubWebApplicationContext mockCxt = (StubWebApplicationContext) cxt; registerMvcSingletons(mockCxt); cxt.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, mockCxt); } private void registerMvcSingletons(StubWebApplicationContext cxt) { StandaloneConfiguration configuration = new StandaloneConfiguration(); RequestMappingHandlerMapping handlerMapping = configuration.requestMappingHandlerMapping(); handlerMapping.setServletContext(cxt.getServletContext()); handlerMapping.setApplicationContext(cxt); cxt.addBean("requestMappingHandlerMapping", handlerMapping); RequestMappingHandlerAdapter handlerAdapter = configuration.requestMappingHandlerAdapter(); handlerAdapter.setServletContext(cxt.getServletContext()); handlerAdapter.setApplicationContext(cxt); handlerAdapter.afterPropertiesSet(); cxt.addBean("requestMappingHandlerAdapter", handlerAdapter); cxt.addBean("handlerExceptionResolver", configuration.handlerExceptionResolver()); cxt.addBeans(initViewResolvers(cxt)); cxt.addBean(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, this.localeResolver); cxt.addBean(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, new FixedThemeResolver()); cxt.addBean(DispatcherServlet.REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, new DefaultRequestToViewNameTranslator()); this.flashMapManager = new SessionFlashMapManager(); cxt.addBean(DispatcherServlet.FLASH_MAP_MANAGER_BEAN_NAME, this.flashMapManager); } private List<ViewResolver> initViewResolvers(WebApplicationContext wac) { this.viewResolvers = (this.viewResolvers == null) ? Arrays.<ViewResolver>asList(new InternalResourceViewResolver()) : this.viewResolvers; for (Object viewResolver : this.viewResolvers) { if (viewResolver instanceof WebApplicationObjectSupport) { ((WebApplicationObjectSupport) viewResolver).setApplicationContext(wac); } } return this.viewResolvers; } /** Using the MVC Java configuration as the starting point for the "standalone" setup */ private class StandaloneConfiguration extends WebMvcConfigurationSupport { @Override public RequestMappingHandlerMapping requestMappingHandlerMapping() { StaticRequestMappingHandlerMapping handlerMapping = new StaticRequestMappingHandlerMapping(); handlerMapping.registerHandlers(controllers); handlerMapping.setUseSuffixPatternMatch(useSuffixPatternMatch); handlerMapping.setUseTrailingSlashMatch(useTrailingSlashPatternMatch); handlerMapping.setOrder(0); handlerMapping.setInterceptors(getInterceptors()); return handlerMapping; } @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.addAll(messageConverters); } @Override protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.addAll(customArgumentResolvers); } @Override protected void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { returnValueHandlers.addAll(customReturnValueHandlers); } @Override protected void addInterceptors(InterceptorRegistry registry) { for (MappedInterceptor interceptor : mappedInterceptors) { InterceptorRegistration registration = registry.addInterceptor(interceptor.getInterceptor()); if (interceptor.getPathPatterns() != null) { registration.addPathPatterns(interceptor.getPathPatterns()); } } } @Override public ContentNegotiationManager mvcContentNegotiationManager() { return (contentNegotiationManager != null) ? contentNegotiationManager : super.mvcContentNegotiationManager(); } @Override public FormattingConversionService mvcConversionService() { return (conversionService != null) ? conversionService : super.mvcConversionService(); } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { if (asyncRequestTimeout != null) { configurer.setDefaultTimeout(asyncRequestTimeout); } } @Override public Validator mvcValidator() { Validator mvcValidator = (validator != null) ? validator : super.mvcValidator(); if (mvcValidator instanceof InitializingBean) { try { ((InitializingBean) mvcValidator).afterPropertiesSet(); } catch (Exception e) { throw new BeanInitializationException("Failed to initialize Validator", e); } } return mvcValidator; } @Override protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { exceptionResolvers.addAll(StandaloneMockMvcBuilder.this.handlerExceptionResolvers); } } /** A {@code RequestMappingHandlerMapping} that allows registration of controllers */ private static class StaticRequestMappingHandlerMapping extends RequestMappingHandlerMapping { public void registerHandlers(Object...handlers) { for (Object handler : handlers) { super.detectHandlerMethods(handler); } } } /** A {@link ViewResolver} that always returns same View */ private static class StaticViewResolver implements ViewResolver { private final View view; public StaticViewResolver(View view) { this.view = view; } public View resolveViewName(String viewName, Locale locale) throws Exception { return this.view; } } }
4f6ff958c70531479c4538a85779de4f8818901e
aec51e852cbb080b7a08fd5a4a15cb412c673d7f
/workspace/ch08/src/ExceptionEx04.java
36db79bfb87c1bdc6e00ec799708f323e3203190
[]
no_license
finalsoul1/java
4b12b1c89412a7d17793c74ee27898581fb86c85
18dce8654b3b9490ce39e8d2114bcde912e32737
refs/heads/master
2020-03-28T15:27:38.084297
2018-09-13T07:00:05
2018-09-13T07:00:05
148,595,549
0
0
null
null
null
null
UHC
Java
false
false
788
java
class ExceptionEx04 { public static void main(String args[]) { System.out.println(1); System.out.println(2); try { System.out.println(3); System.out.println(4); // throw new ArithmeticException(); throw new RuntimeException(); } catch (IndexOutOfBoundsException e) { // try부분에서 발생한 예외 instanceof Exception이 true일 때 // Exception e = try부분에서 발생한 예외 할당하고 catch 블록안에 코드를 수행한다 System.out.println(5_1); } catch (ArithmeticException e) { System.out.println(5_2); } catch (Exception e) { // 예외클래스 상속트리에서 부모 클래스를 하단에 배치해야 한다 System.out.println(5_3); } // try-catch의 끝 System.out.println(6); } // main메서드의 끝 }
78c7d14152acc259f5ee2c682cdb614c4af35967
5d50323c9230a9abf300738d7d40840ca8a5dca0
/app/src/main/java/com/dxq/netease/fragment/MeFragment.java
55a150c108f502ae3142f90a148c7f67cf4fd9e9
[]
no_license
CREEPERDCH/netease
21f8e86e4a4aaa61470fbac32776625be5d69261
84a4b6f00af5307a389581ccb9bc45313e2055e4
refs/heads/master
2020-12-30T11:03:21.900323
2017-07-31T03:51:50
2017-07-31T03:51:50
98,845,672
0
0
null
null
null
null
UTF-8
Java
false
false
168
java
package com.dxq.netease.fragment; import android.support.v4.app.Fragment; /** * Created by CREEPER_D on 2017/7/20. */ public class MeFragment extends Fragment { }
5df92eb225358d84871e76f83a306223354dff1a
ed160a474b136138f2c430d215f56ab67ed4a87f
/src/main/java/com/sample/crud/exception/ResourceNotFoundException.java
9d88e63dd4a6067c3942db0be3bbbb0d64e94663
[]
no_license
Siva378/Crud-operations-springboot
cb4f479ba2d479caae73b61df8795c880336e2f1
656f3716ea374f6180404cb1d9a2ac669a4d45e5
refs/heads/main
2023-07-31T13:03:34.095790
2021-09-24T05:12:24
2021-09-24T05:12:24
409,837,714
0
0
null
null
null
null
UTF-8
Java
false
false
877
java
package com.sample.crud.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { private static final long serialVersionUID = 5344320715962995240L; private String resourceName; private String fieldName; private Object fieldValue; public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) { super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); this.resourceName = resourceName; this.fieldName = fieldName; this.fieldValue = fieldValue; } public String getResourceName() { return resourceName; } public String getFieldName() { return fieldName; } public Object getFieldValue() { return fieldValue; } }
4ba92816ef84fdf9a81d91cbc40f237de863901f
57b0c18f8f592f612f10861a0f889d4f600a1707
/src/test/java/io/github/scalp/application/repository/CustomAuditEventRepositoryIntTest.java
2f127b57be034b5271054e2c556e8d57c6dc6cb4
[]
no_license
BulkSecurityGeneratorProject/scalpApplication
e5ee51dc3ee82caaa4fd2888d421fd6604f78ebf
add898b1f40cb962de330fac05b3d23731495af8
refs/heads/master
2022-12-09T12:34:49.581960
2018-01-26T14:38:30
2018-01-26T14:38:30
296,672,424
0
0
null
2020-09-18T16:21:23
2020-09-18T16:21:22
null
UTF-8
Java
false
false
11,651
java
package io.github.scalp.application.repository; import io.github.scalp.application.ScalpApplicationApp; import io.github.scalp.application.config.Constants; import io.github.scalp.application.config.audit.AuditEventConverter; import io.github.scalp.application.domain.PersistentAuditEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpSession; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static io.github.scalp.application.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; /** * Test class for the CustomAuditEventRepository class. * * @see CustomAuditEventRepository */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ScalpApplicationApp.class) @Transactional public class CustomAuditEventRepositoryIntTest { @Autowired private PersistenceAuditEventRepository persistenceAuditEventRepository; @Autowired private AuditEventConverter auditEventConverter; private CustomAuditEventRepository customAuditEventRepository; private PersistentAuditEvent testUserEvent; private PersistentAuditEvent testOtherUserEvent; private PersistentAuditEvent testOldUserEvent; @Before public void setup() { customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter); persistenceAuditEventRepository.deleteAll(); Instant oneHourAgo = Instant.now().minusSeconds(3600); testUserEvent = new PersistentAuditEvent(); testUserEvent.setPrincipal("test-user"); testUserEvent.setAuditEventType("test-type"); testUserEvent.setAuditEventDate(oneHourAgo); Map<String, String> data = new HashMap<>(); data.put("test-key", "test-value"); testUserEvent.setData(data); testOldUserEvent = new PersistentAuditEvent(); testOldUserEvent.setPrincipal("test-user"); testOldUserEvent.setAuditEventType("test-type"); testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000)); testOtherUserEvent = new PersistentAuditEvent(); testOtherUserEvent.setPrincipal("other-test-user"); testOtherUserEvent.setAuditEventType("test-type"); testOtherUserEvent.setAuditEventDate(oneHourAgo); } @Test public void testFindAfter() { persistenceAuditEventRepository.save(testUserEvent); persistenceAuditEventRepository.save(testOldUserEvent); List<AuditEvent> events = customAuditEventRepository.find(Date.from(testUserEvent.getAuditEventDate().minusSeconds(3600))); assertThat(events).hasSize(1); AuditEvent event = events.get(0); assertThat(event.getPrincipal()).isEqualTo(testUserEvent.getPrincipal()); assertThat(event.getType()).isEqualTo(testUserEvent.getAuditEventType()); assertThat(event.getData()).containsKey("test-key"); assertThat(event.getData().get("test-key").toString()).isEqualTo("test-value"); assertThat(event.getTimestamp()).isEqualTo(Date.from(testUserEvent.getAuditEventDate())); } @Test public void testFindByPrincipal() { persistenceAuditEventRepository.save(testUserEvent); persistenceAuditEventRepository.save(testOldUserEvent); persistenceAuditEventRepository.save(testOtherUserEvent); List<AuditEvent> events = customAuditEventRepository .find("test-user", Date.from(testUserEvent.getAuditEventDate().minusSeconds(3600))); assertThat(events).hasSize(1); AuditEvent event = events.get(0); assertThat(event.getPrincipal()).isEqualTo(testUserEvent.getPrincipal()); assertThat(event.getType()).isEqualTo(testUserEvent.getAuditEventType()); assertThat(event.getData()).containsKey("test-key"); assertThat(event.getData().get("test-key").toString()).isEqualTo("test-value"); assertThat(event.getTimestamp()).isEqualTo(Date.from(testUserEvent.getAuditEventDate())); } @Test public void testFindByPrincipalNotNullAndAfterIsNull() { persistenceAuditEventRepository.save(testUserEvent); persistenceAuditEventRepository.save(testOtherUserEvent); List<AuditEvent> events = customAuditEventRepository.find("test-user", null); assertThat(events).hasSize(1); assertThat(events.get(0).getPrincipal()).isEqualTo("test-user"); } @Test public void testFindByPrincipalIsNullAndAfterIsNull() { persistenceAuditEventRepository.save(testUserEvent); persistenceAuditEventRepository.save(testOtherUserEvent); List<AuditEvent> events = customAuditEventRepository.find(null, null); assertThat(events).hasSize(2); assertThat(events).extracting("principal") .containsExactlyInAnyOrder("test-user", "other-test-user"); } @Test public void findByPrincipalAndType() { persistenceAuditEventRepository.save(testUserEvent); persistenceAuditEventRepository.save(testOldUserEvent); testOtherUserEvent.setAuditEventType(testUserEvent.getAuditEventType()); persistenceAuditEventRepository.save(testOtherUserEvent); PersistentAuditEvent testUserOtherTypeEvent = new PersistentAuditEvent(); testUserOtherTypeEvent.setPrincipal(testUserEvent.getPrincipal()); testUserOtherTypeEvent.setAuditEventType("test-other-type"); testUserOtherTypeEvent.setAuditEventDate(testUserEvent.getAuditEventDate()); persistenceAuditEventRepository.save(testUserOtherTypeEvent); List<AuditEvent> events = customAuditEventRepository.find("test-user", Date.from(testUserEvent.getAuditEventDate().minusSeconds(3600)), "test-type"); assertThat(events).hasSize(1); AuditEvent event = events.get(0); assertThat(event.getPrincipal()).isEqualTo(testUserEvent.getPrincipal()); assertThat(event.getType()).isEqualTo(testUserEvent.getAuditEventType()); assertThat(event.getData()).containsKey("test-key"); assertThat(event.getData().get("test-key").toString()).isEqualTo("test-value"); assertThat(event.getTimestamp()).isEqualTo(Date.from(testUserEvent.getAuditEventDate())); } @Test public void addAuditEvent() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); assertThat(persistentAuditEvent.getData()).containsKey("test-key"); assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value"); assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp().toInstant()); } @Test public void addAuditEventTruncateLargeData() { Map<String, Object> data = new HashMap<>(); StringBuilder largeData = new StringBuilder(); for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) { largeData.append("a"); } data.put("test-key", largeData); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal()); assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType()); assertThat(persistentAuditEvent.getData()).containsKey("test-key"); String actualData = persistentAuditEvent.getData().get("test-key"); assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH); assertThat(actualData).isSubstringOf(largeData); assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp().toInstant()); } @Test public void testAddEventWithWebAuthenticationDetails() { HttpSession session = new MockHttpSession(null, "test-session-id"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); request.setRemoteAddr("1.2.3.4"); WebAuthenticationDetails details = new WebAuthenticationDetails(request); Map<String, Object> data = new HashMap<>(); data.put("test-key", details); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); } @Test public void testAddEventWithNullData() { Map<String, Object> data = new HashMap<>(); data.put("test-key", null); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null"); } @Test public void addAuditEventWithAnonymousUser() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(0); } @Test public void addAuditEventWithAuthorizationFailureType() { Map<String, Object> data = new HashMap<>(); data.put("test-key", "test-value"); AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(0); } }
3b487054d2e7072849d2f735eda15829844cd92a
327be1427daad81689a5aff5a3569f5a48783f67
/src/main/java/org/edec/newOrder/service/orderCreator/SocialIncreasedNewReferenceOrderService.java
c7fc1ace655cc6e3f6ee2e55d22f229d8a8f18b8
[]
no_license
luninok/curriculum
7e1a0ccee1ba71f382559543fd62a13ea724490a
80e84ec2eb88490260d278e8890a979a8e8d32eb
refs/heads/master
2021-07-11T08:11:48.644816
2018-12-12T08:02:44
2018-12-12T08:02:44
147,468,888
0
0
null
2019-02-05T03:54:08
2018-09-05T06:14:49
Java
UTF-8
Java
false
false
1,568
java
package org.edec.newOrder.service.orderCreator; import org.edec.newOrder.model.addStudent.LinkOrderSectionEditModel; import org.edec.newOrder.model.createOrder.OrderCreateStudentModel; import org.edec.newOrder.model.editOrder.StudentModel; import org.edec.newOrder.model.editOrder.OrderEditModel; import org.edec.newOrder.model.addStudent.SearchStudentModel; import java.util.List; public class SocialIncreasedNewReferenceOrderService extends OrderService { @Override protected void generateParamModel () { // TODO } @Override protected void generateDocumentModel () { // TODO } @Override protected Long createOrderInDatabase (List<Object> orderParams, List<OrderCreateStudentModel> students) { return null; } @Override public boolean createAndAttachOrderDocuments (List<Object> documentParams, OrderEditModel order) { // TODO return true; } @Override public void removeStudentFromOrder (Long idLoss, OrderEditModel order) { } @Override public void setParamForStudent (Integer i, Object value, StudentModel studentModel, Long idOS) { } @Override public Object getParamForStudent (Integer i, StudentModel studentModel, Long idOS) { return null; } @Override public String getStringParamForStudent (Integer i, StudentModel studentModel, Long idOS) { return null; } public void addStudentToOrder (SearchStudentModel studentModel, OrderEditModel order, LinkOrderSectionEditModel orderSection) { } }
ee882b58ba4285f52a40b012e7d76533ac757666
bde4450604d811be74d0cbdd9abb29afae7f8728
/java_fx_test_component/src/application/FileChooserTest.java
53d051da008a7c242059649e88631d6ed55102ed
[]
no_license
ev15963/java_work
a5a04eb0ffe037fd00c652e23d04dc2ae26e3503
7696471abf5348dc97733ff5686cc729b0929ff4
refs/heads/master
2022-11-27T20:00:39.668937
2020-08-01T17:21:15
2020-08-01T17:21:15
258,440,061
0
0
null
null
null
null
UHC
Java
false
false
2,009
java
package application; import java.io.File; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; import javafx.stage.Stage; public class FileChooserTest extends Application{ public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { BorderPane root = new BorderPane(); Scene scene = new Scene(root, 400, 400); final ImageView view = new ImageView(); root.setCenter(view); final FileChooser chooser = new FileChooser(); //파일을 선택할 수 있는 //걸러내는 객체을 얻음 //한글 가능 FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Image", "*.jpg", "*.gif", "*.png"); chooser.getExtensionFilters().add(filter); MenuBar bar = new MenuBar(); root.setTop(bar); //상단에 Menubar 배치 //MenuBar의 위치할 menu 생성 Menu fileMenu = new Menu("_File"); //Menu("_File")에 해당하는 item 생성 MenuItem openItem = new MenuItem("_Open"); //MenuItem("_Open")클릭시, openItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //FileChooser 출력후, 선택한 파일의 경로 반환 File file = chooser.showOpenDialog(primaryStage); if (file != null) { //파일의 경로를 이용하여 ImageView에 출력 Image image = new Image(file.toURI().toString()); view.setImage(image); //image view에 set } } }); //setOnAction() END fileMenu.getItems().add(openItem); bar.getMenus().add(fileMenu); primaryStage.setTitle("FileChooser Test"); primaryStage.setScene(scene); primaryStage.show(); } }
82e92826c77dacae91aa456606b841ae7b95c54a
50c7dbf3e0192694ee9ff3c14b6481565b068399
/beerCalculator/src/beerCalculator/beerGui.java
46e7d94b41fdcbb89e1bd31f1fec20c63f66d0e1
[]
no_license
mwg6/beercalc
536e94db2dd4f5cdc0a74dba167fb6fea981c332
f1e6085745b9d69871ac088636d14118141f4185
refs/heads/master
2021-01-25T13:59:22.522520
2018-03-06T01:03:47
2018-03-06T01:03:47
123,639,172
0
0
null
2018-03-04T17:15:56
2018-03-02T22:51:40
Java
UTF-8
Java
false
false
3,426
java
package beerCalculator; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.Box; import javax.swing.JOptionPane; import javax.swing.JPanel; //our class beergui adds functionality to JPanel public class beerGui extends JPanel{ //first we need the table where all information will be displayed beerTable beerTable = new beerTable(); //now we need user interaction buttons and input areas beerButtonTop buttonPanelTop = new beerButtonTop(); beerPanelTop informationPanelTop = new beerPanelTop(); beerButton buttonPanelBottom = new beerButton(); beerPanel informationPanel = new beerPanel(); //aight constructor for the gui itself. Componenets needed are made above public beerGui() { //hey look, adding the top panel stuff to a panel on top! JPanel topPanel = new JPanel(); topPanel.add(informationPanelTop); topPanel.add(Box.createHorizontalStrut(10)); topPanel.add(buttonPanelTop); //see above but replace top with bottom JPanel bottomPanel = new JPanel(); bottomPanel.add(buttonPanelBottom); bottomPanel.add(Box.createHorizontalStrut(10)); bottomPanel.add(informationPanel); //making the panel purtty. Adding the components as described setLayout(new BorderLayout()); add(topPanel, BorderLayout.NORTH); add(beerTable, BorderLayout.CENTER); add(bottomPanel, BorderLayout.SOUTH); //make the buttons on bottom work. One day they'll be respectable members of society buttonPanelBottom.addInfoBtnAddActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try{ //attempt get what the user inputs when they hit add String name = informationPanel.Name(); String type = informationPanel.Type(); double quantity = informationPanel.Quantity(); String unit = informationPanel.Unit(); //attempt to pass that data to the table beerTable.addRow(name, type, quantity, unit); } //if a number confuses the user we correct them gently catch(NumberFormatException r){ JOptionPane.showMessageDialog(null, "Please input a valid number for Quantity"); } } }); //so now make the print button work buttonPanelBottom.addPrintBtnAddActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ //the below statement gives gallons to be made, total lbs of grain in the recipe, and a list of grain and hop names int gals = informationPanelTop.getQuantity(); double i = beerTable.sumColumn(2); String grains = beerTable.getGrainNames(); String hops = beerTable.getHopNames(); //and passes it to print with its own error handling buttonPanelBottom.print(gals, i, grains, hops); } }); //simple boy. destroys all user input buttonPanelTop.addClearBtnAddActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ beerTable.clearTable(); } }); }}
51011be8c447ca97a054c54d271f4eb8506985be
ec58bc8e5a5b5141c7334f8ac164b7b73ab1865e
/nepalidatepicker/src/main/java/app/nepali/nepalidatepicker/Model.java
b61ec73c3f3b2cb1b5cf7a9d902d336333cf26c2
[]
no_license
kapilmhr/NepaliDatePicker
24032b97a3c84c82fca7d70d9a4044f4ab0c8882
913ea0c41e67fc4703fe80fdd49789a28951af96
refs/heads/master
2022-12-14T21:56:19.313510
2020-09-14T05:09:44
2020-09-14T05:09:44
295,303,995
0
0
null
null
null
null
UTF-8
Java
false
false
1,368
java
package app.nepali.nepalidatepicker; import androidx.annotation.IntRange; import java.util.Calendar; import java.util.GregorianCalendar; public class Model { private int day; private int year; private int month; private int dayOfWeek; public int getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek(@IntRange(from = 1, to = 7) int dayOfWeek) { this.dayOfWeek = dayOfWeek; } public Model() { GregorianCalendar date = new GregorianCalendar(); day = date.get(GregorianCalendar.DAY_OF_MONTH); month = date.get(GregorianCalendar.MONTH) + 1; year = date.get(GregorianCalendar.YEAR); dayOfWeek = date.get(Calendar.DAY_OF_WEEK); } public Model(@IntRange(from=1970,to=2090) int year, @IntRange(from = 0, to = 12) int month, @IntRange(from = 1, to = 32) int day) { this.year = year; this.month = month; this.day = day; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } }
3d00e6fb836553ab6112691173329499bcacd395
df8e54ff5fbd5942280e3230123494a401c57730
/code/learning-way/src/main/java/com/vika/autumn/leetcode/editor/cn/P239SlidingWindowMaximum.java
105bf56bd0719994679f4ea2c1581e1bf2579907
[]
no_license
kabitonn/cs-note
255297a0a0634335eefba79882f7314f7b97308f
1235bb56a40bce7e2056f083ba8cda0cd08e39b4
refs/heads/master
2022-06-09T23:46:02.145680
2022-05-13T10:44:53
2022-05-13T10:44:53
224,864,415
0
1
null
2022-05-13T07:25:09
2019-11-29T13:58:19
Java
UTF-8
Java
false
false
4,445
java
//给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 // // // 返回滑动窗口中的最大值。 // // // // 进阶: // // 你能在线性时间复杂度内解决此题吗? // // // // 示例: // // 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 //输出: [3,3,5,5,6,7] //解释: // // 滑动窗口的位置 最大值 //--------------- ----- //[1 3 -1] -3 5 3 6 7 3 // 1 [3 -1 -3] 5 3 6 7 3 // 1 3 [-1 -3 5] 3 6 7 5 // 1 3 -1 [-3 5 3] 6 7 5 // 1 3 -1 -3 [5 3 6] 7 6 // 1 3 -1 -3 5 [3 6 7] 7 // // // // 提示: // // // 1 <= nums.length <= 10^5 // -10^4 <= nums[i] <= 10^4 // 1 <= k <= nums.length // // Related Topics 堆 Sliding Window // 👍 536 👎 0 //Java:滑动窗口最大值 package com.vika.autumn.leetcode.editor.cn; import org.junit.Test; import java.util.Arrays; import java.util.LinkedList; import java.util.PriorityQueue; public class P239SlidingWindowMaximum { public static void main(String[] args) { Solution solution = new P239SlidingWindowMaximum().new Solution(); // TO TEST } //leetcode submit region begin(Prohibit modification and deletion) class Solution { /** * 滑动窗口最大值pop出窗口时重新计算 * * @param nums * @param k * @return */ public int[] maxSlidingWindow1(int[] nums, int k) { if (nums == null || nums.length == 0) { return new int[]{}; } int n = nums.length; int[] slide = new int[n - k + 1]; int max = Integer.MIN_VALUE; for (int i = 0; i < k - 1; i++) { max = Math.max(max, nums[i]); } for (int left = 0, right = k - 1; right < n; left++, right++) { max = Math.max(max, nums[right]); slide[left] = max; if (nums[left] == max) { max = Integer.MIN_VALUE; for (int i = left + 1; i <= right; i++) { max = Math.max(max, nums[i]); } } } return slide; } /** * 最大堆维护窗口内值 超时 * * @param nums * @param k * @return */ public int[] maxSlidingWindow2(int[] nums, int k) { if (nums == null || nums.length == 0) { return new int[]{}; } PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, (o1, o2) -> o2 - o1); int n = nums.length; int[] slide = new int[n - k + 1]; for (int r = 0; r < n; r++) { maxHeap.offer(nums[r]); if (maxHeap.size() == k) { slide[r - k + 1] = maxHeap.peek(); maxHeap.remove(nums[r - k + 1]); } } return slide; } public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0) { return new int[]{}; } int n = nums.length; int[] slide = new int[n - k + 1]; LinkedList<Integer> queue = new LinkedList<>(); for (int i = 0; i < k - 1; i++) { while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) { queue.pollLast(); } queue.offer(i); } for (int l = 0, r = k - 1; r < n; l++, r++) { while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[r]) { queue.pollLast(); } queue.offer(r); slide[l] = nums[queue.peek()]; if (r - queue.peek() >= k - 1) { queue.poll(); } } return slide; } } //leetcode submit region end(Prohibit modification and deletion) @Test public void test() { Solution solution = new Solution(); int[] nums = {1, 3, 1, 2, 0, 5}; int[] slide = solution.maxSlidingWindow(nums, 3); System.out.println(Arrays.toString(slide)); } }
afb0fd2f819860f5901c925726df48c6937cd554
1b2d020d9323eba28cc7dd9d18a74d41632a2b5a
/src/com/facility/service/InspectionService.java
f33b868f9fbc4981f87cf89aa5f8cd731dbc8ec8
[]
no_license
mgiovenco/comp473_project1
fb173bdc7a8e52038ecce7031acd5a4d37762ff4
640608efb30648faffa39bbe9f145951a3d8d085
refs/heads/master
2021-01-10T06:28:14.347120
2016-02-23T04:07:00
2016-02-23T04:07:00
51,266,178
1
0
null
null
null
null
UTF-8
Java
false
false
588
java
package com.facility.service; import com.facility.dao.InspectionDao; import com.facility.model.Inspection; import java.util.List; /** * Service for handling facility inspection inquiries */ public class InspectionService { private InspectionDao inspectionDao; public InspectionService() { this.inspectionDao = new InspectionDao(); } /** * Return a list of inspections for given facility * * @return */ public List<Inspection> listInspections(int facilityId) { return inspectionDao.selectAllInspections(facilityId); } }
c22b5026f9470c87996a5f2eca2ae7cc0013ed8a
30a8aea53554c0c8cf14b109cf6d5256afc41589
/LYWUtil/src/com/lyw/util/TestCount.java
e0eb3c882d9a7a7e859bd4c0aa6633a75da655ff
[]
no_license
281451241/YuWenJavaUtils
f96d6f1a76c5957fe03dc75877b85e2da0e1d72e
403fc478d49446ac5b3da4829b2d5404379291be
refs/heads/master
2021-01-01T19:16:00.476178
2013-11-28T09:54:33
2013-11-28T09:54:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
419
java
package com.lyw.util; public class TestCount { private void sub() { for(int i = 0; i < 10; i++) { count--; } System.out.println(count); } private void add() { for(int i = 0; i < 10; i++) { count++; } System.out.println(count); } public static void main(String[] args) { TestCount tc = new TestCount(); tc.add(); tc.sub(); } private int count = 0; }
ff5a65af9aaf24c9a3547adf51be73a3a5d1afd7
83f4e19abd0201834f4d130d4a98902106f18974
/src/cn/java/servlet/SubMenuListServlet.java
9939fe789db49cda12a3e2742846769287fc34f2
[]
no_license
holyedding/easybuy
3a280739010802104c0d2787c26d4d9318373e6a
bd0b298bbf3c7c38052b9e3ce44e5988558619e6
refs/heads/master
2021-07-02T20:48:47.162005
2017-09-23T04:24:14
2017-09-23T04:31:25
104,443,189
0
0
null
null
null
null
UTF-8
Java
false
false
2,245
java
/* 1: */ package cn.java.servlet; /* 2: */ /* 3: */ import cn.java.service.GoodsListService; /* 4: */ import cn.java.service.impl.GoodsListServiceImpl; /* 5: */ import java.io.IOException; /* 6: */ import java.util.List; /* 7: */ import java.util.Map; /* 8: */ import javax.servlet.ServletException; /* 9: */ import javax.servlet.ServletOutputStream; /* 10: */ import javax.servlet.annotation.WebServlet; /* 11: */ import javax.servlet.http.HttpServlet; /* 12: */ import javax.servlet.http.HttpServletRequest; /* 13: */ import javax.servlet.http.HttpServletResponse; /* 14: */ import org.json.JSONObject; /* 15: */ /* 16: */ @WebServlet({"/SubMenuListServlet"}) /* 17: */ public class SubMenuListServlet /* 18: */ extends HttpServlet /* 19: */ { /* 20:31 */ private GoodsListService gls = new GoodsListServiceImpl(); /* 21: */ /* 22: */ protected void doGet(HttpServletRequest request, HttpServletResponse response) /* 23: */ throws ServletException, IOException /* 24: */ { /* 25: */ try /* 26: */ { /* 27:40 */ String menuId = request.getParameter("MenuId"); /* 28:41 */ long id = Long.parseLong(menuId); /* 29: */ /* 30: */ /* 31: */ /* 32:45 */ List<Map<String, Object>> menulist = this.gls.goodList(id, "1"); /* 33: */ /* 34: */ /* 35: */ /* 36: */ /* 37:50 */ JSONObject json = new JSONObject(); /* 38:51 */ json.put("menulist", menulist); /* 39:52 */ response.getOutputStream().write(json.toString().getBytes("utf-8")); /* 40: */ } /* 41: */ catch (Exception e) /* 42: */ { /* 43:55 */ e.printStackTrace(); /* 44: */ } /* 45: */ } /* 46: */ /* 47: */ protected void doPost(HttpServletRequest request, HttpServletResponse response) /* 48: */ throws ServletException, IOException /* 49: */ { /* 50:66 */ doGet(request, response); /* 51: */ } /* 52: */ } /* Location: C:\Users\Administrator\Workspaces\MyEclipse Professional 2014\dt41_easybuy\ImportedClasses\ * Qualified Name: cn.java.servlet.SubMenuListServlet * JD-Core Version: 0.7.0.1 */
33ca036e2f2d8de39e7ec6f1d9eeaa0df8b8bbcb
8b73d92e633f5ffee2664fe5567bbfa7890c66d3
/mall-coupon/src/main/java/com/yukino/coupon/controller/HomeSubjectController.java
ea659291a56313adb8ce4598f7e91a4a1756026e
[]
no_license
yukinocyann/guli_mall
d0541d774973d7004ba7a35f1a98eccb5862bc01
847343d79adc0e5cea2fa7f8bf7874699fcf476e
refs/heads/master
2023-09-01T19:38:44.828460
2021-10-07T08:47:48
2021-10-07T08:47:48
393,608,647
0
0
null
null
null
null
UTF-8
Java
false
false
2,334
java
package com.yukino.coupon.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.yukino.coupon.entity.HomeSubjectEntity; import com.yukino.coupon.service.HomeSubjectService; import com.yukino.common.utils.PageUtils; import com.yukino.common.utils.R; /** * 首页专题表【jd首页下面很多专题,每个专题链接新的页面,展示专题商品信息】 * * @author yukino * @email [email protected] * @date 2019-10-08 09:36:40 */ @RestController @RequestMapping("coupon/homesubject") public class HomeSubjectController { @Autowired private HomeSubjectService homeSubjectService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("coupon:homesubject:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = homeSubjectService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("coupon:homesubject:info") public R info(@PathVariable("id") Long id){ HomeSubjectEntity homeSubject = homeSubjectService.getById(id); return R.ok().put("homeSubject", homeSubject); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("coupon:homesubject:save") public R save(@RequestBody HomeSubjectEntity homeSubject){ homeSubjectService.save(homeSubject); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("coupon:homesubject:update") public R update(@RequestBody HomeSubjectEntity homeSubject){ homeSubjectService.updateById(homeSubject); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("coupon:homesubject:delete") public R delete(@RequestBody Long[] ids){ homeSubjectService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
8a6b15e5023fc385cf059e1f11dae72d6c9038a1
f57c9d57f967289ebc50d9709d8fb6564b1a7898
/src/main/java/com/ylz/packcommon/common/comEnum/ReferralType.java
ff3f22f6d27de16ca568068d21f314d238ed1afa
[]
no_license
zzr156/familydoctor
dc78838040fcc838f252f498e101900b9ab1eda6
a0d24b24f27b209c748ce1767109fc46b076d785
refs/heads/master
2022-12-23T18:59:12.892124
2019-12-14T02:46:48
2019-12-14T02:46:48
227,955,558
2
1
null
2022-12-16T02:48:39
2019-12-14T02:37:27
Java
UTF-8
Java
false
false
381
java
package com.ylz.packcommon.common.comEnum; /** * 转诊类型 * Created by zzl on 2017/12/11. */ public enum ReferralType { /** * 转出 */ ZC("1"), /** * 转入 */ ZR("2"); private String value; private ReferralType(String value){ this.value = value; } public String getValue(){ return this.value; } }
c193f83649879df0780df99909cd974cfbe0045b
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/stanfordnlp--CoreNLP/69b760924bdb71f22a9673d3828812d516ec5ff0/after/PatternToken.java
7c3e8536be6d94c4a014a755ed7159d86528198e
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
3,872
java
package edu.stanford.nlp.patterns.surface; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import edu.stanford.nlp.util.StringUtils; import edu.stanford.nlp.util.logging.Redwood; /** * Class to represent a target phrase. Note that you can give additional negative constraints * in getTokenStr(List) but those are not used by toString, hashCode and equals functions * * Author: Sonal Gupta ([email protected]) */ public class PatternToken implements Serializable { private static final long serialVersionUID = 1L; String tag; boolean useTag; int numWordsCompound; boolean useNER = false; String nerTag = null; boolean useTargetParserParentRestriction = false; String grandparentParseTag; public PatternToken(String tag, boolean useTag, boolean getCompoundPhrases, int numWordsCompound, String nerTag, boolean useNER, boolean useTargetParserParentRestriction, String grandparentParseTag) { this.tag = tag; this.useTag = useTag; this.numWordsCompound = numWordsCompound; if (!getCompoundPhrases) numWordsCompound = 1; this.nerTag = nerTag; this.useNER = useNER; this.useTargetParserParentRestriction = useTargetParserParentRestriction; if(useTargetParserParentRestriction){ if(grandparentParseTag == null){ Redwood.log(ConstantsAndVariables.extremedebug,"Grand parent parse tag null "); this.grandparentParseTag = ""; } else this.grandparentParseTag = grandparentParseTag; } } // static public PatternToken parse(String str) { // String[] t = str.split("#"); // String tag = t[0]; // boolean usetag = Boolean.parseBoolean(t[1]); // int num = Integer.parseInt(t[2]); // boolean useNER = false; // String ner = ""; // if(t.length > 3){ // useNER = true; // ner = t[4]; // } // // return new PatternToken(tag, usetag, true, num, ner, useNER); // } public String toStringToWrite() { String s = "X"; if (useTag) s += ":" + tag; if (useNER) s += ":" + nerTag; if (useTargetParserParentRestriction) s += ":" + grandparentParseTag; // if(notAllowedClasses !=null && notAllowedClasses.size() > 0){ // s+= ":!("; // s+= StringUtils.join(notAllowedClasses,"|")+")"; // } if (numWordsCompound > 1) s += "{" + numWordsCompound + "}"; return s; } String getTokenStr(List<String> notAllowedClasses) { String str = " (?$term "; List<String> restrictions = new ArrayList<String>(); if (useTag) { restrictions.add("{tag:/" + tag + ".*/}"); } if (useNER) { restrictions.add("{ner:" + nerTag + "}"); } if (useTargetParserParentRestriction) { restrictions.add("{grandparentparsetag:" + grandparentParseTag + "}"); } if (notAllowedClasses != null && notAllowedClasses.size() > 0) { for (String na : notAllowedClasses) restrictions.add("!{" + na + "}"); } str += "[" + StringUtils.join(restrictions, " & ") + "]{1," + numWordsCompound + "}"; str += ")"; str = StringUtils.toAscii(str); return str; } @Override public boolean equals(Object b) { if (!(b instanceof PatternToken)) return false; PatternToken t = (PatternToken) b; if(this.useNER != t.useNER || this.useTag != t.useTag || this.useTargetParserParentRestriction != t.useTargetParserParentRestriction || this.numWordsCompound != t.numWordsCompound) return false; if (useTag && ! this.tag.equals(t.tag)) { return false; } if (useNER && ! this.nerTag.equals(t.nerTag)){ return false; } if (useTargetParserParentRestriction && ! this.grandparentParseTag.equals(t.grandparentParseTag)) return false; return true; } @Override public int hashCode() { return getTokenStr(null).hashCode(); } }
a8c2a98584388ee6aa5ed20257d0668357a61b4a
271ccca678554b7703e460546be641db850c1416
/mapposition/src/main/java/com/lwf/base/mvp/test/ITestContract.java
f553b45da05983b1626ddca5fcf3034f2b8c524d
[]
no_license
LiWenFei/MyApp
03b457e9faf706bbf73dfb1a912f4962478693a3
2fc4919f550df66136a4ab8376f1e3d00808a12f
refs/heads/master
2020-04-18T22:38:05.726846
2016-10-12T07:14:37
2016-10-12T07:14:37
66,257,486
0
1
null
null
null
null
UTF-8
Java
false
false
521
java
package com.lwf.base.mvp.test; import com.lwf.base.mvp.IModel; import com.lwf.base.mvp.IPresenter; import com.lwf.base.mvp.IView; /** * Created by liwenfei on 2016/10/11. */ public interface ITestContract { interface ITestView extends IView { void showLoginSuccess(); } interface ITestModel extends IModel { void Login(); } interface ITestPresenter extends IPresenter<ITestView> { void Login(); } interface ResultListener { void onsuccess(); } }
aaf09930bdf2ae64bcb60cf5dc0ff102eee70c24
2c40544be8739e5f0d63adf231c1070d97f25aaf
/SpringProjects/WebContent/ntsp67/IOCProj6-ConstructorInjection-ParameterResolvation/src/com/nt/beans/StudentDetails.java
8f54f10b6116091484e4189aa078ad4c45a687ea
[]
no_license
gurunatha/samples
7ad293750bc351b722dd079f3b8a8b08a4c7d2d4
379cc85d521923bf579fc130e35883f1c1e8b947
refs/heads/master
2021-08-23T01:52:33.976429
2017-12-02T08:37:05
2017-12-02T08:37:05
112,822,525
0
0
null
null
null
null
UTF-8
Java
false
false
562
java
package com.nt.beans; import java.beans.ConstructorProperties; public class StudentDetails { private int sno; private String sname; private float avg; //@ConstructorProperties(value={"sno","stname","avg"}) only in spring 3.x public StudentDetails(int sno, String stname, float avg) { System.out.println("StudentDetails:3-param cosntructor"); this.sno = sno; this.sname = stname; this.avg = avg; } public String toString() { return "StudentDetails [sno=" + sno + ", sname=" + sname + ", avg=" + avg + "]"; } }
b98b3fbac1896bc9f79d277ad27d0630a4010d43
d6518804a3ba871b095f11699816c412efd4ed55
/R719A.java
d5762ade1fc9620352b811035660c2ccedc64f04
[]
no_license
Setako/Codeforce
2205f9679cc41f269c849085dad28cb64ac97579
3fe1d2234a9692a978cfa621528493dce61ad133
refs/heads/master
2021-01-10T23:20:21.755580
2020-10-09T04:01:45
2020-10-09T04:01:45
70,597,735
0
0
null
null
null
null
UTF-8
Java
false
false
798
java
import java.util.Scanner; public class R719A { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); int[] arr = new int[n]; for(int i = 0;i<n;i++){ arr[i] = in.nextInt(); } if(arr[n-1]==15) { System.out.println("DOWN"); return; } if(arr[n-1]==0) { System.out.println("UP"); return; } if(n <=1) { System.out.println(-1); return; } int offset = arr[n-1]-arr[n-2]; if(offset>0) { System.out.println("UP"); return; } if(offset<0){ System.out.println("DOWN"); return; } System.out.println("-1"); } }
fc5ed67131b2ab0cb2f6729a8937bc35201ec7d5
128fac185e45bdb6f60270bec449f44a4ca4ddf6
/spring-cloud-eureka/src/main/java/com/tuandai/architecture/logs/MyLogEndpoint.java
4da22115c9c863fb56b3f9b06459648d7d68073d
[]
no_license
jurson86/springcloud-tcc
9a7a896d2a5bf0a62d17f394c675faa1815339ad
b830694a6f250fb60231f9f9ba5735553794d05c
refs/heads/master
2021-09-06T04:40:12.836497
2018-01-02T09:42:07
2018-01-02T09:42:07
113,958,557
0
1
null
null
null
null
UTF-8
Java
false
false
773
java
package com.tuandai.architecture.logs; import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; public class MyLogEndpoint extends AbstractEndpoint<Boolean> { AtomicBoolean atomicBoolean = new AtomicBoolean(); // mgrlogging 为该 endpoint 的请求子路径: http://localhost:8080/mgrlogging public MyLogEndpoint() { super("mgrlogging", true, true); } @Override public Boolean invoke() { // 这里我的本意是 log 开关,一个布尔值。 // 每次请求 http://localhost:8080/mgrlogging 都会调用该 invoke 方法 // 通常情况下返回该 endpoint 的监控信息 return atomicBoolean.getAndSet(!atomicBoolean.get()); } }
67ef8853a711e2edd6da46dacb12d0ae094e73a1
a7da271e01708ad4fd15d68fb0313ebbcc844083
/Prm_ExportResources_mxJPO.java
56226fbb3d1caf68f7ec0b9b049f9a19b0974a48
[]
no_license
hellozjf/JPO
73c2008a476206158f88987a713db6573b28eaf9
630920f4f026db93575166276ba59ad9d72493eb
refs/heads/master
2021-06-25T21:16:59.633721
2017-09-12T10:24:31
2017-09-12T10:24:31
100,002,796
2
1
null
null
null
null
UTF-8
Java
false
false
18,101
java
import matrix.db.Context; import com.dassault_systemes.EKLEngine.completion.CompletionJPOEvaluator; /** * ${CLASSNAME} */ public final class Prm_ExportResources_mxJPO extends CompletionJPOEvaluator { /** * Attributes */ private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_0__PLMResourceSetRep_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PLMResourceSetRep"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_1__prm_navigate_ref_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("prm_navigate_ref"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_2__prm_navigate_repref_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("prm_navigate_repref"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_3__prm_navigate_cbp_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("prm_navigate_cbp"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_4__ENOCLG_LIBRARY_div_EN = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("ENOCLG_LIBRARY/ENOCLG_LibraryReference"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_5__Clg_ExportCatalog_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("Clg_ExportCatalog"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_6__ENOCLG_CLASS_div_ENOC = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("ENOCLG_CLASS/ENOCLG_ClassReference"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_7__Clg_ExportChapter_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("Clg_ExportChapter"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_8__PLMKnowledgeTemplate_div_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PLMKnowledgeTemplate/PLMTemplateRepReference"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_9__Pkt_ExportTemplate_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("Pkt_ExportTemplate"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_10__PRODUCTCFG_div_VPMRe = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PRODUCTCFG/VPMReference"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_11__PRODUCTCFG_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PRODUCTCFG"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_12__ProductCfg_AddChildr = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("ProductCfg_AddChildrenProduct"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_13__PRODUCTCFG_div_VPMRe = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PRODUCTCFG/VPMRepReference"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_14__VPMEditor_GetAllRepr = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("VPMEditor_GetAllRepresentations"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_15__PLMKnowHowRuleSet_div_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PLMKnowHowRuleSet/PLMRuleSet"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_16__Kwe_ExportRuleSet_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("Kwe_ExportRuleSet"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_17__PLMKbaAppliComponent = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PLMKbaAppliComponent/PLMKbaAppliComponent"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_18__Kba_ExportAppComp_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("Kba_ExportAppComp"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_19__RFLVPMLogical_div_RF = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("RFLVPMLogical/RFLVPMLogicalReference"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_20__Logical_ExportRefere = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("Logical_ExportReference_Design"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_21__PLMEnsSpecSpecificat = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PLMEnsSpecSpecification/EnsSpecification"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_22__ESE_SpecExport_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("ESE_SpecExport"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_23__PLMEnsSpecTechnoTabl = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PLMEnsSpecTechnoTable/EnsTechnologicalTable"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_24__ESE_TechnoTableExpor = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("ESE_TechnoTableExport"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_25__PLMKnowHowLibrary_div_ = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("PLMKnowHowLibrary/PLMEKLLibrary"); private final static com.dassault_systemes.EKLEngine.common.lib.implementation.StringType _STRING_26__Kwe_ExportEKLLibrary = new com.dassault_systemes.EKLEngine.common.lib.implementation.StringType("Kwe_ExportEKLLibrary"); /** * evaluate * @param iContext * @param iPLMIDSet * @param oPLMIDSet */ public final void evaluate(matrix.db.Context iContext, com.dassault_systemes.EKLEngine.common.lib.PLMIDSet iPLMIDSet, com.dassault_systemes.EKLEngine.common.lib.PLMIDSet oPLMIDSet) throws Exception { com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet RsARMpointedCoreRef = new com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet(); com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet RsARMpointedCoreRepRef = new com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet(); com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet RsARMpointedBO = new com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet(); com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet RsProductStructure = new com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsARMpointedCoreRef = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsARMpointedCoreRepRef = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsARMpointedBO = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsCatalogs = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsCatalogsContents = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsChapters = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsChaptersContents = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsTemplates = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsTemplatesStructure = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsProductStructureInputs1 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsProductStructureInputs2 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsProductStructure1 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsProductStructure2 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsRulesets = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsRulesetsContents = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsKComps = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsKCompStructure = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsLogicalPKT1 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsLogicalPKT2 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsEnsSpecs1 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsEnsSpecs2 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsEnsTechTables1 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsEnsTechTables2 = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsEKLLibs = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); com.dassault_systemes.EKLEngine.common.lib.PLMIDSet IdsEKLLibsContents = new com.dassault_systemes.EKLEngine.common.lib.PLMIDSet(); RsARMpointedCoreRef.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMFunction( iContext , _STRING_0__PLMResourceSetRep_, _STRING_1__prm_navigate_ref_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { iPLMIDSet } ) ); IdsARMpointedCoreRef.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet.Ids( RsARMpointedCoreRef ) ); RsARMpointedCoreRepRef.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMFunction( iContext , _STRING_0__PLMResourceSetRep_, _STRING_2__prm_navigate_repref_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { iPLMIDSet } ) ); IdsARMpointedCoreRepRef.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet.Ids( RsARMpointedCoreRepRef ) ); RsARMpointedBO.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMFunction( iContext , _STRING_0__PLMResourceSetRep_, _STRING_3__prm_navigate_cbp_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { iPLMIDSet } ) ); IdsARMpointedBO.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet.Ids( RsARMpointedBO ) ); IdsCatalogs.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_4__ENOCLG_LIBRARY_div_EN ) ); IdsCatalogsContents.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_5__Clg_ExportCatalog_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsCatalogs } ) ); IdsChapters.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_6__ENOCLG_CLASS_div_ENOC ) ); IdsChaptersContents.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_7__Clg_ExportChapter_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsChapters } ) ); IdsTemplates.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRepRef, _STRING_8__PLMKnowledgeTemplate_div_ ) ); IdsTemplatesStructure.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_9__Pkt_ExportTemplate_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsTemplates } ) ); IdsProductStructureInputs1.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_10__PRODUCTCFG_div_VPMRe ) ); RsProductStructure.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMFunction( iContext , _STRING_11__PRODUCTCFG_, _STRING_12__ProductCfg_AddChildr, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsProductStructureInputs1 } ) ); IdsProductStructure1.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMRouteSet.Ids( RsProductStructure ) ); IdsProductStructureInputs2.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsProductStructure1, _STRING_10__PRODUCTCFG_div_VPMRe ), com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsProductStructure1, _STRING_13__PRODUCTCFG_div_VPMRe ) ), com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRepRef, _STRING_13__PRODUCTCFG_div_VPMRe ) ) ); IdsProductStructure2.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_14__VPMEditor_GetAllRepr, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsProductStructureInputs2 } ) ); IdsRulesets.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_15__PLMKnowHowRuleSet_div_ ) ); IdsRulesetsContents.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_16__Kwe_ExportRuleSet_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsRulesets } ) ); IdsKComps.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRepRef, _STRING_17__PLMKbaAppliComponent ) ); IdsKCompStructure.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_18__Kba_ExportAppComp_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsKComps } ) ); IdsLogicalPKT1.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_19__RFLVPMLogical_div_RF ) ); IdsLogicalPKT2.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_20__Logical_ExportRefere, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsLogicalPKT1 } ) ); IdsEnsSpecs1.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_21__PLMEnsSpecSpecificat ) ); IdsEnsSpecs2.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_22__ESE_SpecExport_, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsEnsSpecs1 } ) ); IdsEnsTechTables1.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_23__PLMEnsSpecTechnoTabl ) ); IdsEnsTechTables2.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_24__ESE_TechnoTableExpor, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsEnsTechTables1 } ) ); IdsEKLLibs.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.Restrict( iContext , IdsARMpointedCoreRef, _STRING_25__PLMKnowHowLibrary_div_ ) ); IdsEKLLibsContents.setValue( com.dassault_systemes.EKLEngine.completion.lib.Completion.ExecutePLMProcedure( iContext , _STRING_26__Kwe_ExportEKLLibrary, new com.dassault_systemes.EKLEngine.common.lib.implementation.ObjectType[] { IdsEKLLibs } ) ); oPLMIDSet.setValue( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( com.dassault_systemes.EKLEngine.common.lib.PLMIDSet.plus( iPLMIDSet, IdsARMpointedCoreRef ), IdsARMpointedCoreRepRef ), IdsARMpointedBO ), IdsCatalogsContents ), IdsChaptersContents ), IdsTemplatesStructure ), IdsProductStructure1 ), IdsProductStructure2 ), IdsRulesetsContents ), IdsKCompStructure ), IdsLogicalPKT2 ), IdsEnsSpecs2 ), IdsEnsTechTables2 ), IdsEKLLibsContents ) ); } }
3b7001e30e7b78eb6e2e88d718fca7543398cae6
3b99672285cdd97878910bed7a2e188dd29ff065
/Math/PerfectNumber.java
241c3f1a596534126f4dc426b3f391ee985f08ec
[]
no_license
mohdshahbazmirza/DSA
ccd47e58d3dd53832dfc0d756ba30e257ea8a2c3
64e4a43e45d47cfa2837ccc8f8e7b365f262d778
refs/heads/master
2023-08-10T18:55:18.643181
2021-09-27T18:24:31
2021-09-27T18:24:31
378,571,982
1
0
null
null
null
null
UTF-8
Java
false
false
463
java
class Solution { public boolean isPerfectSquare(int num) { long start = 0; long end = num; while(start<=end){ long mid = start + (end-start)/2; if(mid*mid == num){ return true; } else if(mid*mid > num){ end = mid-1; } else{ start = mid+1; } } return false; } }
4bcfaabbb27f8b02968b6ea7637117e7c887f91b
5f3fc6841b4e7ea1d0fd410eab769a55c58e42ec
/src/main/java/com/djhoyos/citasweb/dominio/modelo/Identificacion.java
4ad373edbf631763243af083decec42512a3e7cc
[]
no_license
ddhoyos0/ADN-Ceiba
af0ee65e1064a00dd8beb9cfe6c6a3d86cae88fc
6f06b2936cb8f06f4e844c4248dd12163b7888aa
refs/heads/master
2021-02-25T22:00:11.254639
2020-04-13T13:51:35
2020-04-13T13:51:35
244,940,266
0
0
null
null
null
null
UTF-8
Java
false
false
657
java
package com.djhoyos.citasweb.dominio.modelo; import com.djhoyos.citasweb.dominio.utilidades.Validaciones; public class Identificacion { private long id; private String tipo; public Identificacion() { } public Identificacion(long id, String tipo) { Validaciones.validarNoVacio(tipo,"El tipo de documento no puede ser vacio"); this.id = id; this.tipo = tipo; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } }
c6125dc19efc6dc3326046cf1814dc542535dd87
85fce37186a2a44e8430f5480659e7ff33488626
/nio/src/main/java/src/luban/testdome/TestThreadGroup.java
4c55131b2bbe8703276cf5c16326903a2f4d5a97
[]
no_license
chc0618/jdk8
c03f7c8b88ed4392c2686449a420785c58535354
a9b9f756aee3b4e25be95aee805dcbf6ac880c65
refs/heads/master
2022-05-04T02:23:54.682202
2020-11-19T07:48:15
2020-11-19T07:48:15
249,917,372
0
0
null
2022-03-31T19:34:30
2020-03-25T07:49:31
Java
UTF-8
Java
false
false
15,307
java
package src.luban.testdome; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; import java.util.Arrays; /** * * {@link java.lang.ThreadGroup}示例 * * <pre> * 1.线程组表示一个线程的结合.此外线程组也可以包含其他线程组.线程组构成一棵树,在树中,除了初始线程组外,每个线程组都有一个父线程组 * 2.每个线程产生时,都会被归入某个线程组(Java中每个线程都是属于某个线程组),视线程是在那个线程组中产生而定.如果没有指定,则归入产生该子线程的线程的线程组中.(如在main中初始化一个线程,未指定线程组,则线程所属线程组为main) * 3.线程一旦归入某个组就无法更换组 * 4.main线程组的parent是system线程组,而system线程组的parent为null.(参考ThreadGroup的私有构造方法).也就是说初始线程组为system.以system/main衍生出一颗树 * 5.其activeCount/activeCount/enumerate方法均为不精确的统计,建议仅用于信息目的 * 6.可通过enumerate获得活动线程的引用并对其进行操作 * 7.允许线程访问有关自己的线程组的信息{@link Thread#getThreadGroup()},但是不允许它访问有关其线程组的父线程组或其他任何线程组的信息 * 8.线程组的某些方法,将对线程组机器所有子组的所有线程执行,如{@link ThreadGroup#interrupt()} * 7.public class ThreadGroup implements Thread.UncaughtExceptionHandler,即其实现了UncaughtExceptionHandler方法.即 * ->当Thread因未捕获的异常而突然中止时,调用处理程序的接口.当某一线程因捕获的异常而即将中止时,JVM将使用UncaughtExceptionHandler查询该线程以获得其 * UncaughtExceptionHandler的线程并调用处理程序的uncaughtException方法,将线程和异常作为参数传递.如果某一线程为明确设置其UncaughtExceptionHandler, * 则将它的ThreadGroup对象作为UncaughtExceptionHandler.如果ThreadGroup对象对处理异常没有特殊要求,可以将调用转发给 * {@link Thread#getDefaultUncaughtExceptionHandler()} * </pre> * * <pre> * 1."线程是独立执行的代码片断,线程的问题应该由线程自己来解决,而不要委托到外部".基于这样的设计理念,在Java中,线程方法的异常 * (无论是checked还是unchecked exception),都应该在线程代码边界之内(run方法内)进行try catch并处理掉 * .换句话说,我们不能捕获从线程中逃逸的异常 * * 2.参考{@link Thread#dispatchUncaughtException},该方法是一个私有方法,在异常逃逸时调用.判断线程自身是否设置了uncaughtExceptionHandler. * 如果没有则直接返回group,即自己的所在的线程组,而线程组实现了UncaughtExceptionHandler接口.{@link Thread#getUncaughtExceptionHandler()} * </pre> * * @author landon * */ public class TestThreadGroup { // private static final Logger LOGGER = LoggerFactory // .getLogger(TestThreadGroup.class); // // public static void main(String[] args) { // // main.thread.name:main,main.threadGroup.name:main // // 即当前线程为main,其所属线程组 // // Thread#public final ThreadGroup getThreadGroup() // // 返回该线程所属的线程组.如果该线程已经停止运行则返回null // LOGGER.debug("main.thread.name:{},main.threadGroup.name:{}", Thread // .currentThread().getName(), Thread.currentThread() // .getThreadGroup().getName()); // // Thread thread1 = new Thread("Thread-1"); // // 从输出可以看到 // // 1.thread1为指定线程组,则其输出的线程组为main,即产生thread1的main线程所属的线程组main // // 2.thread1并未启动.其所属线程组就已经指定了,即在线程初始化的时候就已经拥有了 // // 从源码看: // // Thread#private void init(ThreadGroup g, Runnable target,String // // name,long stackSize) // // 1.Thread parent = currentThread(),获取调用线程,即产生thread的线程 // // 2.判断SecurityManager是否为空,如果不为空,则用SecurityManager#getThreadGroup(). // // 3.如果SecurityManager#getThreadGroup()为空或者不存在SecurityManager,则线程组赋值为parent.getThreadGroup(),即调用线程所属的线程组 // // 另外从Thread的初始化方法中可以看到,线程是否是守护线程以及线程的优先级均是由parent指定 // LOGGER.debug("thread1.name:{},thread1.threadGroup.name:{}", // thread1.getName(), thread1.getThreadGroup().getName()); // // 从是否是守护线程和线程的优先级的输出来看,threa1和其parent线程main的是一样的 // LOGGER.debug("threa1.name:{},threa1.isDaemon:{},threa1.priority:{}", // thread1.getName(), thread1.isDaemon(), thread1.getPriority()); // Thread curThread = Thread.currentThread(); // LOGGER.debug( // "curThread.name:{},curThread.isDaemon:{},curThread.priority:{}", // curThread.getName(), curThread.isDaemon(), // curThread.getPriority()); // // // 该线程未执行名字,从输出看:其名字是Thread-0 // // 从Thread的初始化方法可以看到,当名字为null的时候(即匿名线程),会指定一个名字"Thread-" + // // nextThreadNum() // // 而nextThreadNum是一个静态同步方法,对threadInitNumber这个静态计数器执行++ // Thread thread2 = new Thread(); // LOGGER.debug("threa2.name:{}", thread2.getName()); // // // public ThreadGroup(String name) 构造一个新的线程组,该新线程组的父线程组是目前调用线程的线程组 // // 从源码上看: // // 1.this(Thread.currentThread().getThreadGroup(), // // name),即将当前调用线程所属的线程组作为其父parent线程组传入 // // 2.将parent.maxPriority/daemon赋值传入 // // 3.parent.add(this),将将该线程组加入到父线程组 // // 4.另外ThreadGroup有一个私有的空参数的构造方法,其指定线程组名字为system,priority为最大优先级,parent为null,即没有父线程组.从该代码的注释来看, // // ->该私有构造方法通常用来创建一个系统线程组,C代码调用 // ThreadGroup group1 = new ThreadGroup("ThreadGroup-1"); // // 输出:group1.parent.name:main,即group1的父线程组为main // // ThreadGroup#public final ThreadGroup getParent() 返回线程组的父线程组 // LOGGER.debug("group1.parent.name:{}", group1.getParent().getName()); // ThreadGroup mainGroup = Thread.currentThread().getThreadGroup(); // // 输出:mainGroup.parentOf(group1):true,group1.parentOf(group1),true // // ThreadGroup#public final boolean parentOf(ThreadGroup g) // // 判断该线程组是否为线程组参数或者是其祖先线程组 // // 从输出看,mainGroup是group1的parent,而传入原组,方法也返回true // LOGGER.debug( // "mainGroup.parentOf(group1):{},group1.parentOf(group1),{}", // mainGroup.parentOf(group1), group1.parentOf(group1)); // // 从输出看mainGroup的父线程组为system.参考ThreadGroup的私有构造方法,可知system是一个系统线程组,其parent为null.即为初始线程组 // LOGGER.debug("mainGroup.parent.name:{}", mainGroup.getParent() // .getName()); // // GroupExampleThread get1 = new GroupExampleThread("GroupExampleThread-1"); // // 从Thread#start源码看,在启动线程后->会调用group.add(this),即只有在线程启动后,将才会将线程加入其所属线程组 // // 另外注意ThreadGroup#void add(Thread // // t),即该方法只有默认访问权限,即包访问权限.所以应用程序无法调用该方法除非jdk lang包内的库 // get1.start(); // // ThreadGroup#public int activeCount() // // 返回此线程组中活动线程的估计数,结果并不能反映并发活动(因为多线程并发运行,所以不是很精确.多线程的不确定性,如add(某一新增线程启动)/remove(某一现有线程销毁)). // // ->固有的不精确性->建议只用于信息 // // 从源码的实现看,其计算数目只是取了一个groupsSnapshot(syncrhonized),即当前的快照 // LOGGER.debug("mainGroup.activeCount:{}", get1.getThreadGroup() // .activeCount()); // Thread[] mainGroupActiveThreads = new Thread[mainGroup.activeCount()]; // // ThreadGroup#public int enumerate(Thread list[]) // // 将此线程组即其子组中的所有活动线程复制到指定数组中.注应用程序可用使用activeCount方法获取数组大小的估计数. // // 如果数组太小而无法保持所有线程,则忽略额外的线程 // // 可额外校验该方法的返回值是否严格小于参数list的长度 // // 因为此方法固有的竞争条件(源码实现也是取了一个Snapshot(syncrhonized)),建议仅用于信息目的 // mainGroup.enumerate(mainGroupActiveThreads); // // 从输出看:1.主线程组包括两个活动线程,main和GroupExampleThread-1 // // 2.Thread#toString方法返回的信息是Thread[threadName,priority,groupName(如果其group不为null)] // LOGGER.debug("mainGroupActiveThreads:{}", // Arrays.toString(mainGroupActiveThreads)); // // // Thread#public Thread(ThreadGroup group, String name) 指定线程组 // GroupExampleThread get2 = new GroupExampleThread(group1, // "GroupExampleThread-2"); // // 通过调用start将get2加入group1 // get2.start(); // // // 输出:group1.activeCount:1 // LOGGER.debug("group1.activeCount:{}", group1.activeCount()); // // 输出:mainGroup.activeCount:3,即其统计包括子线程的活动线程数目,因为group1为其子组 // LOGGER.debug("mainGroup.activeCount:{}", mainGroup.activeCount()); // // Thread[] mainGroupActiveThreads2 = new Thread[mainGroup.activeCount()]; // // ThreadGroup#public int enumerate(Thread list[], boolean recurse) // // recurse为递归的意思 // // 如果recurse为true表示要复制遍历子线程组的活动线程,否则只是复制当前线程组的活动线程 // // enumerate(Thread list[])方法默认传true // mainGroup.enumerate(mainGroupActiveThreads2, false); // // 输出:[Thread[main,5,main], Thread[GroupExampleThread-1,5,main], null] // // 从输出可以看,只包括主线程组自身的活动线程 // LOGGER.debug("mainGroupActiveThreads2:{}", // Arrays.toString(mainGroupActiveThreads2)); // // Thread[] mainGroupActiveThreads3 = new Thread[mainGroup.activeCount()]; // mainGroup.enumerate(mainGroupActiveThreads3, true); // // 输出:Thread[GroupExampleThread-1,5,main], // // Thread[GroupExampleThread-2,5,ThreadGroup-1]] // // 从输出可以看,包含了主线程组的子线程组group1的活动线程 // LOGGER.debug("mainGroupActiveThreads3:{}", // Arrays.toString(mainGroupActiveThreads3)); // // // 通过enumerate方法得到活动线程的引用,我们可以对其进行操作 // Thread get1Ref = mainGroupActiveThreads3[1]; // LOGGER.debug("get1 == get1Ref:{}", get1 == get1Ref); // // 中断get1,从输出看,get1线程任务确实被打断了 // get1Ref.interrupt(); // // // 可以遍历活动线程列表,进行操作如获取线程状态,判断是否处于活动状态等 // for (Thread tRef : mainGroupActiveThreads3) { // LOGGER.debug("threadName:{},state:{},isAlive:{}", tRef.getName(), // tRef.getState(), tRef.isAlive()); // } // // // ThreadGroup#public final void interrupt() 对线程组及其子组中的所有线程调用interrupt方法 // // 从输出可以看到get2也被中断了 // mainGroup.interrupt(); // // // 自定义的一个group,覆写了uncaughtException方法i // ExampleThreadGroup etg = new ExampleThreadGroup("ExampleThreadGroup"); // AExceptionThread aet = new AExceptionThread(etg, "A-Exception-Thread"); // aet.start(); // // // ThreadGroup#public void list() 将有关此线程组的信息打印的标准输出.此方法只对调试有用 // // 包括此线程组的信息:className[name=groupName,maxPri=],还包括当前组内线程的信息,{@link // // Thread#toString()}.{@link ThreadGroup#toString()} // // 然后迭代子线程组进行输出 // etg.list(); // // mainGroup.list(); // } // // /** // * // * GroupExampleThread // * // * @author landon // * // */ // private static class GroupExampleThread extends Thread { // public GroupExampleThread(String name) { // super(name); // } // // // 此构造方法指定了线程组 // public GroupExampleThread(ThreadGroup tg, String name) { // super(tg, name); // } // // @Override // public void run() { // LOGGER.debug("GroupExampleThread" + "[" + getName() + "]" // + " task begin."); // // // 用sleep模拟任务耗时 // try { // sleep(5 * 1000); // } catch (InterruptedException e) { // LOGGER.debug("GroupExampleThread" + "[" + getName() + "]" // + " was interrutped"); // } // // LOGGER.debug("GroupExampleThread" + "[" + getName() + "]" // + " task end."); // } // } // // // 自实现的一个线程组,覆写了uncaughtException // private static class ExampleThreadGroup extends ThreadGroup { // // public ExampleThreadGroup(String name) { // super(name); // } // // @Override // public void uncaughtException(Thread t, Throwable e) { // // 注.该方法调用是在t线程,参考Thread#dispatchUncaughtException,是一个私有方法 // LOGGER.debug("uncaughtException.thread.name.{}", t.getName(), e); // LOGGER.debug("uncaughtException.thread.state.{}", t.getState()); // // // 这里再重新启动一个新线程 // GroupExampleThread thread = new GroupExampleThread(this, // t.getName()); // thread.start(); // } // } // // private static class AExceptionThread extends Thread { // public AExceptionThread(ThreadGroup group, String name) { // super(group, name); // } // // @Override // public void run() { // // 直接抛出一个空指针异常 // throw new NullPointerException(); // } // } }
e7ed6b9bdc0dade3ec491283a7148a214c557aa6
7b5d877a9eb557f1dc55a42bca9cd97cf523dd8e
/module2(JDBC)/src/main/java/dao/jdbcdaoimpl/DeveloperDAOImpl.java
da6b4f4c49f93083f502d4eeec97b63089233080
[]
no_license
diomedtedid/GoIT_Homeworks
e585d7c844e56f8e6b4cf170ea93525e3ea351b2
4348ca2d7dfe2060aa301e0c4ac24263f3d1509c
refs/heads/master
2021-01-20T08:25:10.402999
2017-09-26T19:30:40
2017-09-26T19:30:40
101,546,241
0
0
null
null
null
null
UTF-8
Java
false
false
10,811
java
package dao.jdbcdaoimpl; import dao.DeveloperDAO; import dao.SkillDAO; import domain.Developer; import domain.Skill; import tools.ConnectionManager; import tools.DBCPConnectionManager; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by User on 17.06.2017. */ public class DeveloperDAOImpl implements DeveloperDAO { private SkillDAO skillDAO = new SkillDAOImpl(); private ConnectionManager connectionManager = new DBCPConnectionManager(); public ConnectionManager getConnectionManager() { return connectionManager; } public void setConnectionManager(ConnectionManager connectionManager) { this.connectionManager = connectionManager; } @Override public void create(Developer entity) throws SQLException { String createQuery = "INSERT INTO goit.developers (dev_name, dev_lastname, dev_email, salary) VALUES (?, ?, ?, ?);"; try (Connection connection = this.connectionManager.getConnection()) { try { //если выпадет исключение, мы откатываем все назад и возвращаем автокомит connection.setAutoCommit(false); //Добавляем Developer в таблицу developers try (PreparedStatement preparedStatement = connection.prepareStatement(createQuery)){ preparedStatement.setString(1, entity.getName()); preparedStatement.setString(2, entity.getLastName()); preparedStatement.setString(3, entity.getEmail()); preparedStatement.setDouble(4, entity.getSalary()); preparedStatement.executeUpdate(); } //Проверяем есть ли у девелопера лист скилов List<Skill> skillList = entity.getSkillList(); if (skillList != null) { if ( !skillList.isEmpty() ) { //Если скилы есть, читаем id записи последнего девелопера в ДБ long lastId; String lastIdQuery = "SELECT dev_id FROM goit.developers ORDER BY dev_id DESC LIMIT 1;"; try (PreparedStatement preparedStatement = connection.prepareStatement(lastIdQuery)){ ResultSet resultSet = preparedStatement.executeQuery(); resultSet.next(); lastId = resultSet.getLong(1); entity.setId(lastId); } writeSkillList (connection, entity); } } //Если все прошло по феншую, то сохраняем все изменения в БД connection.commit(); connection.setAutoCommit(true); } catch (Exception e) { //Если произошла ошибка на любом из этапов откатываем все добавления e.printStackTrace(); connection.rollback(); connection.setAutoCommit(true); } } } private void writeSkillList (Connection connection, Developer developer) throws SQLException { //Соединяем id разраба и id навыка в таблице связи developers_has_skills List<Skill> skillList = developer.getSkillList(); //Читаем все навыки, которыми могут обладать девелоперы List<Skill> generalSkillList = skillDAO.readAll(); String connectQuery = "INSERT INTO goit.developers_has_skills VALUES (?, ?);"; try (PreparedStatement preparedStatement = connection.prepareStatement(connectQuery)){ for (Skill skill : skillList) { int index = generalSkillList.indexOf(skill); if (index != -1) { preparedStatement.setLong(1, developer.getId()); preparedStatement.setLong(2, generalSkillList.get(index).getId()); preparedStatement.addBatch(); } } preparedStatement.executeBatch(); } } @Override public Developer read(Long key) throws SQLException { String readQuery = "SELECT * FROM goit.developers WHERE dev_id=?"; Developer developer = new Developer(); try (Connection connection = this.connectionManager.getConnection()){ try (PreparedStatement preparedStatement = connection.prepareStatement(readQuery)){ preparedStatement.setString(1, String.valueOf(key)); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next() == false) return null; developer.setId(resultSet.getLong("dev_id")); developer.setName(resultSet.getString("dev_name")); developer.setLastName(resultSet.getString("dev_lastname")); developer.setEmail(resultSet.getString("dev_email")); developer.setSalary(resultSet.getDouble("salary")); setAndFillSkillList(connection, developer); } } } return developer; } private void setAndFillSkillList(Connection connection, Developer developer) throws SQLException { // long begine = System.currentTimeMillis(); List<Skill> skillList = new ArrayList<>(); String skillsSelectQuery = "select skills_id from goit.developers_has_skills where developers_id=?;"; try (PreparedStatement preparedStatement = connection.prepareStatement(skillsSelectQuery)){ preparedStatement.setLong(1, developer.getId()); try (ResultSet resultSet = preparedStatement.executeQuery()){ while (resultSet.next()) { // long begin = System.currentTimeMillis(); Skill skill = this.skillDAO.read(resultSet.getLong(1)); // System.out.println("Skill Time = " + (System.currentTimeMillis()- begin)); skillList.add(skill); } // System.out.println(begine - System.currentTimeMillis()); developer.setSkillList(skillList); } } } @Override public List<Developer> readAll() throws SQLException { List<Developer> developerList = new ArrayList<>(); try (Connection connection = connectionManager.getConnection()){ String readAllQuery = "SELECT * FROM goit.developers;"; try (PreparedStatement preparedStatement = connection.prepareStatement(readAllQuery)){ try (ResultSet resultSet = preparedStatement.executeQuery()){ while (resultSet.next()){ Developer developer = new Developer(); developer.setId(resultSet.getLong("dev_id")); developer.setName(resultSet.getString("dev_name")); developer.setLastName(resultSet.getString("dev_lastname")); developer.setEmail(resultSet.getString("dev_email")); developer.setSalary(resultSet.getDouble("salary")); setAndFillSkillList(connection, developer); developerList.add(developer); } } } } return developerList; } @Override public void update(Developer entity) throws SQLException { String updDevQuery = "UPDATE goit.developers SET dev_name = ?, dev_lastname = ?, dev_email = ?, salary = ? " + "WHERE dev_id = ?"; try (Connection connection = this.connectionManager.getConnection()){ try { connection.setAutoCommit(false); try (PreparedStatement preparedStatement = connection.prepareStatement(updDevQuery)){ preparedStatement.setString(1, entity.getName()); preparedStatement.setString(2, entity.getLastName()); preparedStatement.setString(3, entity.getEmail()); preparedStatement.setDouble(4, entity.getSalary()); preparedStatement.setLong(5, entity.getId()); preparedStatement.executeUpdate(); } String deleteConn = "DELETE FROM goit.developers_has_skills WHERE developers_id = ?"; // deleteConn = "1" + deleteConn; try (PreparedStatement preparedStatement = connection.prepareStatement(deleteConn)){ preparedStatement.setLong(1, entity.getId()); preparedStatement.executeUpdate(); writeSkillList(connection, entity); } connection.commit(); connection.setAutoCommit(true); } catch (Exception e) { e.printStackTrace(); connection.rollback(); connection.setAutoCommit(true); } } } @Override public void delete(Developer entity) throws SQLException { try (Connection connection = this.connectionManager.getConnection()){ try { connection.setAutoCommit(false); String deleteDevFromConnTableQuery = "DELETE FROM goit.developers_has_skills WHERE developers_id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(deleteDevFromConnTableQuery)){ preparedStatement.setLong(1, entity.getId()); preparedStatement.executeUpdate(); } String deleteDeveloperQuery = "DELETE FROM goit.developers WHERE dev_id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(deleteDeveloperQuery)){ preparedStatement.setLong(1, entity.getId()); preparedStatement.executeUpdate(); } connection.commit(); connection.setAutoCommit(true); } catch (Exception e) { e.printStackTrace(); connection.rollback(); connection.setAutoCommit(true); } } } @Override public void setSkillDAO(SkillDAO skillDAO) { this.skillDAO = skillDAO; } @Override public SkillDAO getSkillDAO() { return this.skillDAO; } }
1f1a82be507cc3408e15b3d9194c5b88f592ae54
c7b9081e517cb0e5344abaa75fa98398cf39ba66
/novice/minggu-01/hari-04/latihan/ATM/ATMMachine.java
8b3714c958867ddfb2346a9f7353cf37103bd41f
[]
no_license
zthomaz/praxis-academy
b34f6ecada345106555823fd6b2269f960f6a73a
b36ec11a02ea2e36bee8757fb4ea9bd3ce7466b8
refs/heads/master
2020-08-21T12:33:28.094426
2019-10-30T11:07:23
2019-10-30T11:07:23
216,160,729
0
1
null
null
null
null
UTF-8
Java
false
false
4,862
java
package ATM; import java.util.Scanner; import java.io.*; public class ATMMachine { public static void checkBalance() { System.out.println("\tYour current balance is " + BalanceInquiry.getBalance()); } public static void withdrawMoney() { if (BalanceInquiry.balance == 0) { System.out.println("\tYour current balance is zero."); System.out.println("\tYou cannot withdraw!"); System.out.println("\tYou need to deposit money first."); } else if (BalanceInquiry.balance <= 500) { System.out.println("\tYou do not have sufficient money to withdraw"); System.out.println("\tChecked your balance to see your money in the bank."); } else if (Withdraw.withdraw > BalanceInquiry.balance) { System.out.println("\tThe amount you withdraw is greater than to your balance"); System.out.println("\tPlease check the amount you entered."); } else { BalanceInquiry.balance = BalanceInquiry.balance - Withdraw.withdraw; System.out.println("\n\tYou withdraw the amount of Php " + Withdraw.withdraw); } } public static void depositMoney() { System.out.println("\tYou deposited the amount of " + Deposit.getDeposit()); } public static void main(String[] args) { Scanner read = new Scanner(System.in); int select = 0; int choice = 0; System.out.println("===================================================="); System.out.println("\tWelcome to this simple ATM machine"); System.out.println("===================================================="); System.out.println(); do { try { do { System.out.println("\tPlease select ATM Transactions"); System.out.println("\tPress [1] Deposit"); System.out.println("\tPress [2] Withdraw"); System.out.println("\tPress [3] Balance Inquiry"); System.out.println("\tPress [4] Exit"); System.out.print("\n\tWhat would you like to do? "); select = read.nextInt(); if (select > 4) { System.out.println("\n\tPlease select correct transaction."); } else { switch (select) { case 1: System.out.print("\n\tEnter the amount of money to deposit: "); Deposit.deposit = read.nextDouble(); BalanceInquiry.balance = Deposit.deposit + BalanceInquiry.balance; depositMoney(); break; case 2: System.out.print( "\n\tTo withdraw, make sure that you have sufficient balance in your account."); System.out.println(); System.out.print("\tEnter amount of money to withdraw: "); Withdraw.withdraw = read.nextDouble(); withdrawMoney(); break; case 3: checkBalance(); break; default: System.out.print("\n\tTransaction exited."); break; } } } while (select > 4); do { try { System.out.println("\n\tWould you like to try another transaction?"); System.out.println("\n\tPress [1] Yes \n\tPress [2] No"); System.out.print("\tEnter choice: "); choice = read.nextInt(); if (choice > 2) { System.out.print("\n\tPlease select correct choice."); } } catch (Exception e) { System.out.println("\tError Input! Please enter a number only."); read = new Scanner(System.in); System.out.println("\tEnter yout choice:"); choice = read.nextInt(); } } while (choice > 2); } catch (Exception e) { System.out.println("\tError Input! Please enter a number only."); read = new Scanner(System.in); System.out.println("\tEnter yout choice:"); select = read.nextInt(); } } while (choice <= 1); System.out.println("\n\tThank you for using this simple ATM Machine."); } }
c04c530e8be6479fb53496bb963293bbe44a4f40
29678ad06601e48cc79f1ed8ad82630948ed4e25
/src/chart/mksystems/hardware/Marker.java
6b6b5aa853af2d485fe0bf772c80b0da4babad65
[ "LicenseRef-scancode-public-domain" ]
permissive
VijayEluri/Capulin-Chart-Software
d1d85d65847eb34c203be8d0254d800a981c1385
960dce3e5bccf34bf484e1c973002510f22a5aac
refs/heads/master
2020-05-20T11:04:26.050863
2017-03-28T00:10:57
2017-03-28T00:10:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,331
java
/****************************************************************************** * Title: Marker.java * Author: Mike Schoonover * Date: 10/29/16 * * Purpose: * * This class handles variables and actions related to markers which mark the * tube at the position of detected anomalies. * * Open Source Policy: * * This source code is Public Domain and free to any interested party. Any * person, company, or organization may do with it as they please. * */ package chart.mksystems.hardware; //----------------------------------------------------------------------------- import chart.mksystems.inifile.IniFile; import java.util.logging.Level; import java.util.logging.Logger; //----------------------------------------------------------------------------- // class Marker // public class Marker extends Object{ int markerNum; double timeAdjustSpeedRatio = 0; double photoEye1DistanceInInches = 0; int angularPositionInDegrees = 0; public double getPhotoEye1DistanceInInches(){return photoEye1DistanceInInches;} public int getAngularPositionInDegrees(){return angularPositionInDegrees;} //----------------------------------------------------------------------------- // Marker::Marker (constructor) // public Marker(int pMarkerNum) { markerNum = pMarkerNum; }//end of Marker::Marker (constructor) //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Marker::init // // Initializes the object. MUST be called by sub classes after instantiation. // public void init() { }//end of Marker::init //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Marker::configure // // Loads configuration settings from the configuration.ini file. // // Only configuration data for this class are loaded here. Each // child object should be allowed to load its own data. // public void configure(IniFile pConfigFile) { String markerNumText = "Marker " + (markerNum+1); timeAdjustSpeedRatio = pConfigFile.readDouble( "Markers" , markerNumText+ " Time Adjust Speed Ratio", 0.0); photoEye1DistanceInInches = pConfigFile.readDouble( "Markers", markerNumText + " to Photo Eye 1 Distance in Inches", 0); angularPositionInDegrees = pConfigFile.readInt( "Markers", markerNumText + " Angular Position From TDC in Degrees", 0); }//end of Marker::configure //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Marker::logSevere // // Logs pMessage with level SEVERE using the Java logger. // void logSevere(String pMessage) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, pMessage); }//end of Marker::logSevere //----------------------------------------------------------------------------- }//end of class Marker //----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
1f1fd9d795ef19e1c41f916dfe04124a643f8b66
7df40f6ea2209b7d48979465fd8081ec2ad198cc
/TOOLS/server/org/apache/http/HttpException.java
646fc8d6a70582ba6a756369eb981ae3e7e3251f
[ "IJG" ]
permissive
warchiefmarkus/WurmServerModLauncher-0.43
d513810045c7f9aebbf2ec3ee38fc94ccdadd6db
3e9d624577178cd4a5c159e8f61a1dd33d9463f6
refs/heads/master
2021-09-27T10:11:56.037815
2021-09-19T16:23:45
2021-09-19T16:23:45
252,689,028
0
0
null
2021-09-19T16:53:10
2020-04-03T09:33:50
Java
UTF-8
Java
false
false
1,162
java
/* */ package org.apache.http; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class HttpException /* */ extends Exception /* */ { /* */ private static final long serialVersionUID = -5437299376222011036L; /* */ /* */ public HttpException() {} /* */ /* */ public HttpException(String message) { /* 52 */ super(message); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public HttpException(String message, Throwable cause) { /* 63 */ super(message); /* 64 */ initCause(cause); /* */ } /* */ } /* Location: C:\Users\leo\Desktop\server.jar!\org\apache\http\HttpException.class * Java compiler version: 5 (49.0) * JD-Core Version: 1.1.3 */
12daf27be5423f130ce1d4cff43edd9ed24fbcdf
f7fa27b98e884bba998613bb4bdf5581782d5d97
/src/main/java/dev/lallemand/lcore/profile/punishment/PunishmentJsonSerializer.java
dc2e900ff9138db726dc8af8d0e108d6fad0200f
[]
no_license
weak/lCore
e5de6c0f4713f3fa47a8165d8efca37e8e0f5b2a
4033f8bde5da9ada3cdfa2046f119b48d4d2f36d
refs/heads/main
2023-01-13T13:22:49.941151
2020-11-16T16:28:24
2020-11-16T16:28:24
312,318,890
0
0
null
null
null
null
UTF-8
Java
false
false
1,296
java
package dev.lallemand.lcore.profile.punishment; import com.google.gson.JsonObject; import dev.lallemand.lcore.util.json.JsonSerializer; public class PunishmentJsonSerializer implements JsonSerializer<Punishment> { @Override public JsonObject serialize(Punishment punishment) { JsonObject object = new JsonObject(); object.addProperty("uuid", punishment.getUuid().toString()); object.addProperty("targetID", punishment.getTargetID().toString()); object.addProperty("type", punishment.getType().name()); object.addProperty("addedBy", punishment.getAddedBy() == null ? null : punishment.getAddedBy().toString()); object.addProperty("addedAt", punishment.getAddedAt()); object.addProperty("addedReason", punishment.getAddedReason()); object.addProperty("expiration", punishment.getDuration()); object.addProperty("removedBy", punishment.getRemovedBy() == null ? null : punishment.getRemovedBy().toString()); object.addProperty("removedAt", punishment.getRemovedAt()); object.addProperty("removedReason", punishment.getRemovedReason()); object.addProperty("removed", punishment.isRemoved()); object.addProperty("serverName", punishment.getServerName()); return object; } }
066d8bf0aadcda39e6bcb34e92404b9d9c969e01
55678877ac2e914f09cabc9aba457e52caa92cad
/gen/com/touhiDroid/backgroundgpsgetter/R.java
0c7c49d5d183699da6df50fae4687b92637cb8d8
[]
no_license
touhiDroid/ShipperTrek
4c23122fe3f944c514b41c24f121cb5d7022fe2c
794f0c663d4988f3de6918371e4d059ec1f30fcc
refs/heads/master
2021-05-28T19:26:17.104814
2014-11-23T13:51:33
2014-11-23T13:51:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,303
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.touhiDroid.backgroundgpsgetter; public final class R { public static final class attr { } public static final class drawable { public static final int fail=0x7f020000; public static final int gcm_logo=0x7f020001; public static final int ic_action_search=0x7f020002; public static final int ic_launcher=0x7f020003; public static final int success=0x7f020004; } public static final class id { public static final int btnRegister=0x7f060003; public static final int etEmail=0x7f060002; public static final int etName=0x7f060001; public static final int tvGPS=0x7f060000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int already_registered=0x7f040004; public static final int app_name=0x7f040000; public static final int error_config=0x7f040003; public static final int gcm_deleted=0x7f04000a; public static final int gcm_error=0x7f040008; public static final int gcm_message=0x7f040007; public static final int gcm_recoverable_error=0x7f040009; public static final int gcm_registered=0x7f040005; public static final int gcm_unregistered=0x7f040006; public static final int menu_settings=0x7f040001; public static final int options_clear=0x7f040012; public static final int options_exit=0x7f040013; public static final int options_register=0x7f040010; public static final int options_unregister=0x7f040011; public static final int server_register_error=0x7f04000e; public static final int server_registered=0x7f04000c; public static final int server_registering=0x7f04000b; public static final int server_unregister_error=0x7f04000f; public static final int server_unregistered=0x7f04000d; public static final int title_activity_main=0x7f040002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f050000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f050001; } }
76bd37ec3e048bb73871c9eebd5e99ee8a40a073
f7cdcaea1129d83f5eaefd6243f32c92da79a9dc
/alembic/src/main/java/liquer/alchemy/alembic/Log.java
f61bf1174a972d021b6228866f6514e4b3b527fc
[ "Apache-2.0" ]
permissive
sius/alchemy
92c3e075e79ecab868aba28d529a0628476af1c5
9bea90881245affb6cf38fc3e26a55ee17fda439
refs/heads/master
2022-03-13T13:37:16.262228
2022-01-05T12:26:56
2022-01-05T12:26:56
210,592,764
0
0
Apache-2.0
2022-01-05T12:26:58
2019-09-24T12:04:41
Java
UTF-8
Java
false
false
782
java
package liquer.alchemy.alembic; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; public interface Log<T> { public static final int LF = 10; default T println(String message) { return println(message, System.out); } default T println(String message, OutputStream out) { if (out == null || System.out == out) { System.out.println(message); } else { try (final OutputStream o = out) { o.write(message.getBytes(StandardCharsets.UTF_8)); o.write(LF); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } return (T)this; } }
cb026b765287f1d1b71623a0d40737a6a6c59fbd
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/29/29_d5c7a28b5346f8c051885dd4f982119c4f1bd5fa/EvaluationException/29_d5c7a28b5346f8c051885dd4f982119c4f1bd5fa_EvaluationException_s.java
b382023c931c287d9d61b81e2b75e67bfbc41b9a
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
1,600
java
/* * Copyright 2004-2007 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 org.springframework.binding.expression; import org.springframework.core.NestedRuntimeException; /** * Indicates an expression evaluation failed. * * @author Keith Donald */ public class EvaluationException extends NestedRuntimeException { /** * The evaluation attempt that failed. */ private EvaluationAttempt evaluationAttempt; /** * Creates a new evaluation exception. * @param evaluationAttempt the evaluation attempt that failed * @param cause the underlying cause of this exception */ public EvaluationException(EvaluationAttempt evaluationAttempt, Throwable cause) { super("Expression " + evaluationAttempt + " failed - make sure the expression is evaluatable on the target object", cause); this.evaluationAttempt = evaluationAttempt; } /** * Returns the evaluation attempt that failed. */ public EvaluationAttempt getEvaluationAttempt() { return evaluationAttempt; } }
4e0d0f41d34688b9f8fa9a652bd20adb3e99bcae
800b16077c126979e266af575f3cc476346241b0
/AutoevaluacionWeb/src/main/java/co/com/poli/autoevaluacion/domain/AutoevaluacionDetalle.java
e8876bf81f0849439d39bd1418569ada09edeed3
[]
no_license
juanprada/autoevaluacion
d74741f728135d53cc9e72fd9536811fb7616335
e2d78495318a959109568fa9055cff7649d93c11
refs/heads/master
2021-08-23T23:34:50.021524
2017-12-07T03:07:49
2017-12-07T03:07:49
113,395,549
0
0
null
null
null
null
UTF-8
Java
false
false
1,565
java
package co.com.poli.autoevaluacion.domain; 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="autoevaluacion_detalle") public class AutoevaluacionDetalle { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long autoevaluacionDetalleID; @ManyToOne @JoinColumn(name="autoevaluacionID") private Autoevaluacion autoevaluacion; @ManyToOne @JoinColumn(name="indicadorID") private Indicador indicador; private Integer calificacion; private String observaciones; public Long getAutoevaluacionDetalleID() { return autoevaluacionDetalleID; } public void setAutoevaluacionDetalleID(Long autoevaluacionDetalleID) { this.autoevaluacionDetalleID = autoevaluacionDetalleID; } public Autoevaluacion getAutoevaluacion() { return autoevaluacion; } public void setAutoevaluacion(Autoevaluacion autoevaluacion) { this.autoevaluacion = autoevaluacion; } public Indicador getIndicador() { return indicador; } public void setIndicador(Indicador indicador) { this.indicador = indicador; } public Integer getCalificacion() { return calificacion; } public void setCalificacion(Integer calificacion) { this.calificacion = calificacion; } public String getObservaciones() { return observaciones; } public void setObservaciones(String observaciones) { this.observaciones = observaciones; } }
09b8c4a6ac8489e8f4df90c77139f8558ddb9f74
c074acf2945feebfe5927478eb36dee946364f0a
/multiple-thread/src/main/java/com/chapter1/P24/RunTest.java
9d6d46e600385b2e917f207c9e20e2bb6afd693f
[]
no_license
wooyeeyii/think-in-java
fcbf9d7baf9fe30ac0dbdb8ebe43a98f69541175
3d8c7ab5a7ede7b9d625881bda350ecc19a47375
refs/heads/master
2021-11-08T17:08:10.117191
2021-11-05T01:22:40
2021-11-05T01:22:40
178,848,694
1
0
null
null
null
null
UTF-8
Java
false
false
530
java
package com.chapter1.P24; public class RunTest { public static void main(String[] args) { try { Thread thread = new Thread(() -> { for (int i = 0; i <= 50000; i++) { System.out.println("i = " + i); } }); thread.start(); Thread.sleep(2000); thread.interrupt(); } catch (InterruptedException e) { System.out.println("main catch."); e.printStackTrace(); } } }
9f246fa89aec1eee7963e259be7ab2e30a3db892
ab582cc0bf8f86c5606b6c4f7acc178ea467e0ca
/src/main/java/com/example/loginuser/model/Config.java
741e67198e3ba5286579741c7ee59e37aaef8aaa
[]
no_license
usfcs-perf-eng-s20/heroku-project-login-user
84822d2ffddc6accfaa9c19d8889a103405fc001
42ebd4960af8a9735d64a3437b74b8b63370500c
refs/heads/save-edr
2022-05-28T03:42:48.726313
2020-04-30T16:14:06
2020-04-30T16:14:06
241,405,609
0
0
null
2022-05-20T21:29:23
2020-02-18T16:06:58
Java
UTF-8
Java
false
false
779
java
package com.example.loginuser.model; import java.io.FileNotFoundException; import java.io.FileReader; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; public class Config { private boolean faves; private boolean search; private boolean login; private boolean analytics; public boolean isFaves() { return faves; } public void setFaves(boolean faves) { this.faves = faves; } public boolean isSearch() { return search; } public void setSearch(boolean search) { this.search = search; } public boolean isLogin() { return login; } public void setLogin(boolean login) { this.login = login; } public boolean isAnalytics() { return analytics; } public void setAnalytics(boolean analytics) { this.analytics = analytics; } }
6efbe5e19af01dd448e4626763c57d51a4f2c9b7
6c4c6baacc01545469d11f3a326072bf2e91bed5
/kommandozeilen_implementation/KommandozeilenStarter.java
bd4247f8721d6ca7d3e16238a790076d6f29d06b
[ "MIT" ]
permissive
Josef-Friedrich/Wer-wird-INFORMATIKaer
d1aeefdacf5a2d7df09b6b364e4571a3778d0fca
77b70b6af012d55d1e66cb3c61ef364f07b21c0e
refs/heads/master
2022-12-31T23:17:55.513476
2020-10-23T08:22:01
2020-10-23T08:22:01
297,941,257
0
0
null
null
null
null
UTF-8
Java
false
false
467
java
package kommandozeilen_implementation; /** * Kleine Hüll-Klasse um die Kommandozeile aufzurufen. * * Dient dazu um Fehler abzufangen. Es gibt in der Swing-Implementation des * Spiels auch eine korrespondierende Klasse, die * {@link swing_implementation.SwingStarter} heißt. * */ public class KommandozeilenStarter { public KommandozeilenStarter() { try { new KommandoZeile(); } catch (Exception e) { e.printStackTrace(); } } }
9f40ea951adb217ed1696425df1fc3f2c36cb470
a727b0ab64a5ef0811bf786de25dfe32f8c1bf61
/frontend/src/main/java/no/woact/ritand16/Application.java
14bdd6ce5e021dd02e4125816d579a21f70749ca
[]
no_license
andreasholteritter/PGPage
15b47b9914b183215b1776027df0c59c4cdfe9de
ffdf74a7de28448d8662727ed3bc58b97d53ab30
refs/heads/master
2020-03-09T14:18:42.034775
2018-04-09T21:07:54
2018-04-09T21:07:54
128,831,503
0
0
null
null
null
null
UTF-8
Java
false
false
308
java
package no.woact.ritand16; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
24a6404286b3aef36b0f98bfd82c59f8278a341d
368f9e9033ba7af0df02441b1ea1d72537baa582
/src/main/java/com/mageddo/codestyle/Stuff.java
30c4df9896c5ccab06e225d8f484dbba9d31ffa7
[ "Apache-2.0" ]
permissive
mageddo/java-examples
f344de23eda3aab22449b975c1abab87284fae2f
4dab6212ee88311f10eeeea576d3314f5cb616ec
refs/heads/master
2023-09-04T12:50:43.366836
2023-08-21T03:31:19
2023-08-21T03:31:19
162,375,522
21
10
Apache-2.0
2023-09-14T10:19:28
2018-12-19T03:04:25
Java
UTF-8
Java
false
false
783
java
package com.mageddo.codestyle; import java.util.List; import static java.util.Collections.singletonMap; public class Stuff { public void aVeryLongMethodNameExplainingWhatItDoes(String argumentA, String argumentB, String argumentC, String argumentD, String argumentE, String argumentF ) { System.out.println("do stuff"); } public static void main(String[] args) { final List<String> fruits = List.of("apple", "orange"); final var myObject = singletonMap("key", "value"); new Stuff().aVeryLongMethodNameExplainingWhatItDoes( "argument A value", "argument B value", "string for argument C", "argument D value", "argument E value", "argument F value" ); if (1 == 1) { } for (int i = 0; i < 10; i++) { } } }
093e4582de697bcd6fa1ed9db9ec23ddd03151df
e7e4c88c5e48006ed8e54416fb55b74752303bb8
/core/src/main/java/com/omega/core/database/DatastoreManagerSingleton.java
4c15158b02c6a41946d9874806d57fe54a7684a4
[]
no_license
KyuBlade/BotOfSteel
a08311edb46fe387a6e0046e6d6abdbc9b05cce8
a1c918a6c982e833af4a05cb79829f966564e5a4
refs/heads/master
2020-05-26T15:35:59.843758
2018-10-22T15:39:31
2018-10-22T15:39:31
82,493,599
0
1
null
null
null
null
UTF-8
Java
false
false
1,240
java
package com.omega.core.database; import com.mongodb.MongoClient; import com.omega.core.database.impl.morphia.MorphiaDatastoreManager; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; public class DatastoreManagerSingleton { private DatastoreManager datastoreManager; private DatastoreManagerSingleton() { } private DatastoreManager createDatastoreManager() { return createMorphiaDatastoreManager(); } private MorphiaDatastoreManager createMorphiaDatastoreManager() { Morphia morphia = new Morphia(); Datastore datastore = morphia.createDatastore(new MongoClient("localhost:27017"), "discord_bot"); return new MorphiaDatastoreManager(morphia, datastore); } public static DatastoreManager getInstance() { DatastoreManagerSingleton singleton = DatastoreManagerSingletonHolder.INSTANCE; if (singleton.datastoreManager == null) { singleton.datastoreManager = singleton.createDatastoreManager(); } return singleton.datastoreManager; } private static class DatastoreManagerSingletonHolder { private static final DatastoreManagerSingleton INSTANCE = new DatastoreManagerSingleton(); } }
a6ac947deadb2dadd1d07f892f796fb318e8a8ee
0b47197f184f4b3a8ef02c071fb86b07a7d55f8b
/sample-gateway-zuul-fallback/src/main/java/com/zhangzhigang/cloud/ZuulApplication.java
a39b0da97025503d4396956f27a9ae928ee64511
[]
no_license
zhangzhigangcoder/spring-cloud-sample
75c77e7b734431e4eee403ccccba692b104f0ccf
4dcdce10dfc89e8ff8763f53f1582ac6cf4f7ee5
refs/heads/master
2021-03-17T17:15:39.151568
2020-08-01T05:26:17
2020-08-01T05:26:17
247,004,970
0
0
null
null
null
null
UTF-8
Java
false
false
561
java
package com.zhangzhigang.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; /** * 此处不需要用 @EnableEurekaClient注解就可以直接注册到eureka * @author zhangzhigang * @date 2018年5月15日 下午2:48:19 */ @SpringBootApplication @EnableZuulProxy public class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); } }
449a0e04c33a0a26ebb2f36e349a8bf8a1707905
9ad04ca741fd1b546bc69e78af422513c3107dac
/src/main/java/org/frank/resources/BodyMeasurementResource.java
063eea76b79c1ce3ea0874d8d84df8dac09eeca3
[]
no_license
pussinboots/BodyMeasurement
a57874b257051286374b6c85656fecfb9dcc7e83
4988d028e155c3fbf770fce9b5c22f1d04862afb
refs/heads/master
2020-12-02T18:20:32.442776
2017-07-21T08:12:38
2017-07-21T08:12:38
96,517,264
0
0
null
null
null
null
UTF-8
Java
false
false
4,351
java
package org.frank.resources; import lombok.Data; import lombok.experimental.Accessors; import org.frank.json.ApplicationStatus; import org.frank.json.ApplicationStatus.State; import org.frank.json.ApplicationStatus.Status; import org.frank.json.BodyMeasurement; import org.frank.json.JSONResponse; import org.frank.persistence.PersistenceProvider; import org.frank.persistence.database.BodyMeasurementDB; import org.frank.utils.CollectionsUtils; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.SQLException; import java.util.Calendar; import java.util.List; import java.util.Map; import static org.frank.utils.CollectionsUtils.Pair.pair; @Path("body") public class BodyMeasurementResource { public static final int DEFAULT_ITEM_LIMIT = 10; public static final int MAX_ITEM_LIMIT = 100; @Data @Accessors(fluent = true) public static class Paging implements PersistenceProvider.Page { private @QueryParam("page") @DefaultValue("1") int page = 1; private @QueryParam("limit") @DefaultValue(DEFAULT_ITEM_LIMIT + "") long limit; //Paging start with first page that is page 1 public int page() { return ( page > 0 )? page - 1 : 0; } public long limit() { return ( limit > 0 && limit <= MAX_ITEM_LIMIT)? limit : DEFAULT_ITEM_LIMIT; } @Override public long offset() { return page() * limit(); } } @Data @Accessors(fluent = true) private static class FilterMeasurements implements PersistenceProvider.StorageFilter<FilterMeasurements> { private @QueryParam("patientId") String patientId; @Override public Map<String, Object> transform(FilterMeasurements entity) { return CollectionsUtils.hashMap(pair("patientId", patientId)); } @Override public Map<String, Object> transform() { return transform(this); } } private static class DatabaseStatus { public static Status status(PersistenceProvider.Storage storage) { Status databaseStatus = new Status().type("database"); try { storage.healthCheck(); databaseStatus.state(State.RUNNING); } catch (SQLException e) { databaseStatus.state(State.ERROR); databaseStatus.errorMessage(e.getMessage()); } databaseStatus.checkedAt(Calendar.getInstance().getTime()); return databaseStatus; } } @Inject PersistenceProvider.Storage<BodyMeasurementDB, Long> bodyMeasurementDao; @GET @Produces(MediaType.APPLICATION_JSON) @Path("/meta/status") public ApplicationStatus status() { return new ApplicationStatus() .addStatus(new Status().type("application").state(State.RUNNING).checkedAt(Calendar.getInstance().getTime())) .addStatus(DatabaseStatus.status(bodyMeasurementDao)); } @GET @Path("measurement/{measurementId}") @Produces(MediaType.APPLICATION_JSON) public JSONResponse<BodyMeasurement> getMeasurement(@PathParam("measurementId") Long measurementId) throws SQLException { BodyMeasurement bodyMeasurement = BodyMeasurement.fromPojo(bodyMeasurementDao.getAs(measurementId, BodyMeasurementDB.tranformerToPojo())); return new JSONResponse<BodyMeasurement>().item(bodyMeasurement); } @GET @Path("measurements") @Produces(MediaType.APPLICATION_JSON) public JSONResponse<BodyMeasurement> getMeasurements(@BeanParam FilterMeasurements filterMeasurements, @BeanParam Paging paging) throws SQLException { List<BodyMeasurement> bodyMeasurements = bodyMeasurementDao.listAs(filterMeasurements, paging, entity -> BodyMeasurement.fromPojo(entity.toPojo())); return new JSONResponse<BodyMeasurement>().items(bodyMeasurements); } @POST @Path("measurement") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JSONResponse<BodyMeasurement> saveMeasurement(BodyMeasurement bodyMeasurement) throws SQLException { BodyMeasurementDB bodyMeasurementDB = bodyMeasurementDao.save(new BodyMeasurementDB().fromPojo(bodyMeasurement.toPojo())); return new JSONResponse<BodyMeasurement>().item(BodyMeasurement.fromPojo(bodyMeasurementDB.toPojo())); } }
be77a9028158b6c0cc9f66d2ff304c908c345c24
77e73c478327df24f5cb41ab8684588befdf1688
/src/JDBC/JDBC191.java
38b0eb83f99ca7ddca5ec0c5dd3a3bf57a63a762
[]
no_license
trahim13/MyLessons
620a3184182d46fa5822f0a7a20a30e02e5339d8
99bc986672a80202dc774a4ab05537c82982ea4a
refs/heads/master
2021-01-25T09:20:47.402256
2017-06-22T04:54:04
2017-06-22T04:54:04
93,817,270
0
0
null
null
null
null
UTF-8
Java
false
false
1,310
java
package JDBC; import java.sql.*; import java.util.Calendar; public class JDBC191 { public static void main(String[] args) throws ClassNotFoundException, SQLException { final String URL = "jdbc:mysql://localhost:3306/mydbtest"; final String USER = "root"; final String PASSWOR = "root"; Class.forName("com.mysql.jdbc.Driver"); try (Connection con = DriverManager.getConnection(URL, USER, PASSWOR); Statement st = con.createStatement()) { st.execute("drop table if exists JDBC191"); st.executeUpdate("create table if not exists JDBC191(id mediumint auto_increment not null, name char(30) not null, dt date, primary key(id))"); PreparedStatement ps = con.prepareStatement("insert into JDBC191 (name, dt) values ('name', ?)"); ps.setDate(1, new Date(System.currentTimeMillis())); //1490735259655L ps.execute(); System.out.println(ps); // st.executeUpdate("insert into jdbc191 (name, dt) values ('same name', {d'2018-3-29'})"); ResultSet rs = st.executeQuery("select * from jdbc191"); while (rs.next()) System.out.println(rs.getDate("dt")); } catch (SQLException e) { e.printStackTrace(); } } }
779f78604873c6d9da86a0791d7f90ca71ee9f28
5460701929009b36f4e5da8b610fee31d0c210e3
/src/main/java/com/kamigun/gw2eventtracker/service/tts/DoSpeakServiceResponse.java
b1e9decf07da409f5799609591a2cca39fc17e43
[]
no_license
shinobi81/Gw2EventTracker
08aecdb1db550a5aa0aebf3b53b43bd56cf3a4df
2cd5a32bc3d4c93cfa62fcb4309c4a7fea3455f5
refs/heads/master
2021-01-19T14:29:53.397519
2014-02-22T10:32:01
2014-02-22T10:32:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
309
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.kamigun.gw2eventtracker.service.tts; import com.kamigun.gw2eventtracker.model.Response; /** * * @author shinobi */ public class DoSpeakServiceResponse extends Response { }
[ "shinobi@shinobi-PC" ]
shinobi@shinobi-PC
7c5d409831b18a3c736f9aae612707f7013b00b6
1e4b65faf6b14e61eb48dfe652e3c32f57ba7cac
/loader/src/uk/ac/manchester/cs/openphacts/ims/constants/DctermsConstants.java
f6892aaf21a54e9166cc41deaeec46ca29231a50
[]
no_license
openphacts/IdentityMappingService
ad4398cded4f00e25fbd60662a49655cc0231631
843df4c5a423936a9aa86d240d8298cec862f609
refs/heads/master
2021-01-17T11:02:24.145177
2017-10-11T08:48:32
2017-10-11T08:48:32
10,176,369
3
3
null
2017-05-04T01:38:16
2013-05-20T15:59:04
Java
UTF-8
Java
false
false
1,630
java
// BridgeDb, // An abstraction layer for identifier mapping services, both local and online. // // Copyright 2006-2009 BridgeDb developers // Copyright 2012-2013 Christian Y. A. Brenninkmeijer // Copyright 2012-2013 OpenPhacts // // 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 uk.ac.manchester.cs.openphacts.ims.constants; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; /** * */ public class DctermsConstants { private static final String dctermns = "http://purl.org/dc/terms/"; public static final URI CREATED = new URIImpl(dctermns + "created"); public static final URI CREATOR = new URIImpl(dctermns + "creator"); public static final URI DESCRIPTION = new URIImpl(dctermns + "description"); public static final URI LICENSE = new URIImpl(dctermns + "license"); public static final URI MODIFIED = new URIImpl(dctermns + "modified"); public static final URI PUBLISHER = new URIImpl(dctermns + "publisher"); public static final URI SUBJECT = new URIImpl(dctermns + "subject"); public static final URI TITLE = new URIImpl(dctermns + "title"); }
5b9a629b253e92ca38aaaab4b9fcad85ea81502d
4db88170615505efaa71854fe1f720c451868737
/IntroductionToJava/Chapter14/E14_01/src/E14_01.java
8398dfaa822924d61a9bc35c97e0aa4e1c8c3a4a
[]
no_license
TuranAktass/IntroductionToJava
c9fab4f679ca284455d9310cdf02d9adca47e06a
27824da618e41dbe49efe3738df771501269392b
refs/heads/main
2023-07-17T04:34:33.734635
2021-09-01T03:54:18
2021-09-01T03:54:18
309,123,556
5
0
null
null
null
null
UTF-8
Java
false
false
1,218
java
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class E14_01 extends Application{ @Override public void start(Stage primaryStage) throws Exception { Image img1 = new Image("img1.gif"); Image img2 = new Image("img2.gif"); Image img3 = new Image("img3.gif"); Image img4 = new Image("img4.gif"); ImageView imgView1 = new ImageView(img1); ImageView imgView2 = new ImageView(img2); ImageView imgView3 = new ImageView(img3); ImageView imgView4 = new ImageView(img4); GridPane pane = new GridPane(); pane.setPadding(new Insets(2,2,2,2)); pane.add(imgView1, 0 , 0); pane.add(imgView2, 1, 0); pane.add(imgView3, 0 , 1); pane.add(imgView4, 1, 1); Scene scene = new Scene(pane); primaryStage.setTitle("Exercise 14_01"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String args[]){ Application.launch(args); } }
9aa67bcb185e7ebeb222fe0abfdc10379319eb68
b50f9b97b37af41fadfcb241d67b727ec510ff52
/Main.java
62ec7589aa48cd286aa7ba4ccf8a126829ba30fe
[]
no_license
marzia2936/Object-Passing-Example
49210524a66b9b13ac8e962a0c21eb507f5da463
44bf67865b1681d6d7598d6d3c60cba6f46a0d01
refs/heads/main
2023-04-07T00:27:36.081414
2021-04-23T17:16:33
2021-04-23T17:16:33
360,956,003
1
0
null
null
null
null
UTF-8
Java
false
false
315
java
package package1; public class Main { public static void main(String[] args) { Student object1 = new Student(121,3.80); Student object11 = new Student(121,3.70); Admin object2 = new Admin(); object2.waiver_calculation(object1); object2.waiver_calculation(object11); } }
8071781af3161099b21ca814238dc3f77ddd02c5
fb19d351fa9acaa6bfb57e451e2a2a6ca3d68c74
/weigeEdu/console/console-service.impl/src/main/java/com/weige/edu/service/impl/VideoInfoServiceImpl.java
1b2e950b318c751c6fd4d3578a43081dd8ae5c28
[]
no_license
Sickle2/teacher
149a9810fee6372aee52ed5072b5808d6c9751c4
5f0ed08e992671bff4c8232384e277145639d397
refs/heads/master
2021-09-05T07:22:16.767904
2018-01-25T06:06:17
2018-01-25T06:06:47
114,355,169
0
0
null
2017-12-15T09:52:48
2017-12-15T09:52:47
null
UTF-8
Java
false
false
2,931
java
package com.weige.edu.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.weige.edu.dao.VideoInfoDAO; import com.weige.edu.dao.data.VideoInfoDO; import com.weige.edu.dao.data.view.VideoInfoView; import com.weige.edu.service.VideoInfoService; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * * @comment video_info ServiceImpl * @author zhaoshuai * @date 2018-01-25 11:03:35 * @qq 122331175 * @version 1.0 */ @Component("videoInfoService") public class VideoInfoServiceImpl implements VideoInfoService { @Autowired private VideoInfoDAO dao; /** * 添加video_info * @param video_info View * @return */ public int add(VideoInfoView videoInfoView){ VideoInfoDO videoInfoDO = new VideoInfoDO(); BeanUtils.copyProperties(videoInfoView,videoInfoDO); return dao.add(videoInfoDO); } /** * 更新video_info(无条件) * @param video_info View * @return */ public int update(VideoInfoView videoInfoView){ VideoInfoDO videoInfoDO = new VideoInfoDO(); BeanUtils.copyProperties(videoInfoView,videoInfoDO); return dao.update(videoInfoDO); } /** * 更新video_info(有条件) * @param video_info View * @return */ public int updateBySelective(VideoInfoView videoInfoView){ VideoInfoDO videoInfoDO = new VideoInfoDO(); BeanUtils.copyProperties(videoInfoView,videoInfoDO); return dao.updateBySelective(videoInfoDO); } /** * 删除video_info * @param uuid * @return */ public int delete(String[] uuid){ return dao.delete(uuid); } /** * 查询video_info(根据ID) * @param uuid * @return */ public VideoInfoDO queryById(String uuid){ return dao.queryById(uuid); } /** * 查询video_info总数(有条件) * @param video_info View * @return count */ public Integer queryByCount(VideoInfoView videoInfoView){ VideoInfoDO videoInfoDO = new VideoInfoDO(); BeanUtils.copyProperties(videoInfoView,videoInfoDO); return dao.queryByCount(videoInfoDO); } /** * 查询video_info信息列表(有条件) * @param video_info DO * @return List<VideoInfoDO> */ public List<VideoInfoDO> queryByList(VideoInfoDO videoInfoDO){ return dao.queryByList(videoInfoDO); } /** * 查询video_info信息列表(有条件) * @param video_info DO * @return List<VideoInfoDO> */ public List<VideoInfoDO> queryByListNoPage(VideoInfoDO videoInfoDO, String params, String order){ return dao.queryByListNoPage(videoInfoDO); } }
aee1b2bc0db4d8c0c8161f02e5f08d38cc55a487
65c1a39175c136c2419298884796837011b9845a
/src/Tp_1920_JoaoValente_2017016033/logica/estados/Event.java
13c94b11a2a4029a240610d2b1c10efff02412e3
[]
no_license
joaovalente99/Projeto
1a341409407180b587cbe92aa3b7fd3fa3171b6c
82624335eb939f7167db07f39b7ff0c838c080cc
refs/heads/master
2022-11-08T14:12:13.918689
2020-06-27T20:21:19
2020-06-27T20:21:19
261,823,232
0
0
null
null
null
null
UTF-8
Java
false
false
1,092
java
package Tp_1920_JoaoValente_2017016033.logica.estados; import Tp_1920_JoaoValente_2017016033.logica.InteracaoEsperada; import Tp_1920_JoaoValente_2017016033.logica.dados.JogoDados; public class Event extends EstadoAdapter{ public Event(JogoDados jogo) { super(jogo); } @Override public IEstado saiDoEvento() { if(jogo.caiEvento() == 0) { if(!jogo.lastChance()) return new GameOver(jogo); else return new LastChance(jogo); } jogo.setPlanet(null); jogo.setAlien(null); return new SpaceTravel(jogo); } @Override public IEstado saiDoEvento(int id) { if(jogo.caiEvento(id) == 0) { if(!jogo.lastChance()) return new GameOver(jogo); else return new LastChance(jogo); } jogo.setPlanet(null); jogo.setAlien(null); return new SpaceTravel(jogo); } @Override public InteracaoEsperada getInteracaoEsperada() { return InteracaoEsperada.EVENT; } }