blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
35606629ff28e04941843ae802379e69d7e560dd
Java
gozdekurtulmus/chainStoreApp_OOP_1
/src/chainStoreApp/AnnualSale.java
UTF-8
693
2.671875
3
[]
no_license
package chainStoreApp; public class AnnualSale { private ItemTransaction[] itemTransaction; public AnnualSale(String givenFile) { itemTransaction = new ItemTransaction[32]; fillItemTransaction(givenFile); } private void fillItemTransaction(String givenFile) { FileIO read = new FileIO(); String[][] itemList = read.readToArray(givenFile); for(int i=0; i< itemTransaction.length; i++) { this.itemTransaction[i] = new ItemTransaction(itemList[i]); } } public ItemTransaction[] getItemTransaction() { return this.itemTransaction;} public void setItemTransaction(ItemTransaction[] itemTransaction) {this.itemTransaction = itemTransaction; } }
true
81ec9c9d1d5fad82d7ecdd1fc6fde8d2d96231e1
Java
cwan/mikaboshi-jdbc-monitor
/mikaboshi-jdbc-monitor-project/src/main/java/net/mikaboshi/jdbc/monitor/log/aspect/StatementLogger.java
UTF-8
9,365
2.234375
2
[ "Apache-2.0" ]
permissive
package net.mikaboshi.jdbc.monitor.log.aspect; import java.sql.PreparedStatement; import net.mikaboshi.jdbc.monitor.LogEntry; import net.mikaboshi.jdbc.monitor.LogMode; import net.mikaboshi.jdbc.monitor.LogModeMBean; import net.mikaboshi.jdbc.monitor.LogType; import net.mikaboshi.jdbc.monitor.LogWriter; import net.mikaboshi.jdbc.monitor.Result; import net.mikaboshi.jdbc.monitor.SqlUtils; import net.mikaboshi.jdbc.monitor.log.wrapper.PreparedStatementWrapper; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; /** * SQL(Statement, PreparedStatement)の実行をログに出力する。 * * @author Takuma Umezawa */ @Aspect public class StatementLogger { @Pointcut("call(* java.sql.Connection+.prepareStatement(..))") public void prepareStatement() {} // execute(), executeQuery(), executeUpdate() @Pointcut("execution(* java.sql.PreparedStatement+.execute()) || " + "execution(* java.sql.PreparedStatement+.executeQuery()) || " + "execution(* java.sql.PreparedStatement+.executeUpdate())") public void executePreparedStatement() {} // execute(String sql)等、引数があるもの @Pointcut("execution(* java.sql.Statement+.execute(String)) || " + "execution(* java.sql.Statement+.execute(String, int)) || " + "execution(* java.sql.Statement+.execute(String, int[])) || " + "execution(* java.sql.Statement+.execute(String, String[])) || " + "execution(* java.sql.Statement+.executeQuery(String)) || " + "execution(* java.sql.Statement+.executeUpdate(String)) || " + "execution(* java.sql.Statement+.executeUpdate(String, int)) || " + "execution(* java.sql.Statement+.executeUpdate(String, int[])) || " + "execution(* java.sql.Statement+.executeUpdate(String, String[]))") public void executeStatement() {} @Pointcut("execution(void java.sql.Statement+.addBatch(String)) && args(sql)") public void addBatch(String sql) {} @Pointcut("execution(void java.sql.PreparedStatement+.addBatch())") public void addPreparedBatch() {} @Pointcut("execution(int[] java.sql.Statement+.executeBatch())") public void executeBatch() {} @Pointcut("execution(void java.sql.Statement+.close())") public void close() {} private LogModeMBean logMode = LogMode.getInstance(); /** * prepareStatementのログを複数回とらないようにチェックする */ private ThreadLocal<StatementLogger> prepareStatementMutex = new ThreadLocal<StatementLogger>(); @Around("prepareStatement()") public Object logPrepareStatement( ProceedingJoinPoint thisJoinPoint) throws Throwable { if (!this.logMode.getPrepareStatementLoggable() || this.prepareStatementMutex.get() != null) { return thisJoinPoint.proceed(); } Object[] args = thisJoinPoint.getArgs(); if (args == null || args.length == 0) { return thisJoinPoint.proceed(); } LogEntry entry = new LogEntry(LogType.PREPARE_STMT); try { this.prepareStatementMutex.set(this); entry.setSql((String) args[0]); // Connection#prepareStatement実行 PreparedStatement result = (PreparedStatement) AspectUtils.proceedAndReturn(entry, thisJoinPoint); PreparedStatementWrapper pstmt = new PreparedStatementWrapper(result, result.getConnection()); pstmt.setSql(entry.getSql()); entry.setStatement(pstmt); entry.setResult(Result.SUCCESS); return pstmt; } finally { LogWriter.put(entry); this.prepareStatementMutex.remove(); } } /** * executePreparedStatementのログを複数回とらないようにチェックする */ private ThreadLocal<StatementLogger> executePreparedStatementMutex = new ThreadLocal<StatementLogger>(); @Around("executePreparedStatement()") public Object logExecutePreparedStatement( ProceedingJoinPoint thisJoinPoint) throws Throwable { if (!this.logMode.getExecutePreparedStatementLoggable() || this.executePreparedStatementMutex.get() != null) { return thisJoinPoint.proceed(); } if ( !(thisJoinPoint.getTarget() instanceof PreparedStatementWrapper) || (thisJoinPoint.getArgs() != null && thisJoinPoint.getArgs().length > 0)) { return thisJoinPoint.proceed(); } LogEntry entry = new LogEntry(LogType.EXE_PSTMT); try { this.executePreparedStatementMutex.set(this); PreparedStatementWrapper pstmt = (PreparedStatementWrapper) thisJoinPoint.getTarget(); // パラメータを?に代入する entry.setSql( SqlUtils.replaceParameters( pstmt.getSql(), pstmt.getBoundParameters()) ); // PreparedStatement#execute*()実行 Object result = AspectUtils.proceedAndReturn(entry, thisJoinPoint); if (result instanceof Integer) { entry.setAffectedRows((Integer) result); } if (result instanceof Boolean && !((Boolean) result).booleanValue()) { // PreparedStatement#execute()がfalseの場合 entry.setAffectedRows(pstmt.getUpdateCount()); } entry.setResult(Result.SUCCESS); return result; } finally { LogWriter.put(entry); this.executePreparedStatementMutex.remove(); } } /** * executeStatementのログを複数回とらないようにチェックする */ private ThreadLocal<StatementLogger> executeStatementMutex = new ThreadLocal<StatementLogger>(); @Around("executeStatement()") public Object logExecuteStatement( ProceedingJoinPoint thisJoinPoint) throws Throwable { if (!this.logMode.getExecuteStatementLoggable() || this.executeStatementMutex.get() != null) { return thisJoinPoint.proceed(); } Object[] args = thisJoinPoint.getArgs(); if (args == null || args.length == 0) { return thisJoinPoint.proceed(); } LogEntry entry = new LogEntry(LogType.EXE_STMT); try { this.executeStatementMutex.set(this); entry.setSql((String) args[0]); return AspectUtils.proceedAndReturn(entry, thisJoinPoint); } finally { LogWriter.put(entry); this.executeStatementMutex.remove(); } } /** * addBatchのログを複数回とらないようにチェックする */ private ThreadLocal<StatementLogger> addBatchMutex = new ThreadLocal<StatementLogger>(); @Around("addBatch(String) && args(sql)") public Object logAddBatch( String sql, ProceedingJoinPoint thisJoinPoint) throws Throwable { if (!this.logMode.getAddBatchLoggable() || this.addBatchMutex.get() != null) { return thisJoinPoint.proceed(); } LogEntry entry = new LogEntry(LogType.ADD_BATCH); try { this.addBatchMutex.set(this); entry.setSql(sql); return AspectUtils.proceedAndReturn(entry, thisJoinPoint); } finally { LogWriter.put(entry); this.addBatchMutex.remove(); } } /** * addBatchのログを複数回とらないようにチェックする */ private ThreadLocal<StatementLogger> addPreparedBatchMutex = new ThreadLocal<StatementLogger>(); @Around("addPreparedBatch()") public Object logAddPreparedBatch(ProceedingJoinPoint thisJoinPoint) throws Throwable { if (!this.logMode.getAddBatchLoggable() || this.addBatchMutex.get() != null) { return thisJoinPoint.proceed(); } LogEntry entry = new LogEntry(LogType.ADD_BATCH); try { this.addPreparedBatchMutex.set(this); PreparedStatementWrapper pstmt = (PreparedStatementWrapper) thisJoinPoint.getTarget(); // パラメータを?に代入する entry.setSql( SqlUtils.replaceParameters( pstmt.getSql(), pstmt.getBoundParameters()) ); return AspectUtils.proceedAndReturn(entry, thisJoinPoint); } finally { LogWriter.put(entry); this.addPreparedBatchMutex.remove(); } } /** * executeBatchのログを複数回とらないようにチェックする */ private ThreadLocal<StatementLogger> executeBatchMutex = new ThreadLocal<StatementLogger>(); @Around("executeBatch()") public int[] logExecuteBatch( ProceedingJoinPoint thisJoinPoint) throws Throwable { if (!this.logMode.getExecuteBatchLoggable() || this.executeBatchMutex.get() != null) { return (int[]) thisJoinPoint.proceed(); } LogEntry entry = new LogEntry(LogType.EXE_BATCH); try { this.executeBatchMutex.set(this); int[] result = (int[]) AspectUtils.proceedAndReturn(entry, thisJoinPoint); int count = 0; for (int n : result) { if (n > 0) { count += n; } } entry.setAffectedRows(count); return result; } finally { LogWriter.put(entry); this.executeBatchMutex.remove(); } } /** * Statementクローズのログを複数回とらないようにチェックする */ private ThreadLocal<StatementLogger> closeStatementMutex = new ThreadLocal<StatementLogger>(); @Around("close()") public void logClose(ProceedingJoinPoint thisJoinPoint) throws Throwable { if (!this.logMode.getCloseStatementLoggable() || this.closeStatementMutex.get() != null) { thisJoinPoint.proceed(); return; } try { this.closeStatementMutex.set(this); AspectUtils.proceed(LogType.CLOSE_STMT, thisJoinPoint); } finally { this.closeStatementMutex.remove(); } } }
true
1c4b48a90ec654bff9e63a33bdfcfb4293222c50
Java
ronaldodornelles/gitflow
/source/src/br/gov/iphan/sisgep/webservices/test/ConsultaSIAPEWSTest.java
UTF-8
1,266
1.929688
2
[]
no_license
package br.gov.iphan.sisgep.webservices.test; import java.util.List; import org.junit.Test; import br.gov.iphan.sisgep.webservices.ConsultaSIAPEWS; import br.gov.iphan.sisgep.webservices.vo.ParametrosEntradaSIAPE; import br.gov.iphan.sisgep.ws.DadosPessoais; import br.gov.iphan.sisgep.ws.Uorg; public class ConsultaSIAPEWSTest { @Test public final void testListaUorgs() { try { ConsultaSIAPEWS consultaWS = new ConsultaSIAPEWS("https://www1.siapenet.gov.br/WSSiapenet/services/ConsultaSIAPE?wsdl"); ParametrosEntradaSIAPE parametros = new ParametrosEntradaSIAPE(); List<Uorg> uorgs = consultaWS.listaUorgs(parametros); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public final void testConsultaDadosPessoais() { try { ConsultaSIAPEWS consultaWS = new ConsultaSIAPEWS("https://www1.siapenet.gov.br/WSSiapenet/services/ConsultaSIAPE?wsdl"); ParametrosEntradaSIAPE parametros = new ParametrosEntradaSIAPE(); DadosPessoais dadosPessoais = consultaWS.consultaDadosPessoais(parametros); System.out.println(dadosPessoais.getNome().getValue()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
9ff40223e8b899c63285205cc588f1e850189142
Java
AmirGeorge/Micro
/src/eg/edu/guc/micro/ROBentry.java
UTF-8
339
1.632813
2
[]
no_license
package eg.edu.guc.micro; public class ROBentry { String dest; short value; boolean ready; String type; int instructionIndex; boolean free; boolean tailWa2f3alya; int khalstExecute; int index; public ROBentry() { free = true; dest = ""; ready = false; type = ""; instructionIndex = -1; tailWa2f3alya = false; } }
true
060ec36340a1f85f6e52ebd8b5ffe701debef27d
Java
Face-Sora/zzcl
/src/main/java/com/xinxi/controller/ApplyController.java
UTF-8
3,287
2
2
[]
no_license
package com.xinxi.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.xinxi.entity.Apply; import com.xinxi.entity.User; import com.xinxi.service.IApplyService; import com.xinxi.service.IUserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import com.xinxi.controller.BaseController; import javax.security.auth.Subject; import java.util.HashMap; import java.util.Map; /** * <p> * 前端控制器 * </p> * * @author jobob * @since 2020-09-11 */ @Controller @RequestMapping("/apply") public class ApplyController extends BaseController { @Autowired IApplyService iApplyService; @Autowired IUserService iUserService; @PostMapping("/save") @ResponseBody public Map<String,String> save(Integer needId){ System.out.println(needId); HashMap<String, String> map = new HashMap<>(); String phone = (String) SecurityUtils.getSubject().getPrincipal(); if (phone != null){ User user = iUserService.getOne(new QueryWrapper<User>().eq("phone", phone)); Long id = user.getId(); Apply apply = iApplyService.findByNeedIdAndApplicantId(needId, id); if (apply == null){ Apply apply2 = new Apply(); apply2.setApplicantId(id); apply2.setNeedId(needId); apply2.setApplicant(user); iApplyService.save(apply2); map.put("success","true"); return map; }else{ map.put("error","您已经申请过该项目,请勿重复申请!"); return map; } }else{ map.put("error","notLogin"); } System.out.println(map); return map; } @PostMapping("/cancel") @ResponseBody public String cancel(int needId){ String phone = (String) SecurityUtils.getSubject().getPrincipal(); User user = iUserService.getOne(new QueryWrapper<User>().eq("phone", phone)); Long id = user.getId(); HashMap<String, Object> map = new HashMap<>(); map.put("applicant_id",id); map.put("need_id",needId); iApplyService.removeByMap(map); return "ok"; } @PostMapping("/delete") @ResponseBody public String delete(int applyId){ QueryWrapper<Apply> applyQueryWrapper = new QueryWrapper<>(); applyQueryWrapper.eq("id",applyId); boolean remove = iApplyService.remove(applyQueryWrapper); if (remove) return "success"; else return "error"; } @GetMapping("/applyList") public String toApplyList(int pageNum, int pageSize, ModelMap modelMap){ Page applys = iApplyService.page(pageNum,pageSize); System.out.println(applys.getRecords()); modelMap.addAttribute("applys",applys); modelMap.addAttribute("pages",applys.getPages()); return "applys"; } }
true
f31efd6a6103907d920e79ef6e23140bf3ae8422
Java
rapopa/SimpleCacheSystem
/src/main/java/search/pojo/CacheableObject.java
UTF-8
859
2.828125
3
[]
no_license
package search.pojo; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by razvan.popa on 27-Dec-17. * @param <T> the object that is cached */ public class CacheableObject<T> { private LocalDateTime lastSearchDate = LocalDateTime.now(); private T object; public CacheableObject(T object) { this.object = object; } public List<T> getResult() { if (object instanceof Collection<?>) { return new ArrayList<T>((Collection<? extends T>) this.object); } List<T> result = new ArrayList<T>(); result.add(this.object); return result; } public LocalDateTime getLastSearchDate() { return lastSearchDate; } public void resetLastSearchDate() { this.lastSearchDate = LocalDateTime.now(); } public void setObject(T object) { this.object = object; } }
true
a12930aa4ac0cc4cde05acedf787d6f8e0d489c8
Java
ahellerjones/AdventureGame2.0
/LocalMapTest.java
UTF-8
5,395
2.9375
3
[]
no_license
package adventuregame; import java.util.ArrayList; import student.TestCase; public class LocalMapTest extends TestCase { ArrayList<MapObject> mapList; ArrayList<MapObject> mapListUP; LocalMap map; LocalMap mapUP; LocalMap mapRIGHT; LocalMap mapDOWN; LocalMap mapLEFT; String mapKey; String mapKey1; MapObject a; MapObject b; MapObject c; MapObject d; MapObject perm; public void setUp() { mapList = new ArrayList<>(); mapListUP = new ArrayList<>(); mapKey = "12"; mapKey1 = "02"; a = new MapObject('a', "Jim", false, 1, 1); b = new MapObject('b', "Jim", false, 2, 2); c = new MapObject('c', "Jim", false, 3, 3); d = new MapObject('d', "Jim", false, 0, 0); perm = new MapObject('p', "Jim", true, 0, 0); mapList.add(a); mapList.add(b); mapList.add(c); map = new LocalMap(mapKey, mapList); mapUP = new LocalMap("02", mapListUP); mapRIGHT = new LocalMap("13", mapListUP); mapDOWN = new LocalMap("22", mapListUP); mapLEFT = new LocalMap("11", mapListUP); } /** * Tests the char grid */ public void testCharGrid() { assertEquals('a', map.getCharGrid()[1][1]); assertEquals('b', map.getCharGrid()[2][2]); assertEquals('c', map.getCharGrid()[3][3]); } /** * Ensuring the remove method works properly */ public void testRemoveObjectAt() { assertTrue(map.removeObjectAt(3, 3)); assertEquals(0, map.getCharGrid()[3][3]); } /** * Ensuring that the method doesn't * do anything student when we remove * an entry that doesn't work. */ public void testRemoveWithNothingThere() { assertFalse(map.removeObjectAt(1, 3)); assertEquals(0, map.getCharGrid()[1][3]); } /** * tests the addObjectAt if the object is null */ public void testAddObjectAtNull() { assertFalse(map.addObjectAt(1, 0, null)); map.getCharGrid(); } /** * Tests adding where an entry already * exists * */ public void testAddSpaceFull() { assertFalse(map.addObjectAt(1, 1, b)); } /** * Test add normally */ public void testAddNormal() { assertEquals(0, map.getCharGrid()[0][0]); assertTrue(map.addObjectAt(0, 0, a)); assertEquals('a', map.getCharGrid()[0][0]); } /** * Tests the object's x,y coordinates after it gets moved * ensures that map.addObjectAt changes the object's actual x, y fields */ public void testCoordinates() { map.addObjectAt(3, 2, a); assertEquals(3, a.getX()); assertEquals(2, a.getY()); } /** * Test the moveObjectOnMap with a null */ public void testMoveObjectNull() { assertFalse(map.moveObjectOnMap(Direction.UP, null)); } /** * Tests the moveObjectOnMap with an object that's not on the map */ public void testMoveObjectNotOnMap() { map.removeObjectAt(2, 2); assertFalse(map.moveObjectOnMap(Direction.UP, b)); } /** * Tests moving up with a non permeable object * in the way */ public void testMovingUpWithSomethingInTheWay() { map.addObjectAt(1, 2, a); assertFalse(map.moveObjectOnMap(Direction.UP, b)); assertEquals('a', map.getObjectAt(1, 2).getMapIcon()); } /** * Tests moving up with a permeable object in the way */ public void testMovingUpWithPerm() { map.addObjectAt(1, 2, perm); assertTrue(map.moveObjectOnMap(Direction.UP, b)); assertEquals('b', map.getObjectAt(1, 2).getMapIcon()); } /** * Tests to see if the map reloads to the correct thing * when you move off of a permeable * object * */ public void testMovingOffOfPerm() { map.addObjectAt(1, 2, perm); assertTrue(map.moveObjectOnMap(Direction.UP, b)); assertEquals('b', map.getObjectAt(1, 2).getMapIcon()); assertTrue(map.moveObjectOnMap(Direction.RIGHT, b)); assertEquals('p', map.getObjectAt(1, 2).getMapIcon()); } /** * Tests the move function with nothing in the way */ public void testMovingNormal() { assertTrue(map.moveObjectOnMap(Direction.UP, b)); } /** * Tests changing maps when moving up */ public void testMovingUpAndChangingMaps() { map.addObjectAt(0, 0, d); map.moveObjectOnMap(Direction.UP, d); assertTrue(d.getMap().equals(mapUP)); } /** * tests moving the map to the right */ public void testMovingLeftChangeMap() { map.addObjectAt(0, 0, d); map.moveObjectOnMap(Direction.LEFT, d); assertTrue(d.getMap().equals(mapLEFT)); } /** * Tests moving the map to the right */ public void testMovingRightChangeMap() { map.addObjectAt(0, 4, d); map.moveObjectOnMap(Direction.RIGHT, d); assertTrue(d.getMap().equals(mapRIGHT)); } /** * Tests moving the map down */ public void testMovingDownChangeMap() { map.addObjectAt(4, 0, d); map.moveObjectOnMap(Direction.DOWN, d); assertTrue(d.getMap().equals(mapDOWN)); } }
true
3c987a4e70e075da0d324044d34a65de365a296b
Java
apandey3/omnipics
/src/main/java/org/amanda/api/AlbumResource.java
UTF-8
597
2.3125
2
[ "MIT" ]
permissive
package org.amanda.api; import org.amanda.Album; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; /** * @author Arti Sharma <arti.sharma@gmail.com> */ @Path("/v1/albums") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class AlbumResource { //TODO: Add a GET method to list albums public List<Album> getAlbums(){ List <Album> list = whatTodo(); return list; } private List<Album> whatTodo() { return null; } }
true
4b43b8fe78729e224f8cce1675bca871f6e2e6f2
Java
KanglaDevelopers/AppModule1
/app/src/main/java/com/kangladevelopers/appmodule1/fragment/HomeFragment.java
UTF-8
2,707
2.375
2
[]
no_license
package com.kangladevelopers.appmodule1.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.kangladevelopers.appmodule1.R; import com.sothree.slidinguppanel.SlidingUpPanelLayout; public class HomeFragment extends Fragment implements View.OnClickListener { // home fragment private SlidingUpPanelLayout slidingUpPanelLayout; private Button buttonShow; private Button buttonHide; private TextView title; private Toolbar toolbar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); slidingUpPanelLayout = (SlidingUpPanelLayout) view.findViewById(R.id.sliding_layout); toolbar = (Toolbar) view.findViewById(R.id.toolbar); AppCompatActivity compatActivity = (AppCompatActivity) getActivity(); compatActivity.setSupportActionBar(toolbar); buttonShow = (Button) view.findViewById(R.id.btn_show); buttonHide = (Button) view.findViewById(R.id.btn_hide); buttonShow.setOnClickListener(this); buttonHide.setOnClickListener(this); return view; } private SlidingPaneLayout.PanelSlideListener onPanelSlide(){ return new SlidingPaneLayout.PanelSlideListener() { @Override public void onPanelSlide(View panel, float slideOffset) { title.setText("panel is sliding"); } @Override public void onPanelOpened(View panel) { title.setText("panel is opening"); } @Override public void onPanelClosed(View panel) { title.setText("panel is closing"); } }; } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_show) { slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED); buttonShow.setVisibility(View.GONE); } else if (id == R.id.btn_hide) { slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN); buttonShow.setVisibility(View.VISIBLE); } } }
true
f2cbd05aff9a9f6859c0ccb461beb9ba190ef9d7
Java
phantomkk/dentalclinic_staff
/app/src/main/java/com/dentalclinic/capstone/admin/custom/DentistAxisValueFormatter.java
UTF-8
549
2.484375
2
[]
no_license
package com.dentalclinic.capstone.admin.custom; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import java.util.List; public class DentistAxisValueFormatter implements IAxisValueFormatter { private List<String> names; public DentistAxisValueFormatter(List<String> names) { this.names = names; } @Override public String getFormattedValue(float value, AxisBase axis) { int pos = (int) value; return names.get(pos); } }
true
3e5f972adf639efa5bd878b7e237f7e6b092a85a
Java
h-asmat/OrangeHelp
/app/src/main/java/missionhack/oranges/orangehelp/DisplayAlertActivity.java
UTF-8
2,024
2.265625
2
[]
no_license
package missionhack.oranges.orangehelp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class DisplayAlertActivity extends AppCompatActivity { private Alert alert = Alert.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_alert); TextView messageTextView = (TextView) findViewById(R.id.alertMessage); messageTextView.setText(alert.getAlertMessage()); setAlertIcon(); setAlertTitle(); Button viewMapButton = (Button) findViewById(R.id.viewmapbutton); viewMapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mapIntent = new Intent(DisplayAlertActivity.this, MapsActivity.class); startActivity(mapIntent); } }); } private void setAlertTitle() { TextView title = (TextView) findViewById(R.id.alertTitle); switch (alert.getOccupation()){ case Fireman: title.setText("FIRE"); break; case Doctor: title.setText("FIRST AID"); break; case Cop: title.setText("CONFLICT"); break; } } private void setAlertIcon() { ImageView image = (ImageView) findViewById(R.id.alertIcon); switch (alert.getOccupation()){ case Cop: image.setImageResource(R.mipmap.siren_l); break; case Doctor: image.setImageResource(R.mipmap.medical_l); break; case Fireman: image.setImageResource(R.mipmap.fire_l); break; } } }
true
7a37e45f4b79f48a9c48ad811c96bb7f5f70929e
Java
leuamrojas/GeoMusic
/app/src/main/java/com/manuelrojas/geomusic/data/repository/datasource/ArtistDataStore.java
UTF-8
459
2.015625
2
[]
no_license
package com.manuelrojas.geomusic.data.repository.datasource; import com.manuelrojas.geomusic.data.entity.ArtistEntity; import java.util.List; import io.reactivex.Completable; import io.reactivex.Observable; public interface ArtistDataStore { Observable<List<ArtistEntity>> findAll(); Observable<ArtistEntity> findById(String id); long save(ArtistEntity artist); void update(ArtistEntity artist); Completable deleteAllArtists(); }
true
d497e620c9b6c20ea21d7f756a78ddf6b19236de
Java
gmmapowell/QuickBuild
/QuickBuild/src/main/java/com/gmmapowell/quickbuild/build/android/AndroidNature.java
UTF-8
1,351
1.96875
2
[]
no_license
package com.gmmapowell.quickbuild.build.android; import org.zinutils.exceptions.UtilException; import com.gmmapowell.quickbuild.config.Config; import com.gmmapowell.quickbuild.config.ConfigFactory; import com.gmmapowell.quickbuild.core.BuildResource; import com.gmmapowell.quickbuild.core.Nature; public class AndroidNature implements Nature { public static void init(ConfigFactory config) { config.addCommandExtension("android", AndroidCommand.class); config.addCommandExtension("use", AndroidUseLibraryCommand.class); config.addCommandExtension("espresso", AndroidEspressoTestsCommand.class); config.addCommandExtension("exportJar", AndroidExportJarCommand.class); config.addCommandExtension("android-jar", AndroidJarCommand.class); config.addCommandExtension("adbinstall", AdbInstallCommand.class); config.addCommandExtension("adbstart", AdbStartCommand.class); config.addCommandExtension("adbinstrument", AdbInstrumentCommand.class); config.addCommandExtension("jniso", AndroidUseJNICommand.class); } public AndroidNature(Config cxt) { } @Override public void resourceAvailable(BuildResource br, boolean analyze) { throw new UtilException("Can't handle " + br); } public boolean isAvailable() { return true; } @Override public void done() { } @Override public void info(StringBuilder sb) { } }
true
d2619f3bb95557a51f085f5f6b6a6ade46cd5e62
Java
MrX456/Cars_Registry_System
/Car Registry System/src/com/CRS/Application/FrmLogin.java
UTF-8
10,166
2.421875
2
[]
no_license
/* * This JFrame is a login form, where user must to validate his credentials * before open the application */ package com.CRS.Application; import com.CRS.Controller.UserBusinessLogic; import com.CRS.Utils.CoolStuff; /* * Car Registry System / Application / Login Screen * @author MRX * Version : 1.0.0 */ public class FrmLogin extends javax.swing.JFrame { public FrmLogin() { initComponents(); // Custom icon for jar and Jframe this.setIconImage(CoolStuff.createIcon().getImage()); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); panColor = new javax.swing.JPanel(); lblLogin = new javax.swing.JLabel(); lblPassword = new javax.swing.JLabel(); txtLogin = new javax.swing.JTextField(); txtPassword = new javax.swing.JPasswordField(); btnLogin = new javax.swing.JButton(); lblLoginError = new javax.swing.JLabel(); lblExit = new javax.swing.JLabel(); jLabel1.setText("jLabel1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); panColor.setBackground(new java.awt.Color(255, 204, 204)); lblLogin.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblLogin.setText("Login :"); lblPassword.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblPassword.setText("Password :"); txtLogin.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N txtPassword.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N btnLogin.setText("Login"); btnLogin.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLoginActionPerformed(evt); } }); lblLoginError.setForeground(new java.awt.Color(255, 0, 51)); lblExit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N lblExit.setForeground(new java.awt.Color(255, 0, 51)); lblExit.setText("x"); lblExit.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblExit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblExitMouseClicked(evt); } }); javax.swing.GroupLayout panColorLayout = new javax.swing.GroupLayout(panColor); panColor.setLayout(panColorLayout); panColorLayout.setHorizontalGroup( panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panColorLayout.createSequentialGroup() .addGroup(panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panColorLayout.createSequentialGroup() .addGroup(panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panColorLayout.createSequentialGroup() .addGap(134, 134, 134) .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panColorLayout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblPassword) .addGroup(panColorLayout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(lblLogin))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE) .addComponent(txtLogin)))) .addGap(0, 46, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panColorLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(lblExit, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) .addGroup(panColorLayout.createSequentialGroup() .addGap(87, 87, 87) .addComponent(lblLoginError, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(88, Short.MAX_VALUE)) ); panColorLayout.setVerticalGroup( panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panColorLayout.createSequentialGroup() .addComponent(lblExit) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblLoginError, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblLogin) .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addGroup(panColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblPassword) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(btnLogin) .addGap(29, 29, 29)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panColor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panColor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); setSize(new java.awt.Dimension(340, 201)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed // Invoke login method(is not static because his Class implements a Interface) UserBusinessLogic user = new UserBusinessLogic(); user.login(txtLogin.getText(), txtPassword.getText()); //Dispose this JFrame this.dispose(); }//GEN-LAST:event_btnLoginActionPerformed private void lblExitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblExitMouseClicked //Close the application System.exit(0); }//GEN-LAST:event_lblExitMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmLogin().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnLogin; private javax.swing.JLabel jLabel1; private javax.swing.JLabel lblExit; private javax.swing.JLabel lblLogin; public static javax.swing.JLabel lblLoginError; private javax.swing.JLabel lblPassword; private javax.swing.JPanel panColor; private javax.swing.JTextField txtLogin; private javax.swing.JPasswordField txtPassword; // End of variables declaration//GEN-END:variables }
true
998230afa80a768eeed071a84d7e2460d5a21507
Java
LynLin0/Lyn
/src/lyn/android/media/TestPlayerPauseActivity.java
UTF-8
2,638
2.265625
2
[]
no_license
package lyn.android.media; import java.io.IOException; import lyn.android.R; import android.annotation.SuppressLint; import android.app.Activity; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; import android.net.rtp.AudioStream; import android.os.Bundle; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * @author Lyn lynlin@vanchu.net * @date 2015-8-19 * */ public class TestPlayerPauseActivity extends Activity implements OnPreparedListener{ private TextureView tv; private Button playBtn; private Button pauseBtn; private MediaPlayer mediaPlayer; private boolean isPrepareing = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_test_player_pause); findView(); setupView(); } private void setupView() { playBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer==null){ toPrepare(); }else{ if(!isPrepareing){ mediaPlayer.start(); } } } }); pauseBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(mediaPlayer!=null&&!isPrepareing&&mediaPlayer.isPlaying()){ mediaPlayer.pause(); } } }); } @SuppressLint("NewApi") private void toPrepare() { try { mediaPlayer = new MediaPlayer(); mediaPlayer.reset(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource("http://quniutest.qiniudn.com/s1/03ebabec24c14cce93d6386668a989f5.mp4"); mediaPlayer.setSurface(new Surface(tv.getSurfaceTexture())); mediaPlayer.setOnPreparedListener(this); mediaPlayer.prepareAsync(); isPrepareing = true; } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void findView() { tv = (TextureView)findViewById(R.id.test_playder_pause_textrueview); playBtn = (Button)findViewById(R.id.test_player_pause_play_btn); pauseBtn = (Button)findViewById(R.id.test_player_pause_pause_btn); } @Override public void onPrepared(MediaPlayer mp) { isPrepareing = false; mediaPlayer.start(); } }
true
a4d107d5104af6304309d92772fdc734af23fee3
Java
SecuritySistem/mingle
/app/src/main/java/com/provenlogic/mingle/Adapters/InterestListAdapter.java
UTF-8
2,763
2.296875
2
[]
no_license
package com.provenlogic.mingle.Adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.provenlogic.mingle.Models.InterestInfo; import com.provenlogic.mingle.R; import java.util.List; /** * Created by amal on 30/08/16. */ public class InterestListAdapter extends RecyclerView.Adapter<InterestListAdapter.MyViewHolder> { private List<InterestInfo> interestInfoList; private List<InterestInfo> full_interestInfoList; private Context mContext; public InterestListAdapter(List<InterestInfo> interestInfoList, List<InterestInfo> full_interestInfoList, Context mContext) { this.interestInfoList = interestInfoList; this.full_interestInfoList = full_interestInfoList; this.mContext = mContext; } @Override public InterestListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.interest_row, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(InterestListAdapter.MyViewHolder holder, int position) { final InterestInfo interestInfo = interestInfoList.get(position); if (interestInfo!=null) { holder.interest_name.setText(interestInfo.getInterestName()); if (interestInfo.isCommon()) { holder.interest_layout.setBackgroundResource(R.drawable.rounded_rectangle); }else holder.interest_layout.setBackgroundResource(R.drawable.border_stroke); }else { holder.interest_name.setText("\u2022 \u2022 \u2022"); holder.interest_layout.setBackgroundResource(R.drawable.rounded_rectangle); } holder.interest_layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (interestInfo==null){ interestInfoList = full_interestInfoList; notifyDataSetChanged(); } } }); } @Override public int getItemCount() { return interestInfoList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView interest_name; public LinearLayout interest_layout; public MyViewHolder(View view) { super(view); interest_name = (TextView) view.findViewById(R.id.interest_name); interest_layout = (LinearLayout) view.findViewById(R.id.interest_layout); } } }
true
51b687d80ff80879f5abd239a8cbc54ec8bafad1
Java
NineWorlds/serenity-android
/serenity-app/src/main/java/us/nineworlds/serenity/events/users/AuthenticatedUserEvent.java
UTF-8
349
2
2
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package us.nineworlds.serenity.events.users; import us.nineworlds.serenity.common.rest.SerenityUser; public class AuthenticatedUserEvent { private SerenityUser serenityUser; public AuthenticatedUserEvent(SerenityUser serenityUser) { this.serenityUser = serenityUser; } public SerenityUser getUser() { return serenityUser; } }
true
8f98ca2b52dc75c0f86093ea68d82850792b50ba
Java
wxjack/qxiao-mp
/src/main/java/com/qxiao/wx/user/jpa/dao/QmPlaySchoolInfoDao.java
UTF-8
2,803
1.867188
2
[]
no_license
package com.qxiao.wx.user.jpa.dao; import java.util.List; import org.springframework.data.jpa.repository.Query; import com.qxiao.wx.user.jpa.entity.QmPlaySchoolInfo; import com.spring.jpa.dao.JPADao; public interface QmPlaySchoolInfoDao extends JPADao<QmPlaySchoolInfo>{ QmPlaySchoolInfo findByTel(String tel); QmPlaySchoolInfo findByOpenId(String openId); QmPlaySchoolInfo findByleaderName(String leaderName); List<QmPlaySchoolInfo> findAll(); QmPlaySchoolInfo findBySchoolCode(String schoolCode); @Query(value = "SELECT qs.* FROM qm_play_school_info AS qs JOIN qm_play_school_class AS qsc " + "ON qs.school_id = qsc.school_id WHERE qsc.class_id = ?1 ",nativeQuery = true) QmPlaySchoolInfo findByClassId(Long classId); @Query(nativeQuery = true, value = "SELECT DISTINCT sch.* FROM qm_play_school_info AS sch " + "JOIN qm_play_school_class AS cla ON sch.school_id = cla.school_id " + "JOIN qm_class_teacher AS ct ON cla.class_id = ct.class_id " + "JOIN qm_play_school_teacher AS tea ON tea.teacher_id = ct.teacher_id " + "where tea.open_id = ?1 AND tea.status = 0 ") QmPlaySchoolInfo findWithTeacher(String openId); @Query(value = "SELECT sch.* FROM qm_play_school_info sch " + "JOIN qm_play_school_class cls ON sch.school_id = cls.school_id " + "JOIN qm_class_student qcs ON cls.class_id = qcs.class_id " + "WHERE qcs.student_id = ?1 ", nativeQuery = true) QmPlaySchoolInfo findByStudentId(Long studentId); @Query(value="SELECT qpsc.class_id FROM qm_play_school_info AS qpsi JOIN qm_play_school_class AS qpsc " + "WHERE qpsi.school_id = qpsc.school_id AND qpsi.open_id = ?1", nativeQuery = true) List<Long> findClassIdByOpenId(String openId); QmPlaySchoolInfo findBySchoolId(Long id); @Query(value = "SELECT a.* FROM qm_play_school_info AS a JOIN qm_notice_info AS b ON a.open_id = b.open_id WHERE b.notice_id = ?1", nativeQuery = true) QmPlaySchoolInfo findByNoticeId(Long noticeId); @Query(value="SELECT qpsi.school_id FROM qm_leader_init AS qli JOIN qm_play_school_info AS qpsi " + "where qli.tel=qpsi.tel and qli.terminal_school_id=?",nativeQuery=true) Long findByterminalSchoolId(Long schoolId); @Query(value="SELECT a.* FROM qm_play_school_info AS a JOIN qm_notice_info AS b " + "join qm_play_school_teacher as qpst where qpst.open_id=b.open_id and qpst.school_id=a.school_id " + "and b.notice_id=?",nativeQuery=true) QmPlaySchoolInfo queryByTeacherOpenId(Long noticeId); @Query(value="SELECT a.* FROM qm_play_school_info AS a JOIN qm_recipe_info AS b JOIN qm_play_school_teacher AS qpst " + "WHERE qpst.open_id = b.open_id AND qpst.school_id = a.school_id AND b.recipe_id =?",nativeQuery=true) QmPlaySchoolInfo queryByRecipe(Long recipeId); }
true
8718a183534462c6ace6f2436e7a732ac085cf9d
Java
das-fbk/ChatBotExample
/src/main/java/utils/BlaBlaCarAPIWrapper.java
UTF-8
3,166
2.515625
3
[]
no_license
package utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.text.DecimalFormat; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import java.util.Random; public class BlaBlaCarAPIWrapper { public ArrayList<TripAlternativeBlaBlaCar> getBlaBlaCarAlternatives(String partenza, String destinazione) { ArrayList<TripAlternativeBlaBlaCar> alternatives = new ArrayList<TripAlternativeBlaBlaCar>(); String result = callURL("https://public-api.blablacar.com/api/v2/trips?key=0954ba4c89b34ab7b73a2d727e91d7ff&fn="+partenza+"&tn="+destinazione+"&cur=EUR&_format=json"); if(result.equalsIgnoreCase("erroreAPI")){ return alternatives; }else{ JSONObject jsonObj = new JSONObject(result); JSONArray trips = new JSONArray(); trips = jsonObj.getJSONArray("trips"); Integer distance = jsonObj.getInt("distance"); Integer perfect_duration = jsonObj.getInt("duration"); Double recommended_price = jsonObj.getDouble("recommended_price"); for(int i = 0;i < trips.length(); i++){ JSONObject route = (JSONObject) trips.get(i); Integer seats_left = route.getInt("seats_left"); String id =route.getString("permanent_id"); String date =route.getString("departure_date").substring(0, 10); String hour =route.getString("departure_date").substring(11, 19); Double priceInd; if(route.has("price_with_commission")) { JSONObject price = route.getJSONObject("price_with_commission"); priceInd = price.getDouble("value"); }else { priceInd = 0.0; } String carmodel; if(route.has("car")) { JSONObject car = route.getJSONObject("car"); carmodel = car.getString("make").toLowerCase()+" "+car.getString("model").toLowerCase(); }else { carmodel = "null"; } if(seats_left > 0) { TripAlternativeBlaBlaCar alternative = new TripAlternativeBlaBlaCar(id, priceInd, seats_left, date, hour, carmodel, distance, perfect_duration, recommended_price); alternatives.add(alternative); } } } return alternatives; } public static String callURL(String myURL) { System.out.println(myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) urlConn.setReadTimeout(60 * 1000); if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { //throw {new RuntimeException("Exception while calling URL:"+ myURL, e); return "erroreAPI"; } return sb.toString(); } }
true
f67d02e1820711dd2dc82b0e89f3fc03de38641e
Java
iShymmi/Console-Weather-App
/src/main/java/com/shymmi/weatherApp/model/Forecast.java
UTF-8
954
3.03125
3
[]
no_license
package com.shymmi.weatherApp.model; import lombok.Getter; import static java.util.Arrays.stream; @Getter public class Forecast { private ForecastDay[] forecastday; @Override public String toString() { return getForecastInfo(false); } public String toString(boolean imperial) { if(!imperial) { return toString(); } return getForecastInfo(imperial); } private String getForecastInfo(boolean imperial) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("| Date | Temp min | Temp max | Sunrise | Sunset |"); stream(forecastday).forEach(forecastDay -> { stringBuilder.append("\n -----------------------------------------------------------------------"); stringBuilder.append("\n").append(forecastDay.toString(imperial)); }); return stringBuilder.toString(); } }
true
989e8577b87d72186ea83149450149d2044436c7
Java
way2rock00/RMSRetailApplication
/ApplicationController/src/com/deloitte/rmsapp/application/NativePushNotificationListener.java
UTF-8
3,156
2.546875
3
[]
no_license
package com.deloitte.rmsapp.application; import java.util.HashMap; import javax.el.ValueExpression; import oracle.adfmf.framework.api.AdfmfJavaUtilities; import oracle.adfmf.framework.api.JSONBeanSerializationHelper; import oracle.adfmf.framework.event.Event; import oracle.adfmf.framework.event.EventListener; import oracle.adfmf.framework.exception.AdfException; public class NativePushNotificationListener implements EventListener { public NativePushNotificationListener() { } public void onMessage(Event event) { String msg = event.getPayload(); System.out.println("#### Message from the Server :" + msg); // Parse the payload of the push notification HashMap payload = null; String pushMsg = "No message received"; try { payload = (HashMap)JSONBeanSerializationHelper.fromJSON(HashMap.class, msg); pushMsg = (String)payload.get("alert"); } catch(Exception e) { e.printStackTrace(); } // Write the push message to app scope to display to the user ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.pushMessage}", String.class); ve.setValue(AdfmfJavaUtilities.getAdfELContext(), pushMsg); AdfmfJavaUtilities.flushDataChangeEvent(); } public void onError(AdfException adfException) { System.out.println("#### Error: " + adfException.toString()); // Write the error into app scope ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.errorMessage}", String.class); ve.setValue(AdfmfJavaUtilities.getAdfELContext(), adfException.toString()); } public void onOpen(String token) { System.out.println("#### Registration token:" + token); String strDebug=""; // Clear error in app scope ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.errorMessage}", String.class); ve.setValue(AdfmfJavaUtilities.getAdfELContext(), null); strDebug = strDebug + "~1~"; // Write the token into app scope ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.deviceToken}", String.class); ve.setValue(AdfmfJavaUtilities.getAdfELContext(), token); strDebug = strDebug + "~2~"; String strTokenDebug = ""; strDebug = strDebug + "~3~"+token; if(token != null) { strDebug = strDebug + "~Not null~"; char[] array = token.toCharArray(); strTokenDebug = strTokenDebug + ":"+array.length+"\n"; for(int i =0 ; i< array.length ; i++) { int j = array[i]; strTokenDebug = strTokenDebug +":"+array[i]+"::"+j+"\n"; } } strDebug = strDebug + "~End~"; AdfmfJavaUtilities.setELValue("#{applicationScope.strDebug}", strDebug); AdfmfJavaUtilities.setELValue("#{applicationScope.strTokenDebug}", strTokenDebug); } }
true
4680be5fa4be120ed5f79c337cc5a8df9df7fcfb
Java
raviranjan1996/Java14
/CollectionsArrayList/src/application/ComparableExample.java
UTF-8
1,329
3.28125
3
[ "MIT" ]
permissive
package application; import java.util.ArrayList; import java.util.Collections; class PersonCompare implements Comparable<PersonCompare> { private String name; private Integer id; private Integer number; public PersonCompare(String name , int id , int number) { this.name = name; this.id = id; this.number = number; } public String toString() { return name + " , " + id +" , " + number; } @Override public int compareTo(PersonCompare o) { int comparision = name.compareTo(o.name); int ids = id.compareTo(o.id); if(ids ==0) { return number.compareTo(o.number); } if(comparision == 0) { return ids; } return comparision; } } public class ComparableExample { public static void main(String[] args) { var person = new ArrayList<PersonCompare>(); person.add(new PersonCompare("ravi", 23 , 1)); person.add(new PersonCompare("patel", 24 , 4)); person.add(new PersonCompare("dabloo", 26 , 3)); person.add(new PersonCompare("kumar", 27 ,7)); person.add(new PersonCompare("ravi", 20 ,2)); person.add(new PersonCompare("patel", 24 ,3)); person.add(new PersonCompare("dabloo", 10 ,4)); Collections.sort(person); person.forEach(e->System.out.println(e)); String name = "ravi@gmail.com"; } }
true
d7cdf7d924a4e3cdcf8fd7019e53d4ad9066c256
Java
marlontaro/Nanamia
/AppApoderado/app/src/main/java/pe/edu/upc/appapoderado/models/Solicitud.java
UTF-8
2,035
2.203125
2
[]
no_license
package pe.edu.upc.appapoderado.models; /** * Created by Marlon Cordova on 3/05/2017. */ public class Solicitud { private int tipoContrato; private boolean PrimerosAuxilio ; private boolean CuidadoEspecial; private double SueldoMinimo ; private double SueldoMaximo ; private String Direccion ; private String Longitud; private String Latitud; private int IdNana ; private String Token; public int getTipoContrato() { return tipoContrato; } public void setTipoContrato(int tipoContrato) { this.tipoContrato = tipoContrato; } public boolean isPrimerosAuxilio() { return PrimerosAuxilio; } public void setPrimerosAuxilio(boolean primerosAuxilio) { PrimerosAuxilio = primerosAuxilio; } public boolean isCuidadoEspecial() { return CuidadoEspecial; } public void setCuidadoEspecial(boolean cuidadoEspecial) { CuidadoEspecial = cuidadoEspecial; } public double getSueldoMinimo() { return SueldoMinimo; } public void setSueldoMinimo(double sueldoMinimo) { SueldoMinimo = sueldoMinimo; } public double getSueldoMaximo() { return SueldoMaximo; } public void setSueldoMaximo(double sueldoMaximo) { SueldoMaximo = sueldoMaximo; } public String getDireccion() { return Direccion; } public void setDireccion(String direccion) { Direccion = direccion; } public String getLongitud() { return Longitud; } public void setLongitud(String longitud) { Longitud = longitud; } public String getLatitud() { return Latitud; } public void setLatitud(String latitud) { Latitud = latitud; } public int getIdNana() { return IdNana; } public void setIdNana(int idNana) { IdNana = idNana; } public String getToken() { return Token; } public void setToken(String token) { Token = token; } }
true
1bf096e540b1cea786f757843e39c1955201644c
Java
brisskit-uol/onyx-core-1.8.1-appts-list-fix
/src/main/java/org/obiba/onyx/core/purge/PurgeParticipantDataTasklet.java
UTF-8
3,092
1.984375
2
[]
no_license
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.onyx.core.purge; import java.util.List; import org.obiba.onyx.core.domain.participant.Participant; import org.obiba.onyx.core.service.ParticipantService; import org.obiba.onyx.core.service.PurgeParticipantDataService; import org.obiba.onyx.engine.variable.export.OnyxDataPurge; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; /** * The goal of this Tasklet is to remove the Participant data which is no longer relevant to Onyx in order to protect * the confidentiality of the Participants. * * Rules governing which Participants are to be purged can be found in purge.xml. */ public class PurgeParticipantDataTasklet implements Tasklet { private static final Logger log = LoggerFactory.getLogger(PurgeParticipantDataTasklet.class); private ParticipantService participantService; private PurgeParticipantDataService purgeParticipantDataService; private OnyxDataPurge onyxDataPurge; public RepeatStatus execute(StepContribution stepContribution, ChunkContext context) { log.info("**** STARTING PARTICIPANT DATA PURGE ****"); log.info("Current purge configuration is [{}] days", purgeParticipantDataService.getPurgeDataOlderThanInDays()); long start = System.currentTimeMillis(); List<Participant> participantsToBePurged = onyxDataPurge.getParticipantsToPurge(); for(Participant participant : participantsToBePurged) { participantService.deleteParticipant(participant); log.info("Deleting Participant id = [{}] and related data : ", participant.getId()); } context.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("totalDeleted", participantsToBePurged.size()); long end = System.currentTimeMillis(); log.info("A total of [{}] Participants were deleted in [{}] ms.", participantsToBePurged.size(), end - start); log.info("**** PARTICIPANT DATA PURGE COMPLETED ****"); return RepeatStatus.FINISHED; } public void setParticipantService(ParticipantService participantService) { this.participantService = participantService; } public void setPurgeParticipantDataService(PurgeParticipantDataService purgeParticipantDataService) { this.purgeParticipantDataService = purgeParticipantDataService; } public void setOnyxDataPurge(OnyxDataPurge onyxDataPurge) { this.onyxDataPurge = onyxDataPurge; } }
true
e26a1809c4b9db5f1f17704d0f09ec2fd47f340f
Java
Meijo-RJIE-Prog4/Exercises
/4/Exercise0402.java
UTF-8
217
1.945313
2
[]
no_license
public class Exercise0402 { public static void main(String[] args) { // 勇者を生成 // 勇者を逃がす // スーパー勇者を生成 // スーパー勇者を逃がす } }
true
a4e898065b88c6449654cf1afeb727d28053bcb8
Java
ifunsoftware/4store-java-client
/src/main/java/uk/co/magus/fourstore/client/EncodedStringWriter.java
UTF-8
792
2.890625
3
[]
no_license
package uk.co.magus.fourstore.client; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.net.URLEncoder; import java.util.Arrays; public class EncodedStringWriter extends Writer { private final OutputStream os; public EncodedStringWriter(OutputStream os) { this.os = os; } @Override public void write(char[] chars, int i, int i1) throws IOException { String string = new String(Arrays.copyOfRange(chars, i, i1)); String encoded = URLEncoder.encode(string, "UTF-8"); os.write(encoded.getBytes("UTF-8")); } @Override public void flush() throws IOException { os.flush(); } @Override public void close() throws IOException { os.close(); } }
true
8b19ce0213fd5bbab25bac2d6ad8f02e9550e4ed
Java
ScratchMyTail/SpringHibernatePersonAnimalWebApp
/src/main/java/no/hinesna/PersonDao.java
UTF-8
297
1.90625
2
[]
no_license
package no.hinesna; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PersonDao { public void savePerson(Person person); public List<Person> getAll(); public void saveHusdyr(Husdyr husdyr); public Person getPerson(int id); }
true
c4cb7429777a407f03252150d1d3ab392f0d20df
Java
BiswajitSahu007/TY_CG_HTD_BangaloreNovember_JFS_BiswajitSahu
/CoreJava/typecasting/pack2/Dog.java
UTF-8
194
2.890625
3
[]
no_license
package com.tyss.typecasting.pack2; public class Dog extends Animal { void eating() { System.out.println("Dog is eating"); } void walking() { System.out.println("Dog is walking"); } }
true
824640987b2f7859d53c5dd2f4605cd1094e448c
Java
NFC3/customer-review-exercise
/CustomerReview_Exercise/customerreviewserver.jar.src/de/hybris/platform/customerreview/exception/CurseWordsFoundException.java
UTF-8
266
1.859375
2
[]
no_license
package de.hybris.platform.customerreview.exception; public class CurseWordsFoundException extends Exception { private static final long serialVersionUID = -4115212430246439148L; public CurseWordsFoundException(String message) { super(message); } }
true
eb1a897d706929ba00681a8c6de1b2a6c7997f56
Java
leilei1144/customized-framework
/customized-common/src/main/java/com/customized/support/dubbo/spring/schema/CustomizedNamespaceHandler.java
UTF-8
580
1.9375
2
[]
no_license
package com.customized.support.dubbo.spring.schema; import com.alibaba.dubbo.config.spring.schema.DubboBeanDefinitionParser; import com.alibaba.dubbo.config.spring.schema.DubboNamespaceHandler; import com.customized.support.dubbo.spring.AnnotationBean; /** * @author gu * @version 2016年5月20日 下午3:19:19 */ public class CustomizedNamespaceHandler extends DubboNamespaceHandler { public void init() { super.init(); System.out.println("进入handler"); registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true)); } }
true
47444d274bb4fcee21e76d98d331dfe6893c39f7
Java
FortuneDream/gradle_plugin_android_aspectjx
/aspectjx/src/main/java/org/aspectj/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
UTF-8
15,935
1.695313
2
[ "Apache-2.0" ]
permissive
// AspectJ Extension /******************************************************************************* * Copyright (c) 2000, 2018 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation * Stephan Herrmann - Contribution for * Bug 440477 - [null] Infrastructure for feeding external annotations into compilation * Bug 440687 - [compiler][batch][null] improve command line option for external annotations *******************************************************************************/ package org.aspectj.org.eclipse.jdt.internal.compiler.batch; // this file has a number of changes made by ASC to prevent us from // leaking OS resources by keeping jars open longer than needed. import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem.Classpath; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ExternalAnnotationDecorator; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ExternalAnnotationProvider; import org.aspectj.org.eclipse.jdt.internal.compiler.env.AccessRuleSet; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IModule; import org.aspectj.org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.ExternalAnnotationStatus; import org.aspectj.org.eclipse.jdt.internal.compiler.util.ManifestAnalyzer; import org.aspectj.org.eclipse.jdt.internal.compiler.util.SuffixConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.util.Util; @SuppressWarnings({"rawtypes", "unchecked"}) public class ClasspathJar extends ClasspathLocation { // AspectJ Extension /** * ASC 23112004 * These fields and related logic throughout the class enable us to cope with very long * classpaths. Normally all the archives on the classpath were openede and left open * for the duration of a compile - this doesn't scale since you will start running out * of file handles when you have extremely long classpaths (e.g. 4000 jars). These * fields enable us to keep track of how many are currently open and if you attempt to * open more than some defined limit, it will close some that you haven't used for a * while before opening the new one. The limit is tailorable through the * org.aspectj.weaver.openarchives * system property, the default is 1000 which means most users will never exercise * this logic. The only change outside of this class related to this feature is that * the FileSystem class now constructs a ClasspathJar object by passing in a File * rather than a ZipFile - it is then the responsibility of this class to * open and manage the ZipFile. */ private static int maxOpenArchives = 1000; private final static int MAXOPEN_DEFAULT = 1000; private static List openArchives = new ArrayList(); // End AspectJ Extension protected File file; protected ZipFile zipFile; protected ZipFile annotationZipFile; protected boolean closeZipFileAtEnd; protected Set<String> packageCache; protected List<String> annotationPaths; // AspectJ Extension static { String openarchivesString = getSystemPropertyWithoutSecurityException("org.aspectj.weaver.openarchives",Integer.toString(MAXOPEN_DEFAULT)); maxOpenArchives=Integer.parseInt(openarchivesString); if (maxOpenArchives<20) maxOpenArchives=1000; } // End AspectJ Extension public ClasspathJar(File file, boolean closeZipFileAtEnd, AccessRuleSet accessRuleSet, String destinationPath) { super(accessRuleSet, destinationPath); this.file = file; this.closeZipFileAtEnd = closeZipFileAtEnd; } @Override public List<Classpath> fetchLinkedJars(FileSystem.ClasspathSectionProblemReporter problemReporter) { // expected to be called once only - if multiple calls desired, consider // using a cache InputStream inputStream = null; try { initialize(); ArrayList<Classpath> result = new ArrayList<>(); ZipEntry manifest = this.zipFile.getEntry(TypeConstants.META_INF_MANIFEST_MF); if (manifest != null) { // non-null implies regular file inputStream = this.zipFile.getInputStream(manifest); ManifestAnalyzer analyzer = new ManifestAnalyzer(); boolean success = analyzer.analyzeManifestContents(inputStream); List calledFileNames = analyzer.getCalledFileNames(); if (problemReporter != null) { if (!success || analyzer.getClasspathSectionsCount() == 1 && calledFileNames == null) { problemReporter.invalidClasspathSection(getPath()); } else if (analyzer.getClasspathSectionsCount() > 1) { problemReporter.multipleClasspathSections(getPath()); } } if (calledFileNames != null) { Iterator calledFilesIterator = calledFileNames.iterator(); String directoryPath = getPath(); int lastSeparator = directoryPath.lastIndexOf(File.separatorChar); directoryPath = directoryPath.substring(0, lastSeparator + 1); // potentially empty (see bug 214731) while (calledFilesIterator.hasNext()) { result.add(new ClasspathJar(new File(directoryPath + (String) calledFilesIterator.next()), this.closeZipFileAtEnd, this.accessRuleSet, this.destinationPath)); } } } return result; } catch (IOException | IllegalArgumentException e) { // JRE 9 could throw an IAE if the path is incorrect. We are to ignore such // linked jars return null; } finally { if (inputStream != null) { try { inputStream.close(); close(); // AspectJ extension - close it (tidyup on windows) } catch (IOException e) { // best effort } } } } @Override public NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String moduleName, String qualifiedBinaryFileName) { return findClass(typeName, qualifiedPackageName, moduleName, qualifiedBinaryFileName, false); } @Override public NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String moduleName, String qualifiedBinaryFileName, boolean asBinaryOnly) { if (!isPackage(qualifiedPackageName, moduleName)) return null; // most common case try { ensureOpen(); // AspectJ Extension IBinaryType reader = ClassFileReader.read(this.zipFile, qualifiedBinaryFileName); if (reader != null) { char[] modName = this.module == null ? null : this.module.name(); if (reader instanceof ClassFileReader) { ClassFileReader classReader = (ClassFileReader) reader; if (classReader.moduleName == null) classReader.moduleName = modName; else modName = classReader.moduleName; } searchPaths: if (this.annotationPaths != null) { String qualifiedClassName = qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length()-SuffixConstants.EXTENSION_CLASS.length()-1); for (String annotationPath : this.annotationPaths) { try { if (this.annotationZipFile == null) { this.annotationZipFile = ExternalAnnotationDecorator.getAnnotationZipFile(annotationPath, null); } reader = ExternalAnnotationDecorator.create(reader, annotationPath, qualifiedClassName, this.annotationZipFile); if (reader.getExternalAnnotationStatus() == ExternalAnnotationStatus.TYPE_IS_ANNOTATED) { break searchPaths; } } catch (IOException e) { // don't let error on annotations fail class reading } } // location is configured for external annotations, but no .eea found, decorate in order to answer NO_EEA_FILE: reader = new ExternalAnnotationDecorator(reader, null); } return new NameEnvironmentAnswer(reader, fetchAccessRestriction(qualifiedBinaryFileName), modName); } } catch (ClassFormatException | IOException e) { // treat as if class file is missing } return null; } @Override public boolean hasAnnotationFileFor(String qualifiedTypeName) { return this.zipFile.getEntry(qualifiedTypeName+ExternalAnnotationProvider.ANNOTATION_FILE_SUFFIX) != null; } @Override public char[][][] findTypeNames(final String qualifiedPackageName, String moduleName) { if (!isPackage(qualifiedPackageName, moduleName)) return null; // most common case final char[] packageArray = qualifiedPackageName.toCharArray(); final ArrayList answers = new ArrayList(); // AspectJ Extension try { ensureOpen(); } catch (IOException ioe) { // Doesn't normally occur - probably means since starting the compile // you have removed one of the jars. ioe.printStackTrace(); return null; } // End AspectJ Extension nextEntry : for (Enumeration e = this.zipFile.entries(); e.hasMoreElements(); ) { String fileName = ((ZipEntry) e.nextElement()).getName(); // add the package name & all of its parent packages int last = fileName.lastIndexOf('/'); if (last > 0) { // extract the package name String packageName = fileName.substring(0, last); if (!qualifiedPackageName.equals(packageName)) continue nextEntry; int indexOfDot = fileName.lastIndexOf('.'); if (indexOfDot != -1) { String typeName = fileName.substring(last + 1, indexOfDot); answers.add( CharOperation.arrayConcat( CharOperation.splitOn('/', packageArray), typeName.toCharArray())); } } } int size = answers.size(); if (size != 0) { char[][][] result = new char[size][][]; answers.toArray(result); return result; } return null; } @Override public void initialize() throws IOException { ensureOpen(); // AspectJ - start - replace next bit with above if (this.zipFile == null) { this.zipFile = new ZipFile(this.file); } // AspectJ - end } void acceptModule(ClassFileReader reader) { if (reader != null) { acceptModule(reader.getModuleDeclaration()); } } void acceptModule(byte[] content) { if (content == null) return; ClassFileReader reader = null; try { reader = new ClassFileReader(content, IModule.MODULE_INFO_CLASS.toCharArray()); } catch (ClassFormatException e) { e.printStackTrace(); } if (reader != null && reader.getModuleDeclaration() != null) { acceptModule(reader); } } protected void addToPackageCache(String fileName, boolean endsWithSep) { int last = endsWithSep ? fileName.length() : fileName.lastIndexOf('/'); while (last > 0) { // extract the package name String packageName = fileName.substring(0, last); if (this.packageCache.contains(packageName)) return; this.packageCache.add(packageName); last = packageName.lastIndexOf('/'); } } @Override public synchronized char[][] getModulesDeclaringPackage(String qualifiedPackageName, String moduleName) { if (this.packageCache != null) return singletonModuleNameIf(this.packageCache.contains(qualifiedPackageName)); // AspectJ Extension try { ensureOpen(); } catch (IOException ioe) { // Doesn't normally occur - probably means since starting the compile // you have removed one of the jars. ioe.printStackTrace(); return singletonModuleNameIf(false); } // End AspectJ Extension this.packageCache = new HashSet<>(41); this.packageCache.add(Util.EMPTY_STRING); for (Enumeration e = this.zipFile.entries(); e.hasMoreElements(); ) { String fileName = ((ZipEntry) e.nextElement()).getName(); addToPackageCache(fileName, false); } return singletonModuleNameIf(this.packageCache.contains(qualifiedPackageName)); } @Override public boolean hasCompilationUnit(String qualifiedPackageName, String moduleName) { qualifiedPackageName += '/'; for (Enumeration<? extends ZipEntry> e = this.zipFile.entries(); e.hasMoreElements(); ) { String fileName = e.nextElement().getName(); if (fileName.startsWith(qualifiedPackageName) && fileName.length() > qualifiedPackageName.length()) { String tail = fileName.substring(qualifiedPackageName.length()); if (tail.indexOf('/') != -1) continue; if (tail.toLowerCase().endsWith(SUFFIX_STRING_class)) return true; } } return false; } @Override public char[][] listPackages() { Set<String> packageNames = new HashSet<>(); for (Enumeration<? extends ZipEntry> e = this.zipFile.entries(); e.hasMoreElements(); ) { String fileName = e.nextElement().getName(); int lastSlash = fileName.lastIndexOf('/'); if (lastSlash != -1 && fileName.toLowerCase().endsWith(SUFFIX_STRING_class)) packageNames.add(fileName.substring(0, lastSlash).replace('/', '.')); } return packageNames.stream().map(String::toCharArray).toArray(char[][]::new); } @Override public void reset() { super.reset(); if (this.closeZipFileAtEnd) { if (this.zipFile != null) { // AspectJ Extension // old code: //try { // this.zipFile.close(); // AspectJ Extension - dont do this //} catch(IOException e) { // // ignore //} //this.zipFile = null; // new code: close(); } // End AspectJ Extension if (this.annotationZipFile != null) { try { this.annotationZipFile.close(); } catch(IOException e) { // ignore } this.annotationZipFile = null; } } this.packageCache = null; this.annotationPaths = null; } @Override public String toString() { return "Classpath for jar file " + this.file.getPath(); //$NON-NLS-1$ } @Override public char[] normalizedPath() { if (this.normalizedPath == null) { String path2 = this.getPath(); char[] rawName = path2.toCharArray(); if (File.separatorChar == '\\') { CharOperation.replace(rawName, '\\', '/'); } this.normalizedPath = CharOperation.subarray(rawName, 0, CharOperation.lastIndexOf('.', rawName)); } return this.normalizedPath; } @Override public String getPath() { if (this.path == null) { try { this.path = this.file.getCanonicalPath(); } catch (IOException e) { // in case of error, simply return the absolute path this.path = this.file.getAbsolutePath(); } } return this.path; } @Override public int getMode() { return BINARY; } @Override public IModule getModule() { return this.module; } // AspectJ Extension private void ensureOpen() throws IOException { if (zipFile != null) return; // If its not null, the zip is already open // if (openArchives.size()>=maxOpenArchives) { // closeSomeArchives(openArchives.size()/10); // Close 10% of those open // } zipFile = new ZipFile(file); // openArchives.add(this); } private void closeSomeArchives(int n) { for (int i=n-1;i>=0;i--) { ClasspathJar zf = (ClasspathJar)openArchives.get(0); zf.close(); } } public void close() { if (zipFile == null) return; try { // openArchives.remove(this); // zipFile.close(); // } catch (IOException ioe) { // ioe.printStackTrace(); } finally { zipFile = null; } } // Copes with the security manager private static String getSystemPropertyWithoutSecurityException (String aPropertyName, String aDefaultValue) { try { return System.getProperty(aPropertyName, aDefaultValue); } catch (SecurityException ex) { return aDefaultValue; } } // End AspectJ Extension }
true
32aefc26947b6dc63b35d0f3c83fefa352ca2924
Java
patricklaux/xcache
/xcache-common/src/main/java/com/igeeksky/xcache/AbstractCache.java
UTF-8
1,445
2.6875
3
[]
no_license
package com.igeeksky.xcache; /** * @author Patrick.Lau * @since 0.0.4 2021-09-19 */ public abstract class AbstractCache<K, V> implements Cache<K, V> { private final String name; private final Class<K> keyType; private final Class<V> valueType; private final Object lock = new Object(); private volatile SyncCache<K, V> syncCache; private volatile AsyncCache<K, V> asyncCache; public AbstractCache(String name, Class<K> keyType, Class<V> valueType) { this.name = name; this.keyType = keyType; this.valueType = valueType; } @Override public String getName() { return name; } @Override public Class<K> getKeyType() { return keyType; } @Override public Class<V> getValueType() { return valueType; } @Override public SyncCache<K, V> sync() { if (null == syncCache) { synchronized (lock) { if (null == syncCache) { this.syncCache = new SyncCache.SyncCacheView<>(this); } } } return syncCache; } @Override public AsyncCache<K, V> async() { if (null == asyncCache) { synchronized (lock) { if (null == asyncCache) { this.asyncCache = new AsyncCache.AsyncCacheView<>(this); } } } return asyncCache; } }
true
4ca1a82fe4319b102ee5e20ff4493543263519b4
Java
kaydoh/geowave
/extensions/adapters/raster/src/main/java/org/locationtech/geowave/adapter/raster/stats/RasterStatisticQueryBuilder.java
UTF-8
2,635
1.851563
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2013-2022 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.adapter.raster.stats; import java.util.Map; import javax.media.jai.Histogram; import org.locationtech.geowave.adapter.raster.Resolution; import org.locationtech.geowave.adapter.raster.stats.RasterBoundingBoxStatistic.RasterBoundingBoxValue; import org.locationtech.geowave.adapter.raster.stats.RasterFootprintStatistic.RasterFootprintValue; import org.locationtech.geowave.adapter.raster.stats.RasterHistogramStatistic.RasterHistogramValue; import org.locationtech.geowave.adapter.raster.stats.RasterOverviewStatistic.RasterOverviewValue; import org.locationtech.geowave.core.store.api.StatisticQueryBuilder; import org.locationtech.geowave.core.store.statistics.query.DataTypeStatisticQueryBuilder; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; public interface RasterStatisticQueryBuilder { /** * Create a new data type statistic query builder for a raster bounding box statistic. * * @return the data type statistic query builder */ static DataTypeStatisticQueryBuilder<RasterBoundingBoxValue, Envelope> bbox() { return StatisticQueryBuilder.newBuilder(RasterBoundingBoxStatistic.STATS_TYPE); } /** * Create a new data type statistic query builder for a raster footprint statistic. * * @return the data type statistic query builder */ static DataTypeStatisticQueryBuilder<RasterFootprintValue, Geometry> footprint() { return StatisticQueryBuilder.newBuilder(RasterFootprintStatistic.STATS_TYPE); } /** * Create a new data type statistic query builder for a raster histogram statistic. * * @return the data type statistic query builder */ static DataTypeStatisticQueryBuilder<RasterHistogramValue, Map<Resolution, Histogram>> histogram() { return StatisticQueryBuilder.newBuilder(RasterHistogramStatistic.STATS_TYPE); } /** * Create a new data type statistic query builder for a raster overview statistic. * * @return the data type statistic query builder */ static DataTypeStatisticQueryBuilder<RasterOverviewValue, Resolution[]> overview() { return StatisticQueryBuilder.newBuilder(RasterOverviewStatistic.STATS_TYPE); } }
true
8127b7f47cc0b787cd0b1654936b774012c12c74
Java
PayalKhattri/Login
/app/src/main/java/com/example/login/blogpost.java
UTF-8
965
2.296875
2
[]
no_license
package com.example.login; import java.util.Date; public class blogpost extends BlogPostId{ public String id; public String image; public String desc; public Date timestamp; public blogpost(){ } public blogpost(String id, String image, String desc,Date timestamp) { this.id = id; this.image = image; this.desc = desc; this.timestamp = timestamp; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } }
true
71ad4c31966b238095445a2e9a024ef02eaf5b7b
Java
MrRmk/DesignPatterns
/src/main/java/com/example/chainofresponsibility/Main.java
UTF-8
2,300
3.28125
3
[]
no_license
package com.example.chainofresponsibility; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Msg msg = new Msg(); msg.setMsg("大家好:),<script> 欢迎访问 www.xxx.com ,大家都是996 "); FilterChain fc = new FilterChain(); fc.add(new HTMLFilter()) .add(new SensitiveFilter()); FilterChain fc2 = new FilterChain(); fc2.add(new FaceFilter()) .add(new URLFilter()); fc.add(fc2); //处理msg // new HTMLFilter().doFilter(msg); // new SensitiveFilter().doFilter(msg); System.out.println(msg); } } class Msg{ String name; String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return "Msg{" + "name='" + name + '\'' + ", msg='" + msg + '\'' + '}'; } } interface Filter { boolean doFilter(Msg msg); } class HTMLFilter implements Filter{ public boolean doFilter(Msg msg) { String r = msg.getMsg(); r = r.replace('<', '['); r = r.replace('>', ']'); msg.setMsg(r); return true; } } class SensitiveFilter implements Filter{ public boolean doFilter(Msg msg) { String r = msg.getMsg(); r = r.replaceAll("996", "955"); msg.setMsg(r); return false; } } class FaceFilter implements Filter{ public boolean doFilter(Msg msg) { String r = msg.getMsg(); r = r.replace(":)", "^V^"); msg.setMsg(r); return true; } } class URLFilter implements Filter{ public boolean doFilter(Msg msg) { String r = msg.getMsg(); r = r.replace("www.xxx.com", "http://www.xxx.com"); msg.setMsg(r); return true; } } class FilterChain implements Filter{ List<Filter> filters = new ArrayList<>(); public FilterChain add(Filter f){ filters.add(f); return this; } public boolean doFilter(Msg m){ for (Filter f:filters ) { if(!f.doFilter(m)) return false; } return true; } }
true
1f28f237b5ca96f712a5f061f3269ecb1fe32609
Java
FadilX/ProjetJava
/civilization/src/civilization/Attaque.java
ISO-8859-1
1,582
3.3125
3
[]
no_license
package civilization; import java.util.Scanner; /** * * @author Fadil *Voil la tant attendue phase attaque dffense *On laissera le choix au joueur: payer ou se battre */ public class Attaque { int vague; Time temps=new Time(); Ressources ressources=new Ressources(); public Attaque(){ vague=0; } public int getVague(){ return vague; } public void setVague(int vague){ this.vague=vague; } public void clash(People people){ System.err.println("TOUOOOOOOOO, TOUTUOUTOUTOUTROUROUROU (corne de guerre :/"); System.out.println("En avant!! SUs l'ennemi!"); if(people.getWarrior()<=5){ System.err.println("Vous avez perdu la guerre"); } else{ System.err.println(" Vous avez terras l'ennemi ! Vous tes venez bout de la "+getVague()+" Vague"); } } public void go(People people){ Scanner sc = new Scanner(System.in); while(temps.seconde<=10){ // wait... } System.err.println("Etrangers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + " Votre ville est encercle, payez 400 Or, ou subbissez notre COUROU!"); System.err.println("tapez 1 pour payer, 0 sinon"); int a=sc.nextInt(); if(a==1) { if(ressources.getgold()>=400){ ressources.setgold(-400); System.err.println("Trs bien vous vivrez pour cette fois..."); } else{ System.err.println("Vous n'avez pas assez d'or, vous tes contraint d'attaquer... Brace Yourself"); // fonction attaque clash(people); } } else{ clash(people); } } }
true
4fb4c9fdb367176791699598c17b372515226d5a
Java
07jeancms/Admision_Diseno
/src/negocio/AdministradorInt.java
UTF-8
2,520
2.296875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package negocio; import javax.swing.JFrame; import negocio.GestorBoletas.*; import vista.GenerarBoletas; import vista.ActualizarNota; import vista.ListaGeneral; import vista.Estadisticas; /** * * @author Felipe Mora */ public class AdministradorInt { GestorBoletas gestor; public AdministradorInt() { this.gestor = new GestorBoletas(); } public int generarEstudiantes(GenerarBoletas boleta) { GenerarBoletas boletas = boleta; int bol = Integer.parseInt(boletas.getTxt_Generar().getText()); gestor.crearBoletas(bol); gestor.construirReporteConTresMejoresPromedios(); return 0; } public String actualizarNota(ActualizarNota actN) { String text = actN.getTxt_NotaBol().getText(); float calificacion = Float.parseFloat(text); int numBol = Integer.parseInt(actN.getTxt_NumBol().getText()); return gestor.actualizarCalificacion(calificacion, numBol); } public int obtenerBoletas(ListaGeneral list) { list.setTxt_BolSist(String.valueOf(gestor.getBoletas().size())); list.setTxt_Boletas(gestor.getBoletas().toString()); return 0; } public void ordenarAlfab(ListaGeneral list) { list.setTxt_BolSist(String.valueOf(gestor.getBoletas().size())); gestor.ordenarPorAlfabeto(); list.setTxt_Boletas(gestor.getBoletas().toString()); } public void rankingAdmitidos(ListaGeneral list) { list.setTxt_BolSist(String.valueOf(gestor.getBoletas().size())); list.setTxt_Boletas(gestor.rankingAdmitidos()); } public void obtenerTresMej(ListaGeneral list) { list.setTxt_Boletas(gestor.construirReporteConTresMejoresPromedios()); } public void obtenerElegibles_Rechazados(ListaGeneral list) { list.setTxt_Boletas(gestor.filtrarPorResultado()); } public int estadisticas(Estadisticas stats) { stats.setTxt_Recibidas(String.valueOf(gestor.getBoletas().size())); stats.setTxt_Aceptados(String.valueOf(gestor.getContadorAprobados())); stats.setTxt_Elegibles(String.valueOf(gestor.getContadorElegibles())); stats.setTxt_Rechazados(String.valueOf(gestor.getContadorRechazados())); return 0; } }
true
281f8887249f35c1cd2d14d8582d8efdf1387291
Java
iromos/LabelPet
/LABEL_PROJECT/LabelCore/src/main/java/exception/ExceptionAnswer.java
UTF-8
829
2.3125
2
[]
no_license
package exception; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; /** * Created by Jackson on 22.05.2015. */ @XmlRootElement(name = "doc") public class ExceptionAnswer { private List<LabelException> exceptions; @XmlElement(name = "LabelError") @XmlElementWrapper(name = "Errors") public List<LabelException> getExceptions() { return exceptions; } public void setExceptions(List<LabelException> exceptions) { this.exceptions = exceptions; } public void addException(LabelException ex) { if (exceptions == null) { exceptions = new ArrayList<LabelException>(); } exceptions.add(ex); } }
true
e4aa66371f0be61da8e706b7c6cd95fdf833c5ae
Java
thaond/eGov_Portal
/Portlet/VAdv-portlet/docroot/WEB-INF/src/com/vportal/portlet/vadvman/util/VAdvmanUtil.java
UTF-8
2,584
2.515625
3
[]
no_license
/** * Copyright (c) Vietsoftware, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.vportal.portlet.vadvman.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import com.liferay.portal.kernel.util.Validator; public class VAdvmanUtil { /** * Generate the random prefix.<br /> * Copied from: com.vportal.portlet.newsadmin.utils.NewsUtils * * @return The random prefix */ public static String getRandPrefix() { Calendar c = Calendar.getInstance(); String curTime = String.valueOf(c.getTimeInMillis()); if (Validator.isNotNull(curTime) && curTime.length() > 23) { curTime = curTime.substring(10, 23); } return curTime; } /** * Ham phan tich ngay thang<br /> * Copied from com.vportal.portlet.edirectory.util.EDirectoryUtil * * @param date * Ngay thang can phan tich * @return Dang dd/MM/yyyy cua ngay thang nhap vao */ public static String dateParser(Date date) { if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); String dateStr = ""; cal.setTime(date); int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); dateStr = day + "/" + month + "/" + year; return dateStr; } /** * Ham chuyen 1 xau sang ngay thang<br /> * Copied from com.vportal.portlet.edirectory.util.EDirectoryUtil * * @param date * Xau chua ngay thang, co dang: dd/MM/yyyy * @return Doi tuong ngay thang */ public static Date dateParser(String date) { try { SimpleDateFormat result = new SimpleDateFormat("dd/MM/yyyy"); Date newDate = result.parse(date); return newDate; } catch (Exception e) { e.printStackTrace(); } return null; } public static String trimString(String str, int length) { try { StringBuffer buff = new StringBuffer(); int index = str.indexOf(" ", length); buff.append(str.substring(0, index)); buff.append("..."); return buff.toString(); } catch (StringIndexOutOfBoundsException e) { return str; } } }
true
09e41d920e61bb901c789d343021823132877c21
Java
karunmatharu/Android-4.4-Pay-by-Data
/external/jsilver/src/com/google/clearsilver/jsilver/functions/bundles/ClearSilverCompatibleFunctions.java
UTF-8
4,455
1.898438
2
[ "MIT" ]
permissive
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clearsilver.jsilver.functions.bundles; import com.google.clearsilver.jsilver.functions.escape.*; import com.google.clearsilver.jsilver.functions.html.CssUrlValidateFunction; import com.google.clearsilver.jsilver.functions.html.HtmlStripFunction; import com.google.clearsilver.jsilver.functions.html.HtmlUrlValidateFunction; import com.google.clearsilver.jsilver.functions.html.TextHtmlFunction; import com.google.clearsilver.jsilver.functions.numeric.AbsFunction; import com.google.clearsilver.jsilver.functions.numeric.MaxFunction; import com.google.clearsilver.jsilver.functions.numeric.MinFunction; import com.google.clearsilver.jsilver.functions.string.CrcFunction; import com.google.clearsilver.jsilver.functions.string.FindFunction; import com.google.clearsilver.jsilver.functions.string.LengthFunction; import com.google.clearsilver.jsilver.functions.string.SliceFunction; import com.google.clearsilver.jsilver.functions.structure.FirstFunction; import com.google.clearsilver.jsilver.functions.structure.LastFunction; import com.google.clearsilver.jsilver.functions.structure.SubcountFunction; /** * Set of functions required to allow JSilver to be compatible with ClearSilver. */ public class ClearSilverCompatibleFunctions extends CoreOperators { @Override protected void setupDefaultFunctions() { super.setupDefaultFunctions(); // Structure functions. registerFunction("subcount", new SubcountFunction()); registerFunction("first", new FirstFunction()); registerFunction("last", new LastFunction()); // Deprecated - but here for ClearSilver compatibility. registerFunction("len", new SubcountFunction()); // Numeric functions. registerFunction("abs", new AbsFunction()); registerFunction("max", new MaxFunction()); registerFunction("min", new MinFunction()); // String functions. registerFunction("string.slice", new SliceFunction()); registerFunction("string.find", new FindFunction()); registerFunction("string.length", new LengthFunction()); registerFunction("string.crc", new CrcFunction()); // Escaping functions. registerFunction("url_escape", new UrlEscapeFunction("UTF-8"), true); registerEscapeMode("url", new UrlEscapeFunction("UTF-8")); registerFunction("html_escape", new HtmlEscapeFunction(false), true); registerEscapeMode("html", new HtmlEscapeFunction(false)); registerFunction("js_escape", new JsEscapeFunction(false), true); registerEscapeMode("js", new JsEscapeFunction(false)); // These functions are available as arguments to <?cs escape: ?> // though they aren't in ClearSilver. This is so that auto escaping // can automatically add <?cs escape ?> nodes with these modes registerEscapeMode("html_unquoted", new HtmlEscapeFunction(true)); registerEscapeMode("js_attr_unquoted", new JsEscapeFunction(true)); registerEscapeMode("js_check_number", new JsValidateUnquotedLiteral()); registerEscapeMode("url_validate_unquoted", new HtmlUrlValidateFunction(true)); registerEscapeMode("css", new StyleEscapeFunction(false)); registerEscapeMode("css_unquoted", new StyleEscapeFunction(true)); // HTML functions. registerFunction("html_strip", new HtmlStripFunction()); registerFunction("text_html", new TextHtmlFunction()); // url_validate is available as an argument to <?cs escape: ?> // though it isn't in ClearSilver. registerFunction("url_validate", new HtmlUrlValidateFunction(false), true); registerEscapeMode("url_validate", new HtmlUrlValidateFunction(false)); registerFunction("css_url_validate", new CssUrlValidateFunction(), true); // Register as an EscapingFunction so that autoescaping will be disabled // for the output of this function. registerFunction("null_escape", new NullEscapeFunction(), true); } }
true
04ab35bc365e6f48542b77aad0ac8dac765c0567
Java
Kindegerten/kindergarten
/src/main/java/com/kindergarten/bean/SchoolBill.java
UTF-8
1,885
2.15625
2
[]
no_license
package com.kindergarten.bean; public class SchoolBill { private int billId; private String billName; private int billMoney; private String billDirector; private int billClassId; private String billClassName; private int kinderId; private String billCreatetime; private String studentbillType="未缴费"; public SchoolBill() { } public int getBillId() { return billId; } public String getBillCreatetime() { return billCreatetime; } public void setBillCreatetime(String billCreatetime) { this.billCreatetime = billCreatetime; } public String getStudentbillType() { return studentbillType; } public void setStudentbillType(String studentbillType) { this.studentbillType = studentbillType; } public void setBillId(int billId) { this.billId = billId; } public String getBillName() { return billName; } public void setBillName(String billName) { this.billName = billName; } public int getBillMoney() { return billMoney; } public void setBillMoney(int billMoney) { this.billMoney = billMoney; } public String getBillDirector() { return billDirector; } public void setBillDirector(String billDirector) { this.billDirector = billDirector; } public int getBillClassId() { return billClassId; } public void setBillClassId(int billClassId) { this.billClassId = billClassId; } public String getBillClassName() { return billClassName; } public void setBillClassName(String billClassName) { this.billClassName = billClassName; } public int getKinderId() { return kinderId; } public void setKinderId(int kinderId) { this.kinderId = kinderId; } }
true
6f011829f74bfd85812101bbafd5cf65d81f79c2
Java
benjdod/comp520-compilerproject
/src/miniJava/AbstractSyntaxTrees/TypeDenoter.java
UTF-8
2,597
2.90625
3
[]
no_license
/** * miniJava Abstract Syntax Tree classes * @author prins * @version COMP 520 (v2.2) */ package miniJava.AbstractSyntaxTrees; import miniJava.SyntacticAnalyzer.SourcePosition; abstract public class TypeDenoter extends AST { public TypeDenoter(TypeKind type, SourcePosition posn){ super(posn); typeKind = type; } public TypeKind typeKind; @Override public int hashCode() { return typeKind.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof TypeDenoter) { return equals((TypeDenoter) o); } else { return false; } } public boolean equals(TypeDenoter td) { return equals(td, this); } public static boolean equals(TypeDenoter a, TypeDenoter b) { if (a.typeKind == TypeKind.UNSUPPORTED || b.typeKind == TypeKind.UNSUPPORTED) return false; if (a.typeKind == TypeKind.ERROR || b.typeKind == TypeKind.ERROR) return true; if (a.typeKind == TypeKind.INT && b.typeKind == TypeKind.INT) { return true; } if (a.typeKind == TypeKind.BOOLEAN && b.typeKind == TypeKind.BOOLEAN) return true; if (a.typeKind == TypeKind.VOID && b.typeKind == TypeKind.VOID) return true; if (a.typeKind == TypeKind.ARRAY || b.typeKind == TypeKind.ARRAY) { if (a.typeKind == TypeKind.ARRAY && b.typeKind == TypeKind.ARRAY) { ArrayType adt = (ArrayType) a; ArrayType bdt = (ArrayType) b; if (equals(adt.eltType, bdt.eltType)) return true; } if (a.typeKind == TypeKind.NULL || b.typeKind == TypeKind.NULL) { return true; } } if (a.typeKind == TypeKind.CLASS || b.typeKind == TypeKind.CLASS) { if (a.typeKind == TypeKind.CLASS && b.typeKind == TypeKind.CLASS) { ClassType act = (ClassType) a; ClassType bct = (ClassType) b; if (act.className.spelling.contentEquals(bct.className.spelling)) return true; } if (a.typeKind == TypeKind.NULL || b.typeKind == TypeKind.NULL) { return true; } } return false; } /** * This is a hacky way of making the compiler * not yell at us, but it is overriden in * every subclass so it's safe. */ public TypeDenoter copy() { return null; } }
true
d0da1a81a7b719e757de24c22187da49a62987e5
Java
marc0tjevp/Avans-Mars-Rover-Pictures
/app/src/main/java/nl/marcovp/avans/nasaroverphotos/controller/PhotoFoundTask.java
UTF-8
5,761
2.578125
3
[]
no_license
package nl.marcovp.avans.nasaroverphotos.controller; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.sql.Date; import java.util.Objects; import nl.marcovp.avans.nasaroverphotos.R; import nl.marcovp.avans.nasaroverphotos.domain.Photo; /** * Created by marco on 3/13/18. */ public class PhotoFoundTask extends AsyncTask<String, Void, String> { private OnPhotoAvailable listener = null; private Context context; private ProgressDialog progressDialog; private String TAG = this.getClass().getSimpleName(); PhotoFoundTask(OnPhotoAvailable listener, Context context) { this.listener = listener; this.context = context; } @Override protected void onPreExecute() { // Debug Log Log.d(TAG, "onPreExecute"); // Start progressDialog progressDialog = ProgressDialog.show(context, context.getResources().getString(R.string.text_fetching_title), context.getResources().getString(R.string.text_fetching_message), true); } @Override protected String doInBackground(String... strings) { // Debug Log Log.d(TAG, "doInBackground"); // Variables InputStream inputStream = null; int responseCode = -1; String movieUrl = strings[0]; String response = ""; try { // Open Connection URL url = new URL(movieUrl); URLConnection connection = url.openConnection(); // Debug Log Log.d(TAG, "doInBackground URL: " + url); if (!(connection instanceof HttpURLConnection)) { return null; } // Connect HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.setAllowUserInteraction(false); httpURLConnection.setInstanceFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); // Get Response Code responseCode = httpURLConnection.getResponseCode(); // On 200, set JSON data to String if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = httpURLConnection.getInputStream(); response = getStringFromInputStream(inputStream); } } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "IOException: " + e.getMessage()); } return response; } @Override protected void onPostExecute(String response) { // Debug Log Log.d(TAG, "onPostExecute"); // Check if response is not empty if (response == null || Objects.equals(response, "")) { Toast.makeText(context, R.string.text_no_internet, Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); return; } JSONObject jsonObject; try { // Make JSON Object from string jsonObject = new JSONObject(response); // Get photos array from data JSONArray photos = jsonObject.getJSONArray("photos"); for (int i = 0; i < photos.length(); i++) { // Get Photo object by index JSONObject photo = photos.getJSONObject(i); // Set variables int photoID = photo.getInt("id"); int photoSol = photo.getInt("sol"); JSONObject photoCamera = photo.getJSONObject("camera"); String photoCameraName = photoCamera.getString("full_name"); String photoURL = photo.getString("img_src"); Date earthDate = Date.valueOf(photo.getString("earth_date")); // Create photo object Photo p = new Photo(photoID, photoSol, photoCameraName, photoURL, earthDate); // Debug Log Log.d(TAG, "New Photo: " + p.getId()); // Return object to listener listener.onPhotoAvailable(p); } // Return nothing available if the arraylist is empty if (photos.length() < 1) { listener.nothingAvailable(); } // Debug Log Log.d(TAG, "Found " + photos.length() + " Photos"); } catch (JSONException e) { Log.e(TAG, "JSONEXCEPTION: " + e.getMessage()); e.printStackTrace(); } // Dismiss progressDialog progressDialog.dismiss(); } private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } // Interface OnPhotoAvailable public interface OnPhotoAvailable { void onPhotoAvailable(Photo p); void nothingAvailable(); } }
true
3138e43d0b95e93f41d3faa185ff0734a5356d00
Java
L1NDS0N/Locadora-Java-Android
/src/main/java/br/senai/rn/locadora/controllers/CopiaController.java
UTF-8
1,148
2.015625
2
[]
no_license
package br.senai.rn.locadora.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import br.senai.rn.locadora.models.Categoria; import br.senai.rn.locadora.models.Copia; import br.senai.rn.locadora.services.CategoriaService; @Controller @RequestMapping("/copia") public class CopiaController extends AbstractController<Copia> { @Autowired private CategoriaService categoriaService; @Override public String index(Model model) { List<Categoria> categorias = categoriaService.findAll(); model.addAttribute("categoriaList", categorias); return super.index(model); } @Override @GetMapping("/editar/{id}") public String editar(@PathVariable Long id, Model model) { List<Categoria> categorias = categoriaService.findAll(); model.addAttribute("categoriaList", categorias); return super.editar(id, model); } }
true
4ca29b148a6c4e8a51c5facf4a5acc71a359792d
Java
colinator27/utonlineserver
/src/me/colinator27/packet/PacketBuilder.java
UTF-8
4,064
3.046875
3
[ "MIT" ]
permissive
package me.colinator27.packet; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.UUID; /** Helper class to fill packet send buffers with data */ public class PacketBuilder { /** The protocol version of packets being sent to and from clients */ public static final byte PROTOCOL_VERSION = 0; /** The offset of the packet header plus type */ public static final int SEND_OFFSET = 5; /** * Fills the send buffer with the standard packet header bytes * * @param send the send buffer to fill */ public static void fillHeader(byte[] send) { send[0] = 'U'; send[1] = 'T'; send[2] = 'O'; send[3] = PROTOCOL_VERSION; } public final byte[] send; private ByteBuffer bb; private int offset; /** * Initializes a new PacketBuilder to fill the send buffer with information * * @param type the type of packet to send * @param send the send buffer to fill */ public PacketBuilder(OutboundPacketType type) { this.send = new byte[4096]; PacketBuilder.fillHeader(send); bb = ByteBuffer.wrap(send); bb.order(ByteOrder.LITTLE_ENDIAN); send[4] = type.id; this.offset = SEND_OFFSET; } /** @return the size of the packet data, including the header and type (SEND_OFFSET) */ public int getSize() { return offset; } /** * Writes a byte to the packet, and advances * * @param val the byte to write * @return this PacketBuilder */ public PacketBuilder addByte(byte val) { bb.put(offset, val); offset++; return this; } /** * Writes a short to the packet, and advances * * @param val the short to write * @return this PacketBuilder */ public PacketBuilder addShort(short val) { bb.putShort(offset, val); offset += 2; return this; } /** * Writes an int to the packet, and advances * * @param val the int to write * @return this PacketBuilder */ public PacketBuilder addInt(int val) { bb.putInt(offset, val); offset += 4; return this; } /** * Writes a float to the packet, and advances * * @param val the float to write * @return this PacketBuilder */ public PacketBuilder addFloat(float val) { bb.putFloat(offset, val); offset += 4; return this; } /** * Writes a long to the packet, and advances * * @param val the long to write * @return this PacketBuilder */ public PacketBuilder addLong(long val) { bb.putLong(offset, val); offset += 8; return this; } /** * Writes a double to the packet, and advances * * @param val the double to write * @return this PacketBuilder */ public PacketBuilder addDouble(double val) { bb.putDouble(offset, val); offset += 8; return this; } /** * Writes a null-terminated String to the packet, and advances * * @param val the String to write * @return this PacketBuilder */ public PacketBuilder addString(String val) { byte[] buff = val.getBytes(Charset.forName("UTF-8")); System.arraycopy(buff, 0, send, offset, buff.length); send[buff.length + offset] = 0; offset += buff.length + 1; return this; } /** * Writes a UUID (128-bit) to the packet, and advances * * @param val the UUID to write * @return this PacketBuilder */ public PacketBuilder addUUID(UUID val) { return addLong(val.getMostSignificantBits()).addLong(val.getLeastSignificantBits()); } /** * Builds and returns the packet in its current state * * @return bytes the raw bytes of the constructed packet */ public byte[] build() { return Arrays.copyOfRange(send, 0, offset); } }
true
e776f41dca7ef8a1ae9a363345182d4f794f85b7
Java
zhhaochen/Algorithm
/CodeTop/src/ByteDance/Solution91.java
UTF-8
782
2.96875
3
[]
no_license
package ByteDance; public class Solution91 { public int numDecodings(String s) { int[] dp = new int[s.length() + 1]; dp[0] = 1; if (s.charAt(0) != '0') dp[1] = 1; for (int i = 1; i < s.length(); i++){ // 当前为 0 if (s.charAt(i) == '0'){ if (s.charAt(i-1) == '1' || s.charAt(i-1) == '2') dp[i+1] = dp[i-1]; else return 0; }else if (s.charAt(i) <= '6'){ if (s.charAt(i-1) == '1' || s.charAt(i-1) == '2') dp[i+1] = dp[i-1] + dp[i]; else dp[i+1] = dp[i]; }else { if (s.charAt(i-1) == '1') dp[i+1] = dp[i-1] + dp[i]; else dp[i+1] = dp[i]; } } return dp[s.length()]; } }
true
db471d56b77ee7c98d17e93889785ae2da672992
Java
unica-open/siacfinapp
/src/main/java/it/csi/siac/siacfinapp/frontend/ui/model/movgest/RicercaImpegnoModel.java
UTF-8
5,380
1.929688
2
[]
no_license
/* *SPDX-FileCopyrightText: Copyright 2020 | CSI Piemonte *SPDX-License-Identifier: EUPL-1.2 */ package it.csi.siac.siacfinapp.frontend.ui.model.movgest; import it.csi.siac.siacbilser.model.ElementoPianoDeiConti; import it.csi.siac.siacfinapp.frontend.ui.model.GenericFinModel; public class RicercaImpegnoModel extends GenericFinModel { private static final long serialVersionUID = 2718637354856268419L; //anno esercizio private String annoEsercizio; //anno movimento private String annoMovimento; //numero impegno private String numeroImpegno; //id stato operativo movgest private String idStatoOperativoMovgest; //competenze private String competenze; //cup private String cup; //cig private String cig; //progetto private String progetto; //anno impegno riaccertamento private String annoImpRiacc; //numero impegno riaccertamento private String numeroImpRiacc; //anno impegno origine private String annoImpOrigine; //numero impegno origine private String numeroImpOrigine; //per marcare competenza tutti private boolean competenzaTutti; //per marcare competenza private boolean competenzaCompetenza; //per marcare competenza corrente private boolean competenzaCorrente; //per marcare competenza futuri private boolean competenzaFuturi; //struttura selezionata su pagina private String strutturaSelezionataSuPagina; //piano dei conti private ElementoPianoDeiConti pianoDeiConti = new ElementoPianoDeiConti(); //SIAC-5253 nuovo campo per escludere i movimenti annullati: private Boolean escludiAnnullati = Boolean.FALSE; private Boolean hiddenPerEscludiAnnullati; //GETTER E SETTER: /** * @return the strutturaSelezionataSuPagina */ public String getStrutturaSelezionataSuPagina() { return strutturaSelezionataSuPagina; } /** * @param strutturaSelezionataSuPagina * the strutturaSelezionataSuPagina to set */ public void setStrutturaSelezionataSuPagina(String strutturaSelezionataSuPagina) { this.strutturaSelezionataSuPagina = strutturaSelezionataSuPagina; } public String getAnnoEsercizio() { return annoEsercizio; } public void setAnnoEsercizio(String annoEsercizio) { this.annoEsercizio = annoEsercizio; } public String getNumeroImpegno() { return numeroImpegno; } public void setNumeroImpegno(String numeroImpegno) { this.numeroImpegno = numeroImpegno; } public String getIdStatoOperativoMovgest() { return idStatoOperativoMovgest; } public void setIdStatoOperativoMovgest(String idStatoOperativoMovgest) { this.idStatoOperativoMovgest = idStatoOperativoMovgest; } public String getCompetenze() { return competenze; } public void setCompetenze(String competenze) { this.competenze = competenze; } public String getCup() { return cup; } public void setCup(String cup) { this.cup = cup; } public String getCig() { return cig; } public void setCig(String cig) { this.cig = cig; } public String getProgetto() { return progetto; } public void setProgetto(String progetto) { this.progetto = progetto; } public String getAnnoImpRiacc() { return annoImpRiacc; } public void setAnnoImpRiacc(String annoImpRiacc) { this.annoImpRiacc = annoImpRiacc; } public String getNumeroImpRiacc() { return numeroImpRiacc; } public void setNumeroImpRiacc(String numeroImpRiacc) { this.numeroImpRiacc = numeroImpRiacc; } public String getAnnoImpOrigine() { return annoImpOrigine; } public void setAnnoImpOrigine(String annoImpOrigine) { this.annoImpOrigine = annoImpOrigine; } public String getNumeroImpOrigine() { return numeroImpOrigine; } public void setNumeroImpOrigine(String numeroImpOrigine) { this.numeroImpOrigine = numeroImpOrigine; } public boolean isCompetenzaTutti() { return competenzaTutti; } public void setCompetenzaTutti(boolean competenzaTutti) { this.competenzaTutti = competenzaTutti; } public boolean isCompetenzaCompetenza() { return competenzaCompetenza; } public void setCompetenzaCompetenza(boolean competenzaCompetenza) { this.competenzaCompetenza = competenzaCompetenza; } public boolean isCompetenzaCorrente() { return competenzaCorrente; } public void setCompetenzaCorrente(boolean competenzaCorrente) { this.competenzaCorrente = competenzaCorrente; } public boolean isCompetenzaFuturi() { return competenzaFuturi; } public void setCompetenzaFuturi(boolean competenzaFuturi) { this.competenzaFuturi = competenzaFuturi; } public ElementoPianoDeiConti getPianoDeiConti() { return pianoDeiConti; } public void setPianoDeiConti(ElementoPianoDeiConti pianoDeiConti) { this.pianoDeiConti = pianoDeiConti; } /** * @return the annoMovimento */ public String getAnnoMovimento() { return annoMovimento; } /** * @param annoMovimento * the annoMovimento to set */ public void setAnnoMovimento(String annoMovimento) { this.annoMovimento = annoMovimento; } public Boolean getEscludiAnnullati() { return escludiAnnullati; } public void setEscludiAnnullati(Boolean escludiAnnullati) { this.escludiAnnullati = escludiAnnullati; } public Boolean getHiddenPerEscludiAnnullati() { return hiddenPerEscludiAnnullati; } public void setHiddenPerEscludiAnnullati(Boolean hiddenPerEscludiAnnullati) { this.hiddenPerEscludiAnnullati = hiddenPerEscludiAnnullati; } }
true
182398612028d2a35b23ea96cf4b7c6ab95f8b12
Java
MariannaSol/multithreading2311
/src/main/java/com/java2311/multithreading2311/model/TaskRunnable.java
UTF-8
590
2.9375
3
[]
no_license
package com.java2311.multithreading2311.model; import javax.swing.*; public class TaskRunnable implements Runnable{ private JProgressBar progressBar; private int currentValue = 0; public TaskRunnable(JProgressBar progressBar) { this.progressBar = progressBar; } @Override public void run() { while(!Thread.interrupted()) { if(currentValue > progressBar.getMaximum()) { currentValue = progressBar.getMinimum(); } progressBar.setValue(currentValue++); } } }
true
650f5700f90adde1ea7d298ffacb8557e43532c3
Java
hemin1003/aylson-parent
/aylson-manage/src/main/java/com/aylson/dc/owner/controller/AppointmentController.java
UTF-8
9,526
1.914063
2
[]
no_license
package com.aylson.dc.owner.controller; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.aylson.core.constants.SysConstant.BillCodePrefix; import com.aylson.core.easyui.EasyuiDataGridJson; import com.aylson.core.frame.controller.BaseController; import com.aylson.core.frame.domain.Result; import com.aylson.core.frame.domain.ResultCode; import com.aylson.dc.owner.search.AppointmentSearch; import com.aylson.dc.owner.service.AppointmentService; import com.aylson.dc.owner.vo.AppointmentVo; import com.aylson.dc.sys.common.SessionInfo; import com.aylson.dc.sys.service.RoleService; import com.aylson.dc.sys.vo.RoleVo; import com.aylson.utils.BillNumUtils; import com.aylson.utils.DateUtil; import com.aylson.utils.StringUtil; import com.aylson.utils.VerificationUtils; /** * 反馈管理 * @author wwx * @since 2016-08 * @version v1.0 * */ @Controller @RequestMapping("/owner/appointment") public class AppointmentController extends BaseController { @Autowired private AppointmentService appointmentService; //在线预约服务 @Autowired private RoleService roleService; //角色服务 /** * 后台-首页 * * @return */ @RequestMapping(value = "/admin/toIndex", method = RequestMethod.GET) public String toIndex() { return "/jsp/owner/admin/appointment/index"; } /** * 获取列表-分页 * @return list */ @RequestMapping(value = "/admin/list", method = RequestMethod.GET) @ResponseBody public EasyuiDataGridJson list(AppointmentSearch appointmentSearch){ EasyuiDataGridJson result = new EasyuiDataGridJson();//页面DataGrid结果集 try{ SessionInfo sessionInfo = (SessionInfo)this.request.getSession().getAttribute("sessionInfo");//缓存信息 if(sessionInfo != null && sessionInfo.getUser() != null){ RoleVo roleVo = this.roleService.getById(sessionInfo.getUser().getRoleId()); if(roleVo != null){ if("agent".equals(roleVo.getRoleCode())){//如果是代理商,只能看到自己的预约单信息 appointmentSearch.setByAgentUserId(sessionInfo.getUser().getId()); } } } appointmentSearch.setIsPage(true); List<AppointmentVo> list = this.appointmentService.getList(appointmentSearch); result.setTotal(this.appointmentService.getRowCount(appointmentSearch)); result.setRows(list); return result; }catch(Exception e){ e.printStackTrace(); return null; } } /** * 获取列表-不分页 * 根据条件获取列表信息 * @param appointmentSearch * @return */ @ResponseBody @RequestMapping(value = "/getList", method = RequestMethod.GET) public List<AppointmentVo> getList(AppointmentSearch appointmentSearch) { List<AppointmentVo> list = this.appointmentService.getList(appointmentSearch); return list; } /** * 后台-添加预约单页面 * @return */ @RequestMapping(value = "/admin/toAdd", method = RequestMethod.GET) public String toAdd() { return "/jsp/owner/admin/appointment/add"; } /** * 后台-添加预约单保存 * @param appointmentVo * @return */ @RequestMapping(value = "/admin/add", method = RequestMethod.POST) @ResponseBody public Result add(AppointmentVo appointmentVo) { Result result = new Result(); try{ //信息校验 if(!VerificationUtils.isValid(appointmentVo.getMobilePhone(), VerificationUtils.MOBILE)){ result.setError(ResultCode.CODE_STATE_4006, "请输入有效的预约人手机号码"); return result; } /*if(!VerificationUtils.isValid(appointmentVo.getDesignerPhone(), VerificationUtils.MOBILE)){ result.setError(ResultCode.CODE_STATE_4006, "请输入有效的上门设计师手机号码"); return result; }*/ if(StringUtil.isNotEmpty(appointmentVo.getHomeTimeStr())){ appointmentVo.setHomeTime(DateUtil.format(appointmentVo.getHomeTimeStr(),"yyyy-MM-dd HH:mm:ss")); } if(StringUtil.isNotEmpty(appointmentVo.getDecoratingTimeStr())){ appointmentVo.setDecoratingTime(DateUtil.format(appointmentVo.getDecoratingTimeStr(),"yyyy-MM-dd")); } appointmentVo.setAppointDate(new Date()); appointmentVo.setSource("web"); //添加来源:web后台 appointmentVo.setBillCode(BillNumUtils.getBillCode(BillCodePrefix.APPOINTMENT,appointmentVo.getMobilePhone())); Boolean flag = this.appointmentService.add(appointmentVo); if(flag){ result.setOK(ResultCode.CODE_STATE_200, "操作成功,下单号为:" + appointmentVo.getBillCode()); }else{ result.setError(ResultCode.CODE_STATE_4006, "操作失败"); } }catch(Exception e){ e.printStackTrace(); result.setError(ResultCode.CODE_STATE_500, e.getMessage()); } return result; } /** * 后台-编辑页面 * @param id * @return */ @RequestMapping(value = "/admin/toEdit", method = RequestMethod.GET) public String toEdit(Integer id, Integer state) { if(id != null){ AppointmentVo appointmentVo = this.appointmentService.getById(id); if(appointmentVo.getHomeTime() != null){ appointmentVo.setHomeTimeStr(DateUtil.format(appointmentVo.getHomeTime())); } if(appointmentVo.getDecoratingTime() != null){ appointmentVo.setDecoratingTimeStr(DateUtil.format(appointmentVo.getDecoratingTime(),true)); } appointmentVo.setState(state); this.request.setAttribute("appointmentVo",appointmentVo); } if(3 == state){ return "/jsp/owner/admin/appointment/cancel"; }else{ return "/jsp/owner/admin/appointment/add"; } } /** * 后台-编辑保存 * @param appointmentVo * @return */ @RequestMapping(value = "/admin/update", method = RequestMethod.POST) @ResponseBody public Result update(AppointmentVo appointmentVo) { Result result = new Result(); try { if(StringUtil.isNotEmpty(appointmentVo.getHomeTimeStr())){ appointmentVo.setHomeTime(DateUtil.format(appointmentVo.getHomeTimeStr(),"yyyy-MM-dd HH:mm:ss")); } if(StringUtil.isNotEmpty(appointmentVo.getDecoratingTimeStr())){ appointmentVo.setDecoratingTime(DateUtil.format(appointmentVo.getDecoratingTimeStr(),"yyyy-MM-dd")); } Boolean flag = this.appointmentService.edit(appointmentVo); if(flag){ result.setOK(ResultCode.CODE_STATE_200, "操作成功"); }else{ result.setError(ResultCode.CODE_STATE_4006, "操作失败"); } } catch (Exception e) { e.printStackTrace(); result.setError(ResultCode.CODE_STATE_500, e.getMessage()); } return result; } /** * 根据id删除 * @param id * @return */ @RequestMapping(value = "/admin/deleteById", method = RequestMethod.POST) @ResponseBody public Result deleteById(Integer id) { Result result = new Result(); try{ Boolean flag = this.appointmentService.deleteById(id); if(flag){ result.setOK(ResultCode.CODE_STATE_200, "删除成功"); }else{ result.setError(ResultCode.CODE_STATE_4006, "删除失败"); } }catch(Exception e){ e.printStackTrace(); result.setError(ResultCode.CODE_STATE_500, e.getMessage()); } return result; } /** * 通知代理商报价 * @param appointId * @return */ @RequestMapping(value = "/admin/noticeAgentQuote", method = RequestMethod.POST) @ResponseBody public Result noticeAgentQuote(Integer appointId) { Result result = null; try{ result = this.appointmentService.noticeAgentQuote(appointId); }catch(Exception e){ e.printStackTrace(); result.setError(ResultCode.CODE_STATE_500, e.getMessage()); } return result; } /** * 通知客户确认报价 * @param appointId * @return */ @RequestMapping(value = "/admin/noticeConfirmQuote", method = RequestMethod.POST) @ResponseBody public Result noticeConfirmQuote(Integer appointId) { Result result = null; try{ result = this.appointmentService.noticeConfirmQuote(appointId); }catch(Exception e){ e.printStackTrace(); result.setError(ResultCode.CODE_STATE_500, e.getMessage()); } return result; } /** * 查看预约信息 * @param id * @return */ @RequestMapping(value = "/admin/toView", method = RequestMethod.GET) public String toView(Integer id) { if(id != null){ AppointmentVo appointmentVo = this.appointmentService.getById(id); if(appointmentVo.getHomeTime() != null){ appointmentVo.setHomeTimeStr(DateUtil.format(appointmentVo.getHomeTime())); } if(appointmentVo.getDecoratingTime() != null){ appointmentVo.setDecoratingTimeStr(DateUtil.format(appointmentVo.getDecoratingTime(),true)); } this.request.setAttribute("appointmentVo",appointmentVo); } return "/jsp/owner/admin/appointment/view"; } @RequestMapping(value = "/admin/sumConfrimDraw", method = RequestMethod.POST) @ResponseBody public Result sumConfrimDraw(Integer appointId) { Result result = null; try{ result = this.appointmentService.sumConfrimDraw(appointId); }catch(Exception e){ e.printStackTrace(); result.setError(ResultCode.CODE_STATE_500, e.getMessage()); } return result; } }
true
8779dc3f364367b587d01c274190a6f14b51b4ac
Java
ivandeleao/ouroboros
/src/model/nosql/relatorio/VendaItemConsolidadoReportBean.java
UTF-8
1,090
1.820313
2
[]
no_license
package model.nosql.relatorio; import java.math.BigDecimal; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author User */ public class VendaItemConsolidadoReportBean { private String vendedor; private String produto; private BigDecimal quantidade; private BigDecimal total; public String getVendedor() { return vendedor; } public void setVendedor(String vendedor) { this.vendedor = vendedor; } public String getProduto() { return produto; } public void setProduto(String produto) { this.produto = produto; } public BigDecimal getQuantidade() { return quantidade; } public void setQuantidade(BigDecimal quantidade) { this.quantidade = quantidade; } public BigDecimal getTotal() { return total; } public void setTotal(BigDecimal total) { this.total = total; } }
true
a107f562ec680c1109310401e4ee6e414a2b951a
Java
joineynguyen/Data-Structures-and-Algorithms
/Recursion/NthTribonacciNumber.java
UTF-8
748
3.578125
4
[]
no_license
/* Joiney Nguyen The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn. Example 1: Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 */ class Solution { public int tribonacci(int n) { return getTri(n, 0, 1, 1); } private int getTri(int n, int one, int two, int three) { if(n == 0) { return 0; } if(n == 1 || n == 2) { return 1; } int sum = one + two + three; if(n == 3) { return sum; } return getTri(n - 1, two, three, sum); } }
true
717a20b96a3f35daf23d41b7496701dcc2ca1f8d
Java
liyue2008/joyqueue
/joyqueue-server/joyqueue-nsr/joyqueue-nsr-ignite/src/main/java/org/joyqueue/nsr/ignite/dao/impl/IgniteConfigDao.java
UTF-8
4,475
1.992188
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2019 The JoyQueue 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.joyqueue.nsr.ignite.dao.impl; import org.joyqueue.model.PageResult; import org.joyqueue.model.QPageQuery; import org.joyqueue.nsr.ignite.dao.ConfigDao; import org.joyqueue.nsr.ignite.dao.IgniteDao; import org.joyqueue.nsr.ignite.model.IgniteConfig; import org.joyqueue.nsr.model.ConfigQuery; import org.joyqueue.nsr.ignite.model.IgniteBaseModel; import org.apache.commons.lang3.StringUtils; import org.apache.ignite.Ignite; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.QueryEntity; import org.apache.ignite.cache.QueryIndex; import org.apache.ignite.cache.query.SqlQuery; import org.apache.ignite.configuration.CacheConfiguration; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import static org.joyqueue.nsr.ignite.model.IgniteConfig.COLUMN_ID; import static org.joyqueue.nsr.ignite.model.IgniteConfig.COLUMN_CFG_KEY; import static org.joyqueue.nsr.ignite.model.IgniteConfig.COLUMN_CFG_VALUE; import static org.joyqueue.nsr.ignite.model.IgniteConfig.COLUMN_CFG_GROUP; public class IgniteConfigDao implements ConfigDao { public static final String CACHE_NAME = "config"; public static CacheConfiguration<String, IgniteConfig> cacheCfg; private IgniteDao igniteDao; static { cacheCfg = new CacheConfiguration<>(); cacheCfg.setName(CACHE_NAME); cacheCfg.setSqlSchema(IgniteBaseModel.SCHEMA); cacheCfg.setCacheMode(CacheMode.REPLICATED); cacheCfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL); QueryEntity queryEntity = new QueryEntity(); queryEntity.setKeyType(String.class.getName()); queryEntity.setValueType(IgniteConfig.class.getName()); LinkedHashMap<String, String> fields = new LinkedHashMap<>(); fields.put(COLUMN_ID, String.class.getName()); fields.put(COLUMN_CFG_GROUP, String.class.getName()); fields.put(COLUMN_CFG_KEY, String.class.getName()); fields.put(COLUMN_CFG_VALUE, String.class.getName()); queryEntity.setFields(fields); queryEntity.setTableName(CACHE_NAME); queryEntity.setIndexes(Arrays.asList(new QueryIndex(COLUMN_ID))); cacheCfg.setQueryEntities(Arrays.asList(queryEntity)); } public IgniteConfigDao(Ignite ignite) { this.igniteDao = new IgniteDao(ignite, cacheCfg); } @Override public IgniteConfig findById(String id) { return igniteDao.getById(id); } @Override public void add(IgniteConfig model) { igniteDao.addOrUpdate(model); } @Override public void addOrUpdate(IgniteConfig model) { igniteDao.addOrUpdate(model); } @Override public void deleteById(String id) { igniteDao.deleteById(id); } @Override public PageResult<IgniteConfig> pageQuery(QPageQuery<ConfigQuery> pageQuery) { return igniteDao.pageQuery(buildQuery(pageQuery.getQuery()), pageQuery.getPagination()); } @Override public List<IgniteConfig> list(ConfigQuery query) { return igniteDao.query(buildQuery(query)); } private SqlQuery buildQuery(ConfigQuery query) { IgniteDao.SimpleSqlBuilder sqlBuilder = IgniteDao.SimpleSqlBuilder.create(IgniteConfig.class); if (query != null) { if (query.getKey() != null && !query.getKey().isEmpty()) { sqlBuilder.and(COLUMN_CFG_KEY, query.getKey()); } if (query.getGroup() != null && !query.getGroup().isEmpty()) { sqlBuilder.and(COLUMN_CFG_GROUP, query.getGroup()); } if (StringUtils.isNotEmpty(query.getKeyword())) { sqlBuilder.and(COLUMN_CFG_KEY,query.getKeyword()).or(COLUMN_CFG_GROUP,query.getKeyword()); } } return sqlBuilder.build(); } }
true
739359c12890a36375b1a49eaa8ba92aecd799de
Java
geocento/EOBroker
/src/com/geocento/webapps/eobroker/customer/client/views/ProductResponseViewImpl.java
UTF-8
13,284
1.570313
2
[]
no_license
package com.geocento.webapps.eobroker.customer.client.views; import com.geocento.webapps.eobroker.common.client.utils.CategoryUtils; import com.geocento.webapps.eobroker.common.client.utils.DateUtil; import com.geocento.webapps.eobroker.common.client.utils.DateUtils; import com.geocento.webapps.eobroker.common.client.widgets.*; import com.geocento.webapps.eobroker.common.client.widgets.maps.AoIUtil; import com.geocento.webapps.eobroker.common.client.widgets.maps.MapContainer; import com.geocento.webapps.eobroker.common.shared.entities.Category; import com.geocento.webapps.eobroker.common.shared.entities.dtos.AoIDTO; import com.geocento.webapps.eobroker.common.shared.entities.formelements.FormElementValue; import com.geocento.webapps.eobroker.common.shared.entities.requests.Request; import com.geocento.webapps.eobroker.customer.client.ClientFactoryImpl; import com.geocento.webapps.eobroker.customer.client.Customer; import com.geocento.webapps.eobroker.customer.client.events.ChangeStatus; import com.geocento.webapps.eobroker.customer.shared.requests.MessageDTO; import com.geocento.webapps.eobroker.customer.shared.requests.ProductServiceResponseDTO; import com.geocento.webapps.eobroker.customer.shared.requests.ProductServiceSupplierResponseDTO; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.*; import gwt.material.design.addins.client.bubble.MaterialBubble; import gwt.material.design.addins.client.rating.MaterialRating; import gwt.material.design.client.constants.Color; import gwt.material.design.client.constants.Position; import gwt.material.design.client.ui.*; import java.util.Date; import java.util.List; /** * Created by thomas on 09/05/2016. */ public class ProductResponseViewImpl extends Composite implements ProductResponseView { interface ProductResponseViewUiBinder extends UiBinder<Widget, ProductResponseViewImpl> { } private static ProductResponseViewUiBinder ourUiBinder = GWT.create(ProductResponseViewUiBinder.class); static public interface StyleFile extends CssResource { String sectionLabel(); } @UiField StyleFile style; @UiField MaterialLabel title; @UiField protected MaterialColumn requestDescription; @UiField HTMLPanel requestResponse; @UiField MaterialRow messages; @UiField protected MapContainer mapContainer; @UiField ProgressButton submitMessage; @UiField MaterialTextArea message; @UiField UserWidget userImage; @UiField MaterialButton status; @UiField MaterialDropDown statuses; @UiField MaterialLabel description; @UiField HTMLPanel responseTitle; @UiField MaterialRow requestTab; @UiField MaterialPanel responsePanel; @UiField MaterialPanel colorPanel; @UiField MaterialPanel responsesPanel; @UiField MaterialPanel offers; @UiField MaterialImageLoading image; @UiField MaterialLabel messagesComment; @UiField MaterialLabel creationTime; private ClientFactoryImpl clientFactory; private ProductResponseView.Presenter presenter; public ProductResponseViewImpl(ClientFactoryImpl clientFactory) { this.clientFactory = clientFactory; initWidget(ourUiBinder.createAndBindUi(this)); colorPanel.setBackgroundColor(CategoryUtils.getColor(Category.productservices)); userImage.setUser(Customer.getLoginInfo().getUserName()); } @Override public void setMapLoadedHandler(Callback<Void, Exception> mapLoadedHandler) { mapContainer.setMapLoadedHandler(mapLoadedHandler); } @Override public void displayTitle(String title) { this.title.setText(title); } @Override public void displayImage(String imageURL) { this.image.setImageUrl(imageURL); } @Override public void displayComment(String comment) { description.setText(comment); } @Override public Widget asWidget() { return this; } @Override public void displayResponseSupplier(String supplierIconUrl, String supplierName) { responseTitle.clear(); responseTitle.add(new HTML("Offer provided by " + //"<img style='max-height: 24px; vertical-align: middle;' src='" + supplierIconUrl + "'/> " + "<b>" + supplierName + "</b>")); } @Override public void addMessage(String userName, boolean isCustomer, String message, Date date) { MaterialRow materialRow = new MaterialRow(); materialRow.setMarginBottom(0); messages.add(materialRow); Color colour = Color.WHITE; UserWidget userWidget = new UserWidget(userName); userWidget.setMarginTop(8); userWidget.setFloat(isCustomer ? Style.Float.LEFT : Style.Float.RIGHT); userWidget.setSize(40); materialRow.add(userWidget); MaterialBubble materialBubble = new MaterialBubble(); materialBubble.setBackgroundColor(colour); materialBubble.setFloat(isCustomer ? Style.Float.LEFT : Style.Float.RIGHT); materialBubble.setPosition(isCustomer ? Position.LEFT : Position.RIGHT); if(isCustomer) { materialBubble.setMarginLeft(12); } else { materialBubble.setMarginRight(12); } materialBubble.setWidth("50%"); materialRow.add(materialBubble); materialBubble.add(new MaterialLabel(message)); MaterialLabel materialLabel = new MaterialLabel(); materialLabel.setText(DateUtils.dateFormat.format(date)); materialLabel.setFloat(Style.Float.RIGHT); materialLabel.setFontSize(0.6, Style.Unit.EM); materialBubble.add(materialLabel); updateMessagesComment(); } protected void displayAoI(AoIDTO aoi) { mapContainer.displayAoI(aoi); mapContainer.centerOnAoI(); } protected void addRequestValue(String name, String value) { this.requestDescription.add(new HTMLPanel("<p style='padding: 0.5rem;'><b>" + name + ":</b> " + (value == null ? "not provided" : value) + "</p>")); } protected void displayResponse(String response) { requestResponse.clear(); if(response == null) { MaterialLabel materialLabel = new MaterialLabel("This supplier hasn't provided an offer yet..."); materialLabel.setMargin(20); materialLabel.setTextColor(Color.GREY); requestResponse.add(materialLabel); } else { requestResponse.add(new HTML(response)); } } protected void displayMessages(List<MessageDTO> messages) { this.messages.clear(); this.message.setText(""); String userName = Customer.getLoginInfo().getUserName(); if(messages != null && messages.size() > 0) { for (MessageDTO messageDTO : messages) { boolean isCustomer = !userName.contentEquals(messageDTO.getFrom()); addMessage(messageDTO.getFrom(), isCustomer, messageDTO.getMessage(), messageDTO.getCreationDate()); } } updateMessagesComment(); } private void updateMessagesComment() { boolean hasMessages = messages.getWidgetCount() > 0; messagesComment.setVisible(!hasMessages); if(!hasMessages) { messagesComment.setText("No messages yet..."); message.setPlaceholder("Start a conversation..."); } else { message.setPlaceholder("Reply..."); } } protected void setStatus(Request.STATUS status) { this.status.setText(status.toString()); statuses.clear(); this.status.setEnabled(false); switch(status) { case submitted: this.status.setEnabled(true); { MaterialLink materialLink = new MaterialLink("Cancel"); materialLink.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clientFactory.getEventBus().fireEvent(new ChangeStatus(Request.STATUS.cancelled)); } }); statuses.add(materialLink); } { MaterialLink materialLink = new MaterialLink("Complete"); materialLink.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clientFactory.getEventBus().fireEvent(new ChangeStatus(Request.STATUS.completed)); } }); statuses.add(materialLink); } break; } } protected void addResponseSection(ProductServiceSupplierResponseDTO selectedOffer) { ExpandPanel expandPanel = new ExpandPanel(); MaterialRating materialRating = new MaterialRating(); materialRating.setFloat(Style.Float.RIGHT); expandPanel.setHeader(materialRating); expandPanel.setLabel("Offer from '" + selectedOffer.getCompany().getName() + "' for service '" + selectedOffer.getServiceName() + "'"); expandPanel.setOpenHandler(new ExpandPanel.OpenHandler() { @Override public void onOpen() { presenter.responseSelected(selectedOffer); } }); expandPanel.setContent(new LoadingWidget("Loading...")); expandPanel.setId(selectedOffer.getId() + ""); expandPanel.setOpen(false); expandPanel.setLabelStyle(style.sectionLabel()); expandPanel.setLabelColor(Color.WHITE); offers.add(expandPanel); } @Override public HasClickHandlers getSubmitMessage() { return submitMessage; } @Override public HasText getMessageText() { return message; } @Override public void setPresenter(ProductResponseView.Presenter presenter) { this.presenter = presenter; } @Override public void displayProductRequest(ProductServiceResponseDTO productServiceResponseDTO) { setStatus(productServiceResponseDTO.getStatus()); creationTime.setText("Created on " + DateUtil.displaySimpleUTCDate(productServiceResponseDTO.getCreationTime())); this.requestDescription.clear(); addRequestValue("Product requested", productServiceResponseDTO.getProduct().getName()); if(productServiceResponseDTO.getFormValues().size() == 0) { this.requestDescription.add(new HTMLPanel("<p>No data provided</p>")); } else { for (FormElementValue formElementValue : productServiceResponseDTO.getFormValues()) { addRequestValue(formElementValue.getName(), formElementValue.getValue()); } } displayAoI(AoIUtil.fromWKT(productServiceResponseDTO.getAoIWKT())); // now add the responses offers.clear(); List<ProductServiceSupplierResponseDTO> responses = productServiceResponseDTO.getSupplierResponses(); for(final ProductServiceSupplierResponseDTO productServiceSupplierResponseDTO : responses) { addResponseSection(productServiceSupplierResponseDTO); } /* if(responses.size() > 1) { for(final ProductServiceSupplierResponseDTO productServiceSupplierResponseDTO : responses) { addResponseSection(productServiceSupplierResponseDTO); } this.responses.setVisible(true); // move response panel out of the collection widget responsesPanel.add(responsePanel); } else { this.responses.setVisible(false); // move response panel out of the collection widget responsesPanel.add(responsePanel); } */ displayProductResponse(responses.get(0)); } @Override public void displayProductResponse(ProductServiceSupplierResponseDTO productServiceSupplierResponseDTO) { if(productServiceSupplierResponseDTO == null) { return; } for(Widget widget : offers.getChildren()) { if(widget instanceof ExpandPanel) { ((ExpandPanel) widget).setOpen(false); if(((ExpandPanel) widget).getId().contentEquals(productServiceSupplierResponseDTO.getId() + "")) { ((ExpandPanel) widget).setContent(responsePanel); displayResponseSupplier(productServiceSupplierResponseDTO.getCompany().getIconURL(), productServiceSupplierResponseDTO.getCompany().getName()); displayResponse(productServiceSupplierResponseDTO.getResponse()); displayMessages(productServiceSupplierResponseDTO.getMessages()); ((ExpandPanel) widget).setOpen(true); } } } } }
true
68e7f67b9c8e7d709f0667914e7f3417a1277a2c
Java
ko9ma7/SingleLife_Market_Login
/src/main/java/org/single/domain/PageVO.java
UTF-8
1,169
1.96875
2
[]
no_license
package org.single.domain; import org.apache.ibatis.type.Alias; @Alias("pageVO") public class PageVO { private Integer count; private Integer pageNo; private Integer beginPage; private Integer endPage; private Integer lastPage; private Integer currTab; private Integer listSize = 20; public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Integer getPageNo() { return pageNo; } public void setPageNo(Integer pageNo) { this.pageNo = pageNo; } public Integer getBeginPage() { return beginPage; } public void setBeginPage(Integer beginPage) { this.beginPage = beginPage; } public Integer getEndPage() { return endPage; } public void setEndPage(Integer endPage) { this.endPage = endPage; } public Integer getLastPage() { return lastPage; } public void setLastPage(Integer lastPage) { this.lastPage = lastPage; } public Integer getCurrTab() { return currTab; } public void setCurrTab(Integer currTab) { this.currTab = currTab; } public Integer getListSize() { return listSize; } public void setListSize(Integer listSize) { this.listSize = listSize; } }
true
27dc3816f9fd522479906ceb5131b7748d0bf83e
Java
gaeeyo/garaponMate
/src/jp/syoboi/android/garaponmate/activity/PlayerActivity.java
UTF-8
2,625
2.171875
2
[]
no_license
package jp.syoboi.android.garaponmate.activity; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.Window; import jp.syoboi.android.garaponmate.App; import jp.syoboi.android.garaponmate.service.PlayerService; public class PlayerActivity extends Activity { private static final String TAG = "PlayerActivity"; static IntentFilter sIntentFilter; static { sIntentFilter = new IntentFilter(); sIntentFilter.addAction(App.ACTION_PLAYER_ACTIVITY_FINISH); sIntentFilter.addAction(App.ACTION_PLAYER_ACTIVITY_FULLSCREEN); } BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent == null) { return; } String action = intent.getAction(); if (action.equals(App.ACTION_PLAYER_ACTIVITY_FINISH)) { runOnUiThread(new Runnable() { @Override public void run() { finish(); overridePendingTransition(0, 0); } }); } else if (action.equals(App.ACTION_PLAYER_ACTIVITY_FULLSCREEN)) { final boolean fullScreen = intent.getBooleanExtra("fullScreen", false); runOnUiThread(new Runnable() { @Override public void run() { setFullScreen(fullScreen); }; }); } } }; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); registerReceiver(mReceiver, sIntentFilter); } @Override public void onUserInteraction() { super.onUserInteraction(); sendReturnFromFullScreen(); } @Override public void onBackPressed() { super.onBackPressed(); sendReturnFromFullScreen(); } @Override protected void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); } void sendReturnFromFullScreen() { if (!isFinishing()) { Intent i = new Intent(this, PlayerService.class); i.setAction(PlayerService.ACTION_RETURN_FROM_FULLSCREEN); startService(i); finish(); overridePendingTransition(0, 0); } } public void setFullScreen(boolean fullscreen) { int FS_FLAGS = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE; View view = getWindow().getDecorView(); int systemUiVisibility = view.getSystemUiVisibility(); if (fullscreen) { systemUiVisibility |= FS_FLAGS; } else { systemUiVisibility &= ~FS_FLAGS; } view.setSystemUiVisibility(systemUiVisibility); } }
true
920e3e801a68b335ee84580997b9cc356ae71a7c
Java
ABolikov/org.avbolikov.shop
/shop-pictures-service/src/main/java/org/avbolikov/shop/service/PictureService.java
UTF-8
346
1.789063
2
[ "Apache-2.0" ]
permissive
package org.avbolikov.shop.service; import org.avbolikov.shop.entity.pictures.PictureData; import java.util.Optional; public interface PictureService { Optional<String> getPictureContentTypeById(int id); Optional<byte[]> getPictureDataById(int id); PictureData createPictureData(byte[] picture); void delete(Integer id); }
true
9a79107f5f8f647b4191e746a2e6c367c012cc15
Java
mittulmandhan/java-interview-prep
/51 Collection/collection-codes/src/main/java/set/treeset/example6/TrainSourceComparator.java
UTF-8
237
2.6875
3
[]
no_license
package set.treeset.example6; import java.util.Comparator; public class TrainSourceComparator implements Comparator<Train>{ @Override public int compare(Train t1, Train t2) { return t1.getSource().compareTo(t2.getSource()); } }
true
6ff581170e69d9ce2d181de3b8a88f618b7b8ef8
Java
mengdongya/NoHttpOzner
/app/src/main/java/com/mdy/nohttpozner/commant/OznerPreference.java
UTF-8
1,308
2.296875
2
[]
no_license
package com.mdy.nohttpozner.commant; import android.content.Context; import android.content.SharedPreferences; /** * Created by cecha on 2016/11/29. */ public class OznerPreference { public static final String Ozner = "Ozner"; public final static String ServerAddress = "serveraddress"; private static SharedPreferences Init(Context context) { if (context != null) return context.getSharedPreferences(Ozner, Context.MODE_PRIVATE); else return null; } private static SharedPreferences.Editor InitEditor(Context context) { if (context != null) return context.getSharedPreferences(Ozner, Context.MODE_PRIVATE).edit(); else return null; } public static String serverAddr(Context context) { SharedPreferences sh = OznerPreference.Init(context); if (sh != null) { if (sh.getString(ServerAddress, null) == null) { SharedPreferences.Editor editor = InitEditor(context); editor.putString(ServerAddress, "http://app.ozner.net:888/"); return "http://app.ozner.net:888/"; } else { return sh.getString(ServerAddress, null); } } return "http://app.ozner.net:888/"; } }
true
68aa195e8f0c184fc7ea3145a25ff42ceb67d502
Java
univas/2021-lab3
/aula-15/src/br/edu/univas/controller/LoginController.java
UTF-8
638
2.625
3
[]
no_license
package br.edu.univas.controller; import br.edu.univas.exception.CheckedLoginException; import br.edu.univas.exception.UncheckedLoginException; import br.edu.univas.model.User; public class LoginController { public void login(User user) throws CheckedLoginException { if (!user.getEmail().equals("admin") || !user.getPassword().equals("admin")) { throw new CheckedLoginException("Usuário/Senha incorretos!"); } } public void login2(User user) { if (!user.getEmail().equals("admin") || !user.getPassword().equals("admin")) { throw new UncheckedLoginException("Usuário/Senha incorretos!"); } } }
true
0ecafa3ba60d3d52e56f3b8fc5c2e605f40968eb
Java
RedkinV/java2
/dz1_Vladimir_Redkin_Cross/Dog.java
UTF-8
144
2.296875
2
[]
no_license
package ru.geekbrains.java2.lesson1; public class Dog extends Animal { public Dog(String name) { super(name, 10, 300, 2); } }
true
704ad88e8892e4ebb791c45cd015cdef94c43a40
Java
ankurcdoshi/Criteria-Parser
/app/src/main/java/com/mp/criteriaparser/source/ScanListRepository.java
UTF-8
2,293
2.28125
2
[]
no_license
package com.mp.criteriaparser.source; import android.util.Log; import com.mp.criteriaparser.CriteriaParserApp; import com.mp.criteriaparser.interfaces.mvp.ScanListDataSource; import com.mp.criteriaparser.model.Scan; import com.mp.criteriaparser.network.NetworkInterface; import java.util.List; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; public class ScanListRepository implements ScanListDataSource { private static final String TAG = ScanListRepository.class.getSimpleName(); private static ScanListRepository scanListRepository; private List<Scan> scanList; private ScanListRepository() { } public static ScanListRepository getInstance() { if (scanListRepository == null) { synchronized (ScanListRepository.class) { if (scanListRepository == null) { scanListRepository = new ScanListRepository(); } } } return scanListRepository; } @Override public void loadScans(LoadScansCallback loadScansCallback) { getObservable().subscribeWith(getObserver(loadScansCallback)); } private Observable<List<Scan>> getObservable() { return CriteriaParserApp.getRetrofitInstance().create(NetworkInterface.class) .getScanList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } private Observer<List<Scan>> getObserver(final LoadScansCallback loadScansCallback) { return new DisposableObserver<List<Scan>>() { @Override public void onNext(List<Scan> scans) { ScanListRepository.this.scanList = scans; loadScansCallback.onScansLoaded(scanList); } @Override public void onError(@NonNull Throwable e) { e.printStackTrace(); loadScansCallback.onError(); } @Override public void onComplete() { loadScansCallback.onComplete(); } }; } }
true
445a11799b75b99fcc59c3e8ad8969f232d7d712
Java
JavaSking/SourceForJavaPattern
/src/创建模式/工厂模式/简单工厂模式SimpleFactory/Product.java
GB18030
176
2
2
[]
no_license
package ģʽ.ģʽ.򵥹ģʽSimpleFactory; /** * Ʒӿڡ * * @author JavaSking * 2017113 */ public interface Product { }
true
780172d05a2f7733c2b3d04be5b0450633c11b05
Java
vishal230400/Coding-Solutions
/src/com/vishal/codeforces/Q116/Q116A/Solution116A.java
UTF-8
477
2.828125
3
[ "MIT" ]
permissive
package com.vishal.codeforces.Q116.Q116A; import java.util.*; public class Solution116A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int max=0,count=0; while(n--!=0) { int a=sc.nextInt(); int b=sc.nextInt(); count=count+b-a; max=Math.max(max,count); } System.out.println(max); sc.close(); } }
true
df31de36ca567b3eb4d4bf8a19bfea9a15dc31f6
Java
shrimantanu/Java_Projects
/school management/mainpr/src/newpackage/FourWay.java
UTF-8
10,802
2.3125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * FourWay.java * * Created on Nov 11, 2013, 11:40:05 AM */ package newpackage; /** * * @author USER2 */ public class FourWay extends javax.swing.JFrame { static int jk = 0; /** Creates new form FourWay */ public FourWay() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLayeredPane1 = new javax.swing.JLayeredPane(); l2 = new javax.swing.JLabel(); l3 = new javax.swing.JLabel(); l4 = new javax.swing.JLabel(); j3 = new javax.swing.JLabel(); j4 = new javax.swing.JLabel(); j5 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Information"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); l2.setFont(new java.awt.Font("Tempus Sans ITC", 1, 12)); l2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpr/teacher-icon.gif"))); // NOI18N l2.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); l2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { l2MouseClicked(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { l2MouseExited(evt); } }); l2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { l2MouseMoved(evt); } }); l2.setBounds(380, 90, 94, 98); jLayeredPane1.add(l2, javax.swing.JLayeredPane.PALETTE_LAYER); l3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 12)); l3.setForeground(new java.awt.Color(51, 51, 51)); l3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpr/Delete Teacher.jpeg"))); // NOI18N l3.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); l3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { l3MouseClicked(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { l3MouseExited(evt); } }); l3.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { l3MouseMoved(evt); } }); l3.setBounds(370, 240, 102, 114); jLayeredPane1.add(l3, javax.swing.JLayeredPane.PALETTE_LAYER); l4.setFont(new java.awt.Font("Tempus Sans ITC", 1, 12)); l4.setForeground(new java.awt.Color(51, 51, 51)); l4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpr/Search.jpeg"))); // NOI18N l4.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); l4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { l4MouseClicked(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { l4MouseExited(evt); } }); l4.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { l4MouseMoved(evt); } }); l4.setBounds(390, 400, 82, 109); jLayeredPane1.add(l4, javax.swing.JLayeredPane.PALETTE_LAYER); j3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); j3.setForeground(new java.awt.Color(0, 153, 204)); j3.setText("Save"); j3.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { j3MouseMoved(evt); } }); j3.setBounds(550, 110, 80, 60); jLayeredPane1.add(j3, javax.swing.JLayeredPane.PALETTE_LAYER); j4.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); j4.setForeground(new java.awt.Color(0, 153, 204)); j4.setText("Delete"); j4.setBounds(540, 240, 80, 110); jLayeredPane1.add(j4, javax.swing.JLayeredPane.PALETTE_LAYER); j5.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); j5.setForeground(new java.awt.Color(0, 153, 204)); j5.setText("Search"); j5.setBounds(540, 390, 80, 110); jLayeredPane1.add(j5, javax.swing.JLayeredPane.PALETTE_LAYER); jLabel3.setForeground(new java.awt.Color(0, 153, 204)); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpr/ghjk.jpg"))); // NOI18N jLabel3.setBounds(0, 0, 830, 600); jLayeredPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER); jLabel5.setText("jLabel5"); jLabel5.setBounds(210, 250, 70, 30); jLayeredPane1.add(jLabel5, javax.swing.JLayeredPane.DEFAULT_LAYER); jLabel18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mainpr/tyu.PNG"))); // NOI18N jLabel18.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabel18.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel18MouseClicked(evt); } }); jLabel18.setBounds(670, 20, 80, 72); jLayeredPane1.add(jLabel18, javax.swing.JLayeredPane.PALETTE_LAYER); jLabel25.setIcon(new javax.swing.ImageIcon(getClass().getResource("/newpackage/BACK.png"))); // NOI18N jLabel25.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel25MouseClicked(evt); } }); jLabel25.setBounds(170, 380, 140, 120); jLayeredPane1.add(jLabel25, javax.swing.JLayeredPane.MODAL_LAYER); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 772, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void l2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l2MouseClicked jk = 0; new mainframe().setVisible(true); this.dispose(); }//GEN-LAST:event_l2MouseClicked private void l3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l3MouseClicked jk = 1; new mainframe().setVisible(true); this.dispose(); }//GEN-LAST:event_l3MouseClicked private void l4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l4MouseClicked jk = 2; new mainframe().setVisible(true); }//GEN-LAST:event_l4MouseClicked private void j3MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_j3MouseMoved // TODO add your handling code here: }//GEN-LAST:event_j3MouseMoved private void l2MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l2MouseMoved j3.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_l2MouseMoved private void l3MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l3MouseMoved j4.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_l3MouseMoved private void l4MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l4MouseMoved j5.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_l4MouseMoved private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated j3.setVisible(false); j4.setVisible(false); j5.setVisible(false); }//GEN-LAST:event_formWindowActivated private void l2MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l2MouseExited j3.setVisible(false); // TODO add your handling code here: }//GEN-LAST:event_l2MouseExited private void l3MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l3MouseExited j4.setVisible(false); // TODO add your handling code here: }//GEN-LAST:event_l3MouseExited private void l4MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_l4MouseExited j5.setVisible(false); // TODO add your handling code here: }//GEN-LAST:event_l4MouseExited private void jLabel18MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel18MouseClicked new ssi().setVisible(true); this.dispose(); }//GEN-LAST:event_jLabel18MouseClicked private void jLabel25MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel25MouseClicked new mainfourway().setVisible(true); this.dispose(); }//GEN-LAST:event_jLabel25MouseClicked public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FourWay().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel j3; private javax.swing.JLabel j4; private javax.swing.JLabel j5; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLayeredPane jLayeredPane1; private javax.swing.JLabel l2; private javax.swing.JLabel l3; private javax.swing.JLabel l4; // End of variables declaration//GEN-END:variables }
true
76115731270e31145cbd76d2e53ccc5451ad3cdc
Java
abhijeet-yahoo/jewels
/src/main/java/com/jiyasoft/jewelplus/controller/manufacturing/masters/StyleChangeController.java
UTF-8
3,714
2.109375
2
[]
no_license
package com.jiyasoft.jewelplus.controller.manufacturing.masters; import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; 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.bind.annotation.ResponseBody; import com.jiyasoft.jewelplus.domain.manufacturing.masters.Design; import com.jiyasoft.jewelplus.domain.manufacturing.masters.StyleChange; import com.jiyasoft.jewelplus.service.manufacturing.masters.IDesignService; import com.jiyasoft.jewelplus.service.manufacturing.masters.IStyleChangeService; @RequestMapping("/manufacturing/masters") @Controller public class StyleChangeController { @Autowired private IDesignService designService; @Autowired private IStyleChangeService styleChangeService; @ModelAttribute public Design constructDesign() { return new Design(); } @ModelAttribute public StyleChange constructStyle() { return new StyleChange(); } @RequestMapping("/styleChange") public String styleChangeMap() { return "styleChange"; } @ResponseBody @RequestMapping(value = "/styleChange/add" , method = RequestMethod.POST) public String addStyleChange(@ModelAttribute("styleChange") StyleChange styleChange, Principal principal){ String retVal = "-1"; Design design = designService.findByDesignNoAndDeactive(styleChange.getDesignNo().trim(),false); if(design != null){ Design design2 = designService.findByStyleNoAndVersion(styleChange.getNewStyleNo().trim(), design.getVersion()); if(design2 != null){ return retVal = "-2"; }else{ design.setStyleNo(styleChange.getNewStyleNo()); design.setModiBy(principal.getName()); design.setModiDt(new java.util.Date()); designService.save(design); StyleChange styleChangeOldRecord = styleChangeService.findByDesign(design); if(styleChangeOldRecord != null){ styleChangeOldRecord.setOldStyleNo(styleChangeOldRecord.getNewStyleNo()); styleChangeOldRecord.setNewStyleNo(styleChange.getNewStyleNo().trim()); styleChangeOldRecord.setDesignNo(styleChange.getDesignNo().trim()); styleChangeOldRecord.setModiBy(principal.getName()); styleChangeOldRecord.setModiDate(new java.util.Date()); styleChangeService.save(styleChangeOldRecord); }else{ styleChange.setDesign(design); styleChange.setCreatedBy(principal.getName()); styleChange.setCreatedDate(new java.util.Date()); styleChangeService.save(styleChange); } } }else{ return retVal = "-3"; } // ending main if-else return retVal; } @RequestMapping("/designNo/forStyleChangeModel") @ResponseBody public String styleNoList(@RequestParam(value = "term", required = false) String designNo) { Page<Design> designList = designService.findByDesignNo(15, 0, "designNo", "ASC", designNo.toUpperCase(), true); StringBuilder sb = new StringBuilder(); for (Design design : designList) { sb.append("\"") .append(design.getDesignNo()) .append("\", "); } String str = "[" + sb.toString().trim(); str = (str.lastIndexOf(",") != -1 ? str.substring(0, str.length() - 1) : str); str += "]"; return str; } }
true
b2afb4b810b2109e312a67dae50ff71ee7384ae1
Java
GPC-debug/hysz
/src/main/java/com/hykj/hysz/entity/data/AccountingSubject.java
UTF-8
1,371
1.984375
2
[]
no_license
package com.hykj.hysz.entity.data; import java.math.BigInteger; import java.util.*; import java.io.Serializable; import javax.persistence.*; import lombok.Data; /** * AccountingSubject Bean * @date 2019-8-28 * @author Jiameng.Ren * */ @Data @Entity @Table(name="accounting_subject") public class AccountingSubject implements Serializable{ private static final long serialVersionUID = 1L; @Id @Column(name="accounting_subject_id") private Integer accountingSubjectId; @Column(name="accounting_subject_name") private String accountingSubjectName; @Column(name="mnemonic_code") private String mnemonicCode; @Column(name="accounting_subject_full_name") private String accountingSubjectFullName; @Column(name="accounting_subject_parentid") private Integer accountingSubjectParentId; @Column(name="is_leaf") private Integer isLeaf; @Column(name="subject_nature") private Integer subjectNature; @Column(name="subject_type_id") private Integer subjectTypeId; @Column(name="hierarchy") private Integer hierarchy; @Column(name="sort") private Integer sort; @Column(name="status") private Integer status; @Column(name="create_time") private Date createTime; @Column(name="upd_time") private Date updTime; @Column(name="create_man") private String createMan; @Column(name="upd_man") private String updMan; }
true
0db2f2db71f874f40c8d54396ad70e4a2f4ff4c7
Java
liuendy/escommons
/core/src/test/java/org/biacode/escommons/core/component/impl/AliasNameGenerationComponentImplTest.java
UTF-8
2,448
2.125
2
[ "MIT" ]
permissive
package org.biacode.escommons.core.component.impl; import org.biacode.escommons.core.component.ClockComponent; import org.biacode.escommons.core.component.IndexNameGenerationComponent; import org.biacode.escommons.core.test.AbstractCoreUnitTest; import org.easymock.Mock; import org.easymock.TestSubject; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.junit.Test; import java.util.UUID; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Created by Arthur Asatryan. * Date: 7/14/17 * Time: 5:07 PM */ public class AliasNameGenerationComponentImplTest extends AbstractCoreUnitTest { //region Test subject and mocks @TestSubject private IndexNameGenerationComponent indexNameGenerationComponent = new IndexNameGenerationComponentImpl(); @Mock private ClockComponent clockComponent; //endregion //region Constructors public AliasNameGenerationComponentImplTest() { } //endregion //region Test subject and mocks @Test public void testGenerateNameForGivenIndexWithInvalidArguments() { // Test data // Reset resetAll(); // Expectations // Replay replayAll(); // Run test scenario try { indexNameGenerationComponent.generateNameForGivenIndex(null); fail("Exception should be thrown"); } catch (final IllegalArgumentException ex) { // Expected } // Verify verifyAll(); } @Test public void testGenerateNameForGivenIndex() { // Test data final String currentDateString = printCurrentDate(); final String aliasName = UUID.randomUUID().toString(); // Reset resetAll(); // Expectations expect(clockComponent.printCurrentDateTimeWithPredefinedFormatter()).andReturn(currentDateString); // Replay replayAll(); // Run test scenario final String result = indexNameGenerationComponent.generateNameForGivenIndex(aliasName); // Verify verifyAll(); assertTrue(result.startsWith(aliasName + "_date_" + currentDateString + "_uuid_")); } //endregion //region Utility methods private String printCurrentDate() { return DateTimeFormat.forPattern("yyyy_MM_dd_HH_mm_ss_SSS").print(DateTime.now()); } //endregion }
true
5dc8ef86c012e8d565bfa5e0cec9d256c64e9722
Java
silvano-pessoa/ArquiteturaPrimefaces
/java_src/br/com/silvanopessoa/dao/IFuncionarioDAO.java
UTF-8
1,220
2.15625
2
[]
no_license
package br.com.silvanopessoa.dao; import java.util.List; import br.com.silvanopessoa.exception.java.BusinessMessageException; import br.com.silvanopessoa.model.entity.Funcionario; public interface IFuncionarioDAO { /** * @param entity */ void save(Funcionario entity); /** * @param entity */ void update(Funcionario entity); /** * @param entity */ public void delete(Funcionario entity); /** * @return */ public List<Funcionario> findAll(); /** * @param id * @return */ public Funcionario findById(int id); /** * @param entity * @return * @throws BusinessMessageException */ public List<Funcionario> find(Funcionario entity); /** * @param entity * @return */ public boolean hasDuplicidade(Funcionario entity); /** * @param user * @return */ public Funcionario getByUser(String user); /** * @param entity * @return */ public List<Funcionario> findBySuperior(Funcionario entity); /** * @param nome * @return */ public Funcionario findByNome(String nome); /** * @param cliId * @return */ List<Funcionario> findBySiteCliente(int cliId); /** * @param sitId * @return */ List<Funcionario> findBySite(int sitId); }
true
f82d8a8b7b925785dfe183c818b65dce46095fdf
Java
ducquanbn/Qsport
/QSport/src/main/java/Services/HoaDonSer.java
UTF-8
1,264
1.890625
2
[]
no_license
package Services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import DAO.HoaDonDao; import Entity.HoaDon; import Implements.HoaDonImp; @Service public class HoaDonSer implements HoaDonImp{ @Autowired HoaDonDao hoaDonDao; public boolean ThemHoaDon(HoaDon hoaDon) { return hoaDonDao.ThemHoaDon(hoaDon); } public List<HoaDon> lstHoaDon() { // TODO Auto-generated method stub return hoaDonDao.lstHoaDon(); } public List<HoaDon> TimKiemTheoUser(int idTaiKhoan) { // TODO Auto-generated method stub return hoaDonDao.TimKiemTheoUser(idTaiKhoan); } public List<HoaDon> TimKiemTheoSDT(String sdt) { // TODO Auto-generated method stub return hoaDonDao.TimKiemTheoSDT(sdt); } public List<HoaDon> TimKiemTheoNgayDat(String ngayBD, String ngayKT) { // TODO Auto-generated method stub return hoaDonDao.TimKiemTheoNgayDat(ngayBD, ngayKT); } public HoaDon showHD(int idHoaDon) { // TODO Auto-generated method stub return hoaDonDao.showHD(idHoaDon); } public String updateHD(int idHoaDon, Boolean TinhTrang) { // TODO Auto-generated method stub return hoaDonDao.updateHD(idHoaDon, TinhTrang); } }
true
e8878553743db9b8a3c1db2771ea89bc4a78d90d
Java
lowgear/SnakeGame
/src/ru/snake_game/model/Interfaces/IFieldObject.java
UTF-8
205
1.875
2
[]
no_license
package ru.snake_game.model.Interfaces; import ru.snake_game.model.util.Location; public interface IFieldObject { Location getLocation(); void snakeInteract(ISnakeHead snake); void act(); }
true
05ba1920af0f0845424229dfa1ee74ac443ba9b1
Java
xhzxhzxhz/bzc
/src/main/java/com/folkestone/bzcx/common/util/ConvertUtil.java
UTF-8
733
2.71875
3
[]
no_license
package com.folkestone.bzcx.common.util; import java.lang.reflect.Field; /** * Describe:将Vo转成Do * * @author smallking * * 2017年10月31日 */ public class ConvertUtil { public static void convert(Object voObj, Object doObj) throws IllegalArgumentException, IllegalAccessException { Field[] voFields = voObj.getClass().getDeclaredFields(); Field[] doFields = doObj.getClass().getDeclaredFields(); for(Field voField : voFields) { voField.setAccessible(true); for(Field doField : doFields){ doField.setAccessible(true); if(doField.getName().equals(voField.getName()) && voField.get(voObj) != null){ doField.set(doObj, voField.get(voObj)); } } } } }
true
cb388625f7762cefdf2582adbe34a0cc264e9fba
Java
apache/jackrabbit-oak
/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedTransformTask.java
UTF-8
12,762
1.664063
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined; import com.mongodb.BasicDBObject; import org.apache.commons.io.FileUtils; import org.apache.jackrabbit.guava.common.base.Stopwatch; import org.apache.jackrabbit.oak.index.indexer.document.NodeStateEntry; import org.apache.jackrabbit.oak.index.indexer.document.flatfile.NodeStateEntryWriter; import org.apache.jackrabbit.oak.plugins.document.Collection; import org.apache.jackrabbit.oak.plugins.document.Document; import org.apache.jackrabbit.oak.plugins.document.DocumentNodeState; import org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore; import org.apache.jackrabbit.oak.plugins.document.NodeDocument; import org.apache.jackrabbit.oak.plugins.document.Path; import org.apache.jackrabbit.oak.plugins.document.RevisionVector; import org.apache.jackrabbit.oak.plugins.document.cache.NodeDocumentCache; import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore; import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStoreHelper; import org.apache.jackrabbit.oak.spi.state.NodeStateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined.PipelinedStrategy.SENTINEL_MONGO_DOCUMENT; /** * Receives batches of Mongo documents, converts them to node state entries, batches them in a {@link NodeStateEntryBatch} * buffer and when the buffer is full, passes the buffer to the sort-and-save task. */ class PipelinedTransformTask implements Callable<PipelinedTransformTask.Result> { public static class Result { private final int transformThreadId; private final long entryCount; public Result(int threadId, long entryCount) { this.transformThreadId = threadId; this.entryCount = entryCount; } public long getEntryCount() { return entryCount; } public int getThreadId() { return transformThreadId; } } private static final Logger LOG = LoggerFactory.getLogger(PipelinedTransformTask.class); private static final AtomicInteger threadIdGenerator = new AtomicInteger(); private final MongoDocumentStore mongoStore; private final DocumentNodeStore documentNodeStore; private final RevisionVector rootRevision; private final Collection<NodeDocument> collection; private final NodeStateEntryWriter entryWriter; private final Predicate<String> pathPredicate; // Input queue private final ArrayBlockingQueue<BasicDBObject[]> mongoDocQueue; // Output queue private final ArrayBlockingQueue<NodeStateEntryBatch> nonEmptyBatchesQueue; // Queue with empty (recycled) buffers private final ArrayBlockingQueue<NodeStateEntryBatch> emptyBatchesQueue; private final TransformStageStatistics statistics; private final int threadId = threadIdGenerator.getAndIncrement(); private long totalEnqueueWaitTimeMillis = 0; public PipelinedTransformTask(MongoDocumentStore mongoStore, DocumentNodeStore documentNodeStore, Collection<NodeDocument> collection, RevisionVector rootRevision, Predicate<String> pathPredicate, NodeStateEntryWriter entryWriter, ArrayBlockingQueue<BasicDBObject[]> mongoDocQueue, ArrayBlockingQueue<NodeStateEntryBatch> emptyBatchesQueue, ArrayBlockingQueue<NodeStateEntryBatch> nonEmptyBatchesQueue, TransformStageStatistics statsCollector) { this.mongoStore = mongoStore; this.documentNodeStore = documentNodeStore; this.collection = collection; this.rootRevision = rootRevision; this.pathPredicate = pathPredicate; this.entryWriter = entryWriter; this.mongoDocQueue = mongoDocQueue; this.emptyBatchesQueue = emptyBatchesQueue; this.nonEmptyBatchesQueue = nonEmptyBatchesQueue; this.statistics = statsCollector; } @Override public Result call() throws Exception { String originalName = Thread.currentThread().getName(); Thread.currentThread().setName("mongo-transform-" + threadId); try { LOG.info("Starting transform task"); NodeDocumentCache nodeCache = MongoDocumentStoreHelper.getNodeDocumentCache(mongoStore); Stopwatch taskStartWatch = Stopwatch.createStarted(); long totalEntryCount = 0; long mongoObjectsProcessed = 0; LOG.info("Waiting for an empty buffer"); NodeStateEntryBatch nseBatch = emptyBatchesQueue.take(); // Used to serialize a node state entry before writing it to the buffer ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); OutputStreamWriter writer = new OutputStreamWriter(baos, PipelinedStrategy.FLATFILESTORE_CHARSET); LOG.info("Obtained an empty buffer. Starting to convert Mongo documents to node state entries"); while (true) { BasicDBObject[] dbObjectBatch = mongoDocQueue.take(); if (dbObjectBatch == SENTINEL_MONGO_DOCUMENT) { LOG.info("Task terminating. Dumped {} nodestates in json format in {}. Total enqueue delay: {} ms ({}%)", totalEntryCount, taskStartWatch, totalEnqueueWaitTimeMillis, String.format("%1.2f", (100.0 * totalEnqueueWaitTimeMillis) / taskStartWatch.elapsed(TimeUnit.MILLISECONDS))); //Save the last batch nseBatch.getBuffer().flip(); tryEnqueue(nseBatch); return new Result(threadId, totalEntryCount); } else { for (BasicDBObject dbObject : dbObjectBatch) { statistics.incrementMongoDocumentsProcessed(); mongoObjectsProcessed++; if (mongoObjectsProcessed % 50000 == 0) { LOG.info("Mongo objects: {}, total entries: {}, current batch: {}, Size: {}/{} MB", mongoObjectsProcessed, totalEntryCount, nseBatch.numberOfEntries(), nseBatch.sizeOfEntries() / FileUtils.ONE_MB, nseBatch.capacity() / FileUtils.ONE_MB ); } //TODO Review the cache update approach where tracker has to track *all* docs NodeDocument nodeDoc = MongoDocumentStoreHelper.convertFromDBObject(mongoStore, collection, dbObject); // TODO: should we cache splitDocuments? Maybe this can be moved to after the check for split document nodeCache.put(nodeDoc); if (nodeDoc.isSplitDocument()) { statistics.addSplitDocument(dbObject.getString(Document.ID)); } else { List<NodeStateEntry> entries = getEntries(nodeDoc); if (entries.isEmpty()) { statistics.addEmptyNodeStateEntry(dbObject.getString(Document.ID)); } for (NodeStateEntry nse : entries) { String path = nse.getPath(); if (!NodeStateUtils.isHiddenPath(path) && pathPredicate.test(path)) { statistics.incrementEntriesAccepted(); totalEntryCount++; // Serialize entry entryWriter.writeTo(writer, nse); writer.flush(); byte[] entryData = baos.toByteArray(); baos.reset(); statistics.incrementTotalExtractedEntriesSize(entryData.length); if (!nseBatch.hasSpaceForEntry(entryData)) { LOG.info("Buffer full, passing buffer to sort task. Total entries: {}, entries in buffer {}, buffer size: {}", totalEntryCount, nseBatch.numberOfEntries(), nseBatch.sizeOfEntries()); nseBatch.flip(); tryEnqueue(nseBatch); // Get an empty buffer nseBatch = emptyBatchesQueue.take(); } // Write entry to buffer nseBatch.addEntry(nse.getPath(), entryData); } else { statistics.incrementEntriesRejected(); if (NodeStateUtils.isHiddenPath(path)) { statistics.addRejectedHiddenPath(path); } if (!pathPredicate.test(path)) { statistics.addRejectedFilteredPath(path); } } } } } } } } catch (InterruptedException t) { LOG.warn("Thread interrupted", t); throw t; } catch (Throwable t) { LOG.warn("Thread terminating with exception.", t); throw t; } finally { Thread.currentThread().setName(originalName); } } private void tryEnqueue(NodeStateEntryBatch nseBatch) throws InterruptedException { Stopwatch stopwatch = Stopwatch.createStarted(); nonEmptyBatchesQueue.put(nseBatch); long enqueueDelay = stopwatch.elapsed(TimeUnit.MILLISECONDS); totalEnqueueWaitTimeMillis += enqueueDelay; if (enqueueDelay > 1) { LOG.info("Enqueuing of node state entries batch was delayed, took {} ms. nonEmptyBatchesQueue size {}. ", enqueueDelay, nonEmptyBatchesQueue.size()); } } private List<NodeStateEntry> getEntries(NodeDocument doc) { Path path = doc.getPath(); DocumentNodeState nodeState = documentNodeStore.getNode(path, rootRevision); //At DocumentNodeState api level the nodeState can be null if (nodeState == null || !nodeState.exists()) { return List.of(); } ArrayList<NodeStateEntry> nodeStateEntries = new ArrayList<>(2); nodeStateEntries.add(toNodeStateEntry(doc, nodeState)); for (DocumentNodeState dns : nodeState.getAllBundledNodesStates()) { nodeStateEntries.add(toNodeStateEntry(doc, dns)); } return nodeStateEntries; } private NodeStateEntry toNodeStateEntry(NodeDocument doc, DocumentNodeState dns) { NodeStateEntry.NodeStateEntryBuilder builder = new NodeStateEntry.NodeStateEntryBuilder(dns, dns.getPath().toString()); if (doc.getModified() != null) { builder.withLastModified(doc.getModified()); } builder.withID(doc.getId()); return builder.build(); } }
true
70ad712da52ff5d268fa6410d97a215daae91107
Java
quangle2020/spring-boot
/src/main/java/com/quanglv/service/impl/CustomUserDetailsService.java
UTF-8
1,149
2.046875
2
[]
no_license
package com.quanglv.service.impl; import com.quanglv.constant.AppConstant; import com.quanglv.domain.Users; import com.quanglv.repository.UsersRepository; import com.quanglv.service.dto.UserPrincipalOauth2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service(value = "userCustomService") public class CustomUserDetailsService implements UserDetailsService { @Autowired private UsersRepository usersRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Users userEntity = usersRepository.findOneByUsernameAndStatus(username, AppConstant.STATUS.ACTIVE_STATUS); if (userEntity == null) { throw new UsernameNotFoundException("User not found"); } return UserPrincipalOauth2.createPrincipalOauth2(userEntity); } }
true
124926f3735a604f2173b74952358cbcde8ca9a0
Java
TubaBee/JavaProgrammer
/src/com/class36/Recap.java
UTF-8
1,639
3.578125
4
[]
no_license
package com.class36; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Recap { public static void main(String[] args) { //Create a Map of grocaries that will store product and it is quantities and we want to maintain the insetion order for keys // Map<K, V> variableName=new MapChildObject<>(); Map<String, Integer> groceryMap=new HashMap<>(); groceryMap.put("Milk", 2); groceryMap.put("Tea", 3); groceryMap.put("Onion", 5); groceryMap.put("Apple", 10); //retrieve single value groceryMap.get("Apple"); //verify if specific key or value is in the map groceryMap.containsKey("Milk"); groceryMap.containsValue(2); //how to retrieve all values? Collection<Integer> values=groceryMap.values(); for(Integer val: values){ System.out.println(val); } Iterator<Integer> valIt=values.iterator(); while(valIt.hasNext()){ System.out.println(valIt.next()); } //get all keys map them to values (milk --> 2) //Set<String> keys=groceryMap.keySet();//eger bunu yapmazsak for(String k:groceryMap.keySet()) { System.out.println(k.toUpperCase()+"-->"+groceryMap.get(k)); } Iterator<String> kIt=groceryMap.keySet().iterator(); while(kIt.hasNext()) { System.out.println(kIt.next().toLowerCase()+"-->"+groceryMap.get(kIt.next())); } //get all keys and map them to values (milk -->2)using entrySet Set<Entry<String, Integer>> entr=groceryMap.entrySet(); for(Entry<String,Integer> e: entr) { System.out.println(e.getKey()+"==>"+ e.getValue()); } } }
true
1ec5a16e96ad3db9e5829bd4bccf21017c952d97
Java
cliicy/autoupdate
/Central/Server/EdgeAppBaseServiceImpl/src/com/ca/arcserve/edge/app/base/webservice/node/HeartBeatJob.java
UTF-8
3,055
2.140625
2
[]
no_license
package com.ca.arcserve.edge.app.base.webservice.node; import javax.xml.ws.WebServiceException; import javax.xml.ws.soap.SOAPFaultException; import org.apache.log4j.Logger; import com.ca.arcserve.edge.app.base.schedulers.EdgeExecutors; import com.ca.arcserve.edge.app.base.util.EdgeCMWebServiceMessages; import com.ca.arcserve.edge.app.base.webservice.INodeService; import com.ca.arcserve.edge.app.base.webservice.contract.log.Module; import com.ca.arcserve.edge.app.base.webservice.contract.log.Severity; import com.ca.arcserve.edge.app.base.webservice.contract.node.NodeDetail; public abstract class HeartBeatJob extends BaseJob{ private static final Logger logger = Logger.getLogger(HeartBeatJob.class); protected INodeService nodeService; public void changeHeartBeatStatus(final boolean enabled){ Runnable task = new Runnable(){ @Override public void run() { logger.debug("change heart beat status begin..."); int[] nodeIDs = prepareNodeIDs(); for (int nodeID:nodeIDs){ NodeDetail nodeDetail = null; try{ nodeDetail = getNodeDetailWithPolicy(nodeService, nodeID); if (!nodeDetail.isVCMMonitee()) { continue; } VCMServiceManager.getInstance().changeHeartBeatStatus(nodeDetail, enabled); if (enabled) generateLog(Severity.Information, Module.VCMHeartBeat, nodeDetail, EdgeCMWebServiceMessages.getMessage("resumeHeartbeatSuccessfully")); else generateLog(Severity.Information, Module.VCMHeartBeat, nodeDetail, EdgeCMWebServiceMessages.getMessage("pauseHeartbeatSuccessfully")); }catch(SOAPFaultException e){ generateLog(Severity.Error, Module.VCMHeartBeat, nodeDetail, getD2DErrorMessage(e.getFault().getFaultCodeAsQName().getLocalPart())); }catch(WebServiceException e){ generateLog(Severity.Error, Module.VCMHeartBeat, nodeDetail, EdgeCMWebServiceMessages.getMessage("failedtoConnectMonitee", nodeDetail.getHostname())); }catch(Exception e){ generateLog(Severity.Error, Module.VCMHeartBeat, nodeDetail, EdgeCMWebServiceMessages.getMessage("failedToChangeHeartBeatJobStatus")); } } logger.debug("change heart beat status ends"); } }; EdgeExecutors.getCachedPool().submit(task); } protected abstract int[] prepareNodeIDs(); public static class HeartBeatJobForGroup extends HeartBeatJob{ private int groupID; private int groupType; public HeartBeatJobForGroup(INodeService nodeService, int groupID, int groupType){ this.nodeService = nodeService; this.groupID = groupID; this.groupType = groupType; } @Override protected int[] prepareNodeIDs() { return this.getNodeIDByGroup(nodeService, groupID, groupType); } } public static class HeartBeatJobForNodes extends HeartBeatJob{ private int[] nodeIDs; public HeartBeatJobForNodes(INodeService nodeService, int[] nodeIDs){ this.nodeService = nodeService; this.nodeIDs = nodeIDs; } @Override protected int[] prepareNodeIDs() { return nodeIDs; } } }
true
e0b0ec5439418de8048122bcf67772e94f412149
Java
Snoozy1995/Week-11-SDE-Design-Patterns-Assignment
/src/FacadeSingletonStrategy/dal/IDataAccessLayer.java
UTF-8
222
2.0625
2
[]
no_license
package FacadeSingletonStrategy.dal; import FacadeSingletonStrategy.be.Message; import java.util.List; public interface IDataAccessLayer { List<Message> getAllMessages(); void createAMessage(Message message); }
true
909004cd11db1eac7fc0947ea76507d439d0c1f1
Java
olentangyfrc/Steamworks2017
/src/org/usfirst/frc/team4611/robot/commands/SingleWheelShoot.java
UTF-8
800
2.25
2
[]
no_license
package org.usfirst.frc.team4611.robot.commands; import org.usfirst.frc.team4611.robot.Robot; import org.usfirst.frc.team4611.robot.RobotMap; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class SingleWheelShoot extends Command{ public SingleWheelShoot(){ //this.speed = inputSpeed; this.requires(Robot.sw); } protected void initialize() { } protected void execute() { //double targetSpeed = (SmartDashboard.getNumber("shoot speed", 0)); Robot.sw.shoot(RobotMap.singleShooterSpeed); } @Override protected boolean isFinished() { // TODO Auto-generated method stub return false; } protected void end() { Robot.sw.shoot(0); } protected void interrupted(){ this.end(); } }
true
db079062fcd85cda3614815602090addc2586f10
Java
jaydev07/DSA-in-java
/Linked List/myNode.java
UTF-8
133
2.359375
2
[]
no_license
public class myNode { int data; myNode next; myNode bottom; myNode(int d) { data = d; next = null; bottom = null; } }
true
ad427d38c6f9a167e1f2137589e0c42e258c94c3
Java
MatthijsKok/HackerGames-Backend
/src/main/java/com/hackergames/pizzas/services/FakePizzaService.java
UTF-8
1,271
2.40625
2
[]
no_license
package com.hackergames.pizzas.services; import com.hackergames.pizzas.model.PizzaOptions; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Fake pizza service simulating Domino's. */ @Service public final class FakePizzaService implements PizzaService { @Override public List<PizzaOptions> getAllPizzas() { final List<PizzaOptions> pizzas = new ArrayList<>(); try { final JSONObject menu = Requester.getRequest("https://hackathon-menu.dominos.cloud/", "/Rest/nl/menus/30544/en"); final JSONArray jPizzas = menu.getJSONArray("MenuPages").getJSONObject(0).getJSONArray("SubMenus"); for (int i = 0; i < jPizzas.length(); i++) { final JSONObject subMenu = jPizzas.getJSONObject(i); final JSONArray jProducts = subMenu.getJSONArray("Products"); for (int j = 0; j < jProducts.length(); j++) { pizzas.add(PizzaOptions.fromJson(jProducts.getJSONObject(j))); } } } catch (final IOException e) { e.printStackTrace(); } return pizzas; } }
true
369c10d14a2f5eb14a0ec4ec2f2ac79981ceb105
Java
youngseo9478/Web
/Web_Spring/5_Spring_IOC/src/main/java/tv/step3/SonySpeaker.java
UTF-8
247
2.828125
3
[]
no_license
package tv.step3; public class SonySpeaker implements Speaker{ @Override public void volumeUp() { System.out.println("SonySpeaker volume UP"); } @Override public void volumeDown() { System.out.println("SonySpeaker volume DOWN"); } }
true
3e3da0728d3db3832949d6ae982039f24f5a0362
Java
inviss/cms-jpa
/cms-jpa/src/main/java/kr/co/d2net/service/UserAuthServiceImpl.java
UTF-8
1,152
1.875
2
[]
no_license
package kr.co.d2net.service; import java.util.List; import kr.co.d2net.dao.UserAuthDao; import kr.co.d2net.dto.UserAuthTbl; import kr.co.d2net.exception.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("userAuthService") @Transactional(readOnly=true) public class UserAuthServiceImpl implements UserAuthServices{ @Autowired private UserAuthDao userAuthDao; @Override public List<Object[]> getAuthUseYn(String id) throws ServiceException { try { } catch (Exception e) { // TODO: handle exception } return null; } @Override public List<UserAuthTbl> getUserAuthObj(String userId) { try { } catch (Exception e) { // TODO: handle exception } return null; } @Override public long findUserAuthCount() throws ServiceException { try { } catch (Exception e) { // TODO: handle exception } return 0; } @Override public void add(UserAuthTbl user) throws ServiceException { try { } catch (Exception e) { // TODO: handle exception } } }
true
3e20ea55514135d998d501aab663410dda7a114a
Java
kangzisoo/Java-practice
/java12/src/배열심화/최대값찾기2.java
UTF-8
1,025
3.921875
4
[]
no_license
package 배열심화; import java.util.Random; public class 최대값찾기2 { public static void main(String[] args) { // 타입이 동일한 많은 양의 데이터가 있으면 배열에 넣으세요. // 반복을 통해서 많은 양의 데이터를 효율적으로 다룰 수 있음. int[] num = new int[1000]; Random r = new Random(); for (int i = 0; i < num.length; i++) { num[i] = r.nextInt(1000); } // int[] num = {11, 33, 55, 22, 44}; int max = num[0]; //오류를 방지한 초기화 방법.! int count = 0; String sum = ""; for (int i = 1; i < num.length; i++) { //0번(자기자긴)과는 비교할 필요 없으므로, i=1부터 시작하게 if (max == num[i]) { System.out.println("최대값 " + max); sum = sum + i + " "; count++; } } System.out.println("최대값의 개수: " + count); System.out.println("최대값의 위치: " + sum); String[] s = sum.split(" "); //비파괴 함수 System.out.println(s[0]); System.out.println(s[1]); } }
true
a7806c5a2a24c15f0a7e1739e2b299cdf53bb9fb
Java
ostigter/testproject3
/projectx/src/main/java/sr/projectx/entities/AppLogMessage.java
UTF-8
1,220
2.234375
2
[]
no_license
package sr.projectx.entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * Application log message. * * @author Oscar Stigter */ @Entity(name = "APP_LOG") public class AppLogMessage implements Serializable { private static final long serialVersionUID = -8235087123701916077L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Basic private Date date; @Basic private LogLevel level; @Basic private String message; public long getId() { return id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public LogLevel getLevel() { return level; } public void setLevel(LogLevel level) { this.level = level; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
true
bdb7169fc26b2e4dba88cb1084cde0aa1262bf85
Java
Nikkie-456/CodevillageSpring
/myapp/src/main/java/com/thecodevillage/myapp/models/AccCreateMul.java
UTF-8
354
1.992188
2
[]
no_license
package com.thecodevillage.myapp.models; import java.io.Serializable; import java.util.List; public class AccCreateMul implements Serializable { private List<Account> accounts; public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } }
true
2f320d26aad73b4043eb4c48d4aa56590b19c238
Java
jacknoerror/yftRepo
/src/com/qfc/yft/net/JackRequestManager.java
GB18030
1,626
2.515625
3
[]
no_license
package com.qfc.yft.net; import java.util.HashMap; import java.util.Map; import android.os.AsyncTask.Status; import android.util.Log; /** * mainly prevent requesting repeatedly * @author taotao * */ public class JackRequestManager { private final String TAG = JackRequestManager.class.getSimpleName(); private static JackRequestManager manager; private Map<String, Long> requestTimeMap; private Map<String, HttpRequestTask> requestTaskMap; private JackRequestManager(){ requestTimeMap = new HashMap<String, Long>(); requestTaskMap = new HashMap<String, HttpRequestTask>(); }; public static JackRequestManager getInstance(){ if(manager==null) manager= new JackRequestManager(); return manager; } public void tryRequest(String url,HttpReceiver receiver, long timeout){//TODO Log.i(TAG, "sure it works?"+url); HttpRequestTask rTask = requestTaskMap.get(url); if(rTask==null){ requestAnyway(url, receiver); }else if(rTask.getStatus()==Status.FINISHED){ long thatTime = requestTimeMap.get(url); long delTime =System.currentTimeMillis()-thatTime; Log.i(TAG , delTime+"::request deltime"); if(delTime>timeout){//һʱ requestAnyway(url, receiver); } } } public void tryRequest(String url,HttpReceiver receiver ){ tryRequest(url, receiver, 3000); } private void requestAnyway(String url,HttpReceiver receiver){ HttpRequestTask rTask = new HttpRequestTask(receiver); rTask.execute(url); requestTaskMap.put(url, rTask); requestTimeMap.put(url, System.currentTimeMillis()); } }
true
05fe68adef67bb45ef4547c995b05a336e83aede
Java
joanalbert/TestMod2
/src/main/java/net/fabricmc/example/entities/TestEntity/TestEntity.java
UTF-8
9,184
2.15625
2
[ "CC0-1.0" ]
permissive
package net.fabricmc.example.entities.TestEntity; import net.minecraft.entity.EntityType; import net.minecraft.entity.damage.DamageSource; import java.util.HashMap; import net.fabricmc.example.ExampleMod; import net.fabricmc.example.entities.ProjectileEntity.ProjectileEntity; import net.fabricmc.example.register.ParticleRegister; import net.fabricmc.example.register.SoundRegister; import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.block.Blocks; import net.minecraft.data.client.model.Texture; import net.minecraft.data.client.model.TextureKey; import net.minecraft.entity.Entity; import net.minecraft.entity.mob.PathAwareEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.FireballEntity; import net.minecraft.particle.ParticleEffect; import net.minecraft.particle.ParticleTypes; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import software.bernie.geckolib3.core.IAnimatable; import software.bernie.geckolib3.core.PlayState; import software.bernie.geckolib3.core.builder.AnimationBuilder; import software.bernie.geckolib3.core.controller.AnimationController; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.manager.AnimationData; import software.bernie.geckolib3.core.manager.AnimationFactory; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvent; /* * Our TestEntity extends PathAwareEntity, which extends MobEntity, which extends LivingEntity. * * LlivingEntity has health and can deal damage * MobEntity has movement controls and AI capabilities * PathAwareEntity has pathfinding favor and slightly tweaked leash behavior. */ public class TestEntity extends PathAwareEntity implements IAnimatable { private AnimationFactory factory = new AnimationFactory(this); // <- this is needed for geckolib public static final float TURRET_RANGE = 35f; //animation controller AnimationController main; AnimationController radar; //static field in which turretData from all instances of this entity is stored, then recovered public static HashMap<String, TurretData> turretInfo = new HashMap<String, TurretData>(); //turret data of each instance Vec3d target; Vec3d headRotations; Vec3d headPosition; Vec3d nozzlePosition; public TestEntity(EntityType<? extends PathAwareEntity> entityType, World world) { super(entityType, world); } @Override public boolean canMoveVoluntarily() { return true; } //when this turret dies, remove it's entry from turret info @Override public void onDeath(DamageSource source) { turretInfo.remove(this.getUuidAsString()); super.onDeath(source); } //so that the entity doesn't get randomly rotated upon egg spawn @Override public void refreshPositionAndAngles(double x, double y, double z, float yaw, float pitch) { super.refreshPositionAndAngles(x, y, z, 0f, 0f); } //METHODS FOR ANIMATION//////////////////////////// private <E extends IAnimatable> PlayState predicate(AnimationEvent<E> event){ if(target == null)event.getController().setAnimation(new AnimationBuilder().addAnimation("idle")); else event.getController().setAnimation(new AnimationBuilder().addAnimation("shoot")); return PlayState.CONTINUE; } private <E extends IAnimatable> PlayState predicate2(AnimationEvent<E> event){ event.getController().setAnimation(new AnimationBuilder().addAnimation("radar")); return PlayState.CONTINUE; } @Override public void tick() { //set turret data for this entity this.target = TurretDataHelper.getTarget(this.getUuidAsString()); this.headRotations = TurretDataHelper.getHeadRotation(this.getUuidAsString()); this.headPosition = TurretDataHelper.getHeadPosition(this.getUuidAsString()); this.nozzlePosition = TurretDataHelper.getNozzlePosition(this.getUuidAsString()); if(target != null && !world.isClient && world.getTime() % 4 == 0) shoot(); super.tick(); } @Override public AnimationFactory getFactory() { return this.factory; } @Override public void registerControllers(AnimationData data) { this.main = data.addAnimationController(new AnimationController<>(this, "controller", 0, this::predicate)); this.radar = data.addAnimationController(new AnimationController<>(this, "radar", 0, this::predicate2)); } /////////////////////////////////////////////////// public static void prepareReceiver(){ ServerPlayNetworking.registerGlobalReceiver(new Identifier(ExampleMod.MODID, "bone_packet"), (server, player, handler, buf, responseSender)->{ //head rotation float x = (float) (buf.readFloat() * 180 / Math.PI); float y = (float) (buf.readFloat() * 180 / Math.PI); float z = (float) (buf.readFloat() * 180 / Math.PI); Vec3d headRotations = new Vec3d(-x,-y,z); //pos double px = buf.readDouble(); double py = buf.readDouble(); double pz = buf.readDouble(); Vec3d headPosition = new Vec3d(px,py,pz); //nozle float nx = buf.readFloat(); float ny = buf.readFloat(); float nz = buf.readFloat(); Vec3d nozlePosition = new Vec3d(nx,ny,nz); //target double tx = buf.readDouble(); double ty = buf.readDouble(); double tz = buf.readDouble(); Vec3d target = new Vec3d(tx, ty, tz); if( Double.isNaN(target.x) || Double.isNaN(target.y) || Double.isNaN(target.z) ) target = null; String turretID = buf.readString(50); TurretData data = new TurretData(headPosition, headRotations, nozlePosition, target); turretInfo.put(turretID, data); }); } public void shoot(){ if(headRotations == null || headPosition == null || target == null ) return; if(!world.isClient){ playShootSound(); shootCustomProjectile(); //shootFireBall(); } } private void playShootSound(){ world.playSound(null, new BlockPos(this.getPos()), SoundRegister.LASER_MONO_EVENT, SoundCategory.AMBIENT, 1f, 1f); } private void shootCustomProjectile(){ ProjectileEntity myProjectile = new ProjectileEntity(world, this); myProjectile.setPosition( headPosition.x, headPosition.y, headPosition.z); myProjectile.setProperties(this, (float)headRotations.x, (float)headRotations.y, 0f, 4.3f, 0f); myProjectile.removed = false; Boolean s = world.spawnEntity(myProjectile); if(!s) System.out.println("no shot"); } private void shootFireBall(){ FireballEntity myProjectile = new FireballEntity(EntityType.FIREBALL, world); myProjectile.setPosition(headPosition.getX(), headPosition.getY(), headPosition.getZ()); myProjectile.setProperties(this, (float)headRotations.x, (float)headRotations.y, 0f, 1.5f, 0f); world.spawnEntity(myProjectile); } private abstract class TurretDataHelper{ public static Vec3d getTarget(String turretID){ TurretData data = turretInfo.get(turretID); Vec3d target = (data != null)? data.target : null; return target; } public static Vec3d getHeadPosition(String turretID){ TurretData data = turretInfo.get(turretID); Vec3d pos = (data != null)? data.headPosition : null; return pos; } public static Vec3d getHeadRotation(String turretID){ TurretData data = turretInfo.get(turretID); Vec3d rot = (data != null)? data.headRotations : null; return rot; } public static Vec3d getNozzlePosition(String turretID){ TurretData data = turretInfo.get(turretID); Vec3d pos = (data != null)? data.nozzlePosition : null; return pos; } } public void packetToClient_Example(){ PlayerEntity player = this.world.getClosestPlayer(this, TURRET_RANGE); //destination, identifier, payload if(player instanceof ServerPlayerEntity) ServerPlayNetworking.send((ServerPlayerEntity)player, new Identifier(ExampleMod.MODID, "test_packet"), PacketByteBufs.empty()); } private Vec3d directionLook(double d, double e){ double radYaw = d / 180 * Math.PI; double radPitch = e / 180 * Math.PI; double x = -Math.sin(radYaw) * Math.cos(radPitch); double y = -Math.sin(radPitch); double z = Math.cos(radYaw) * Math.cos(radPitch); return new Vec3d(x, y, z).normalize(); } }
true
0221c28ddb6a87e47dcb641238bf7e61f3e40b80
Java
moradaniel/humanResources
/src/main/java/org/dpi/web/reporting/ReportUtils.java
UTF-8
1,354
2.28125
2
[]
no_license
package org.dpi.web.reporting; import java.util.HashMap; import java.util.Map; public class ReportUtils { //TODO move this to database // hardcoded list of available reports private static final ReportDescriptor descriptors[] = { new ReportDescriptor(ReportService.Reports.EmployeeAdditionsPromotionsReport.name(),"Employee Additions Promotions Report","Employee_Additions_Promotions_Report") ,new ReportDescriptor(ReportService.Reports.CreditsEntriesReport.name(),"Credits Entries Report","Credits_Entries_Report") ,new ReportDescriptor(ReportService.Reports.ResumenDeSaldosDeCreditosDeReparticionesReport.name(),"Reporte Resumen Saldos de Creditos de Reparticiones","Resumen_Saldos_Creditos_Reparticiones_Report") ,new ReportDescriptor(ReportService.Reports.SolicitudCreditosReparticionReport.name(),"Reporte Solicitud de Creditos para Reparticion","Solicitud_Creditos_Reparticion_Report") }; public static Map<String,ReportDescriptor> getAvailableReports() { Map<String,ReportDescriptor> reportDescriptors = new HashMap<String,ReportDescriptor>(); for (int i = 0; i < descriptors.length; i++) { reportDescriptors.put(descriptors[i].getReportCode(), descriptors[i]); } return reportDescriptors; } }
true
a29d3568f97f9fdfb074e099fefd5343ab81cc59
Java
lanaflonform/workshop-spring-data-jpa
/spring-data-jpa-query-dsl-solution/src/main/java/com/zenika/repository/ContactRepositoryImpl.java
UTF-8
695
2.296875
2
[]
no_license
/** * */ package com.zenika.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.mysema.query.jpa.impl.JPAQuery; import com.zenika.model.Contact; import com.zenika.model.QContact; /** * @author acogoluegnes * */ public class ContactRepositoryImpl implements ContactRepositoryCustom { @PersistenceContext EntityManager em; @Override public List<Contact> findOutlawsInMidThirties() { JPAQuery query = new JPAQuery(em); QContact contact = QContact.contact; return query.from(contact).where( contact.lastname.eq("Dalton").and( contact.age.between(30, 40))) .list(contact); } }
true
514cb802be89e7610d05cb30a6333529271b51cd
Java
cggggggg/jenkins
/src/main/java/com/can/service/LoginService.java
UTF-8
642
2.0625
2
[]
no_license
package com.can.service; import com.can.dao.User; import com.can.pojo.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * Created by admin on 2017/7/31. */ @Service public class LoginService implements UserDao { @Autowired UserDao userDao; //传Map集合 public User login(Map<String,String> map){ User user = userDao.login(map); return user; } //传对象 /*public User login(User userInfo){ User user = userDao.login(userInfo); return user; }*/ }
true
c8e39f0dbd973c0a66e2514172f35e43131aaf9c
Java
flywind2/joeis
/src/irvine/oeis/a000/A000307.java
UTF-8
1,035
2.78125
3
[]
no_license
package irvine.oeis.a000; import irvine.math.z.Binomial; import irvine.math.z.Z; import irvine.oeis.Sequence; import java.util.ArrayList; /** * A000307 Number of 4-level labeled rooted trees with n leaves. * @author Sean A. Irvine */ public class A000307 implements Sequence { private int mN = -1; private final A000258 mA258 = new A000258(); private final ArrayList<Z> mL = new ArrayList<>(); private final ArrayList<Z> mB = new ArrayList<>(); private Z a258(final int n) { while (n >= mL.size()) { mL.add(mA258.next()); } return mL.get(n); } private Z computeB(final int n) { if (n == 0) { return Z.ONE; } else { Z sum = Z.ZERO; for (int k = 1; k <= n; ++k) { sum = sum.add(a258(k).multiply(b(n - k)).multiply(Binomial.binomial(n - 1, k - 1))); } return sum; } } private Z b(final int n) { while (n >= mB.size()) { mB.add(computeB(mB.size())); } return mB.get(n); } @Override public Z next() { return b(++mN); } }
true
0c5500dae7f20ff8cd1148ab2b41dc29e14294ec
Java
AlbertSnow/git_workspace
/TestMemory/wandoujia/src/main/java/com/wandoujia/p4/app_launcher/f/b.java
UTF-8
4,049
1.640625
2
[]
no_license
package com.wandoujia.p4.app_launcher.f; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Looper; import android.text.TextUtils; import com.wandoujia.base.config.GlobalConfig; import com.wandoujia.base.utils.CollectionUtils; import com.wandoujia.base.utils.Preferences; import com.wandoujia.base.utils.Preferences.CustomEditor; import com.wandoujia.base.utils.SharePrefSubmitor; import com.wandoujia.p4.app_launcher.manager.d; import com.wandoujia.p4.app_launcher.model.ALAppInfo; import com.wandoujia.p4.app_launcher.model.ALSuggestion; import com.wandoujia.p4.app_launcher.model.ALSuggestion.FunctionInfo; import com.wandoujia.p4.app_launcher.model.ALSuggestion.Icons; import com.wandoujia.p4.http.c.a; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class b { private static String a; static { b.class.getSimpleName(); } public static void a(boolean paramBoolean) { d.a(new c(paramBoolean)); } public static boolean a() { String str1 = f(); String str2 = com.wandoujia.p4.app_launcher.manager.b.a().getString("key_icon_app_hash", ""); return (TextUtils.isEmpty(str2)) || (!str2.equals(str1)); } public static boolean a(String paramString) { return (!TextUtils.isEmpty(paramString)) && (paramString.equals("com.tencent.mm")); } public static Drawable b() { if (Looper.myLooper() == Looper.getMainLooper()) throw new IllegalStateException("Must not run on UI thread!"); Resources localResources = GlobalConfig.getAppContext().getResources(); try { localObject = new BitmapDrawable(localResources, new URL(a).openConnection().getInputStream()); if (localObject == null) localObject = localResources.getDrawable(2130837710); return localObject; } catch (IOException localIOException) { while (true) Object localObject = null; } } private static void e() { String str = f(); SharePrefSubmitor.submit(com.wandoujia.p4.app_launcher.manager.b.a().edit().putString("key_icon_app_hash", str)); } private static String f() { StringBuilder localStringBuilder = new StringBuilder(); Iterator localIterator = g().iterator(); while (localIterator.hasNext()) localStringBuilder.append((String)localIterator.next()); return a.a().a(localStringBuilder.toString()); } private static List<String> g() { ArrayList localArrayList = new ArrayList(); ALSuggestion localALSuggestion = com.wandoujia.p4.app_launcher.manager.b.b(); if (localALSuggestion != null) { if (!CollectionUtils.isEmpty(localALSuggestion.intentElemList)) { Iterator localIterator2 = localALSuggestion.intentElemList.iterator(); while (localIterator2.hasNext()) { ALSuggestion.FunctionInfo localFunctionInfo = (ALSuggestion.FunctionInfo)localIterator2.next(); if (!a(localFunctionInfo.packageName)) continue; localArrayList.add(localFunctionInfo.packageName); a = localFunctionInfo.icons.px256; } } if (!CollectionUtils.isEmpty(localALSuggestion.appsElemList)) { Iterator localIterator1 = localALSuggestion.appsElemList.iterator(); do { ALAppInfo localALAppInfo; do { if (!localIterator1.hasNext()) break; localALAppInfo = (ALAppInfo)localIterator1.next(); } while (a(localALAppInfo.packageName)); localArrayList.add(localALAppInfo.packageName); } while (localArrayList.size() < 4); } } return localArrayList; } } /* Location: C:\WorkSpace\WandDouJiaNotificationBar\WanDou1.jar * Qualified Name: com.wandoujia.p4.app_launcher.f.b * JD-Core Version: 0.6.0 */
true
744eba452e4f548ca0819a3a96410e44b0633592
Java
JeffTang139/jtcore
/org.eclipse.jt.core/src/org/eclipse/jt/core/impl/NStrCompareExpr.java
WINDOWS-1252
992
2.578125
3
[]
no_license
package org.eclipse.jt.core.impl; /** * ַȽνʽڵ * * @author Jeff Tang * */ class NStrCompareExpr implements NConditionExpr { public enum Keywords { STARTS_WITH, ENDS_WITH, CONTAINS, LIKE } public final NValueExpr first; public final NValueExpr second; public final boolean not; public final Keywords keyword; public NStrCompareExpr(Keywords keyword, NValueExpr first, NValueExpr second, boolean not) { this.first = first; this.second = second; this.not = not; this.keyword = keyword; } public int startLine() { return this.first.startLine(); } public int startCol() { return this.first.startCol(); } public int endLine() { return this.second.endLine(); } public int endCol() { return this.second.endCol(); } public <T> void accept(T visitorContext, SQLVisitor<T> visitor) { visitor.visitStrCompareExpr(visitorContext, this); } @Override public String toString() { return RenderVisitor.render(this); } }
true
bd085ae81460322e8b529595c3302b96de76afa7
Java
cyril23/testone
/Trunk_Jun_09_08/src/com/bagnet/nettracer/tracing/actions/ForwardOnHandAction.java
UTF-8
9,654
2.0625
2
[]
no_license
package com.bagnet.nettracer.tracing.actions; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.util.LabelValueBean; import org.apache.struts.util.MessageResources; import com.bagnet.nettracer.tracing.bmo.CompanyBMO; import com.bagnet.nettracer.tracing.bmo.StationBMO; import com.bagnet.nettracer.tracing.constant.TracingConstants; import com.bagnet.nettracer.tracing.db.Agent; import com.bagnet.nettracer.tracing.db.OHD; import com.bagnet.nettracer.tracing.db.OHDRequest; import com.bagnet.nettracer.tracing.db.OHD_Log; import com.bagnet.nettracer.tracing.db.OHD_Log_Itinerary; import com.bagnet.nettracer.tracing.db.Station; import com.bagnet.nettracer.tracing.forms.ForwardOnHandForm; import com.bagnet.nettracer.tracing.utils.BagService; import com.bagnet.nettracer.tracing.utils.OHDUtils; import com.bagnet.nettracer.tracing.utils.TracerUtils; /** * Implementation of <strong>Action </strong> that is responsible for handling * forward on-hand bags task. It would forward the bag to the desired location * or LZ. * * @author Ankur Gupta */ public class ForwardOnHandAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); // check session and user validity TracerUtils.checkSession(session); Agent user = (Agent) session.getAttribute("user"); if (user == null || form == null) { response.sendRedirect("logoff.do"); return null; } ActionMessages errors = new ActionMessages(); //Obtain a handle on the resources direcory. MessageResources messages = MessageResources .getMessageResources("com.bagnet.nettracer.tracing.resources.ApplicationResources"); BagService bs = new BagService(); ForwardOnHandForm theform = (ForwardOnHandForm) form; //this field is what contains the expedite bagtag which is a freeflow. //must strip invalid characters to prevent reflective xss attacks if(theform.getOhdList() != null){ for(LabelValueBean ohdBean: theform.getOhdList()){ if(ohdBean != null && ohdBean.getValue() != null){ ohdBean.setValue(ohdBean.getValue().replaceAll(TracingConstants.FILTER_CHARACTERS,"")); } } } String companyCode = null; if (theform.getCompanyCode() != null && !theform.getCompanyCode().equals("") && CompanyBMO.getCompany(theform.getCompanyCode())!=null) companyCode = theform .getCompanyCode(); else companyCode = user.getCompanycode_ID(); theform.setCompanyCode(companyCode); List stationList = null; if (theform.getCompanyCode() != null && !theform.getCompanyCode().equals("") && CompanyBMO.getCompany(theform.getCompanyCode())!=null) stationList = TracerUtils .getStationList(theform.getCompanyCode()); else stationList = TracerUtils .getStationList(user.getCompanycode_ID()); if (stationList == null || stationList.size() == 0) { theform.setDestStation(""); } request.setAttribute("stationList", stationList); if (request.getParameter("showForward") != null) { String forward_ID = request.getParameter("forward_id"); //Retrieve the on hand log based on the forward id OHD_Log log = OHDUtils.getForwardLog(forward_ID); theform.setOhd_ID(log.getOhd().getOHD_ID()); if (log.getOhd_request_id() > 0) theform.setBag_request_id("" + log.getOhd_request_id()); theform.setExpediteNumber(log.getExpeditenum()); //Update the itinerary list in the form List itineraryList = new ArrayList(log.getItinerary()); if (itineraryList != null) { for (Iterator i = itineraryList.iterator(); i.hasNext();) { OHD_Log_Itinerary itinerary = (OHD_Log_Itinerary) i.next(); itinerary.set_DATEFORMAT(user.getDateformat().getFormat()); itinerary.set_TIMEFORMAT(user.getTimeformat().getFormat()); } theform.setItinerarylist(itineraryList); } //the message that accompanies the forward theform.setMessage(log.getMessage()); return mapping.findForward(TracingConstants.VIEW_FORWARD_DETAILS); } //Add itinerary item is clicked. else if (request.getParameter("additinerary") != null) { OHD_Log_Itinerary itinerary = theform.getItinerary(theform.getItinerarylist().size()); itinerary.set_DATEFORMAT(user.getDateformat().getFormat()); itinerary.set_TIMEFORMAT(user.getTimeformat().getFormat()); return mapping.findForward(TracingConstants.ENTER_FORWARD_ON_HAND); } else if (request.getParameter("save") != null) { //Invalid or no destination is selected. if (theform.getDestStation() == null || theform.getDestStation().equals("") || StationBMO.getStation(theform.getDestStation())==null) { ActionMessage error = new ActionMessage("error.noStationcode"); errors.add(ActionMessages.GLOBAL_MESSAGE, error); saveMessages(request, errors); } else { // Do the forward if (((theform.getOhd_ID()!=null && theform.getOhd_ID().length()>0 && OHDUtils.getOHD(String.valueOf(theform.getOhd_ID()))!=null) || (theform.getOhdList()!=null && theform.getOhdList().size()>0) || (theform.getBag_request_id()!=null && OHDUtils.getOHD(String.valueOf(theform.getBag_request_id()))!=null)) && bs.forwardOnHand(theform, user, messages)) { return (mapping.findForward(TracingConstants.FORWARD_ON_HAND_SUCCESS)); } else { ActionMessage error = new ActionMessage("error.noForwardcode"); errors.add(ActionMessages.GLOBAL_MESSAGE, error); saveMessages(request, errors); } } return (mapping.findForward(TracingConstants.ENTER_FORWARD_ON_HAND)); } else { boolean deleteBagItin = false; //This technique is employed to get the []['nd] reference String index = "0"; Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String parameter = (String) e.nextElement(); if (parameter.indexOf("[") != -1) { index = parameter.substring(parameter.indexOf("[") + 1, parameter.indexOf("]")); if (parameter.indexOf("deleteBag") != -1) { deleteBagItin = true; break; }//delete bag item is clicked. } } if (deleteBagItin) { List itnList = theform.getItinerarylist(); if (itnList != null) itnList.remove(Integer.parseInt(index)); return (mapping.findForward(TracingConstants.ENTER_FORWARD_ON_HAND)); }//delete bag-item } if (request.getParameter("log_ID") != null) { String log_id = request.getParameter("log_ID"); } String ohd_ID = theform.getOhd_ID(); if(ohd_ID==null || ohd_ID.length()==0){ request.getParameter("ohd_ID"); if(ohd_ID!=null && OHDUtils.getOHD(ohd_ID)==null) ohd_ID=null; } if (request.getParameter("batch") != null) { ohd_ID = request.getParameter("batch_id"); } ArrayList<LabelValueBean> oList = new ArrayList<LabelValueBean>(); if (ohd_ID != null) { String[] ohdArray = ohd_ID.split(","); Map<String, OHD> ohdMap = new HashMap<String, OHD>(); for (String o: ohdArray) { o = StringUtils.stripToNull(o); if (o == null) { continue; } OHD ohd = OHDUtils.getOHD(o); if(ohd != null) { ohdMap.put(o, ohd); oList.add(new LabelValueBean(o, "")); } } //reset the forward form theform = new ForwardOnHandForm(); List list = new ArrayList(); OHD_Log_Itinerary itinerary = theform.getItinerary(0); itinerary.set_DATEFORMAT(user.getDateformat().getFormat()); itinerary.set_TIMEFORMAT(user.getTimeformat().getFormat()); list.add(itinerary); theform.setOhd_ID(ohd_ID); theform.setOhdList(oList); request.setAttribute("ohdMap", ohdMap); if(companyCode!=null && companyCode.length()>0){ theform.setCompanyCode(companyCode); } else { theform.setCompanyCode(user.getCompanycode_ID()); } session.setAttribute("forwardOnHandForm", theform); } String request_ID = request.getParameter("request_ID"); if (request_ID != null) { //set the company code and destination station as well. OHDRequest oReq = OHDUtils.getRequest(request_ID); theform.setBag_request_id(request_ID); theform.setDestStation("" + oReq.getRequestForStation().getStation_ID()); theform.setCompanyCode(oReq.getRequestForStation().getCompany().getCompanyCode_ID()); } if (request.getParameter("lz") != null) { //from lz..update the List stations = new ArrayList(); stations.add(StationBMO.getStation(user.getStation().getCompany().getVariable().getOhd_lz())); if (stations == null || stations.size() == 0) { return (mapping.findForward(TracingConstants.FORWARD_ERROR)); } else { theform.setCompanyCode(user.getStation().getCompany().getCompanyCode_ID()); theform.setDestStation("" + ((Station) stations.get(0)).getStation_ID()); theform.setLz(1); } } if (theform.getItinerarylist().size() == 0) { OHD_Log_Itinerary itinerary = theform.getItinerary(0); itinerary.set_DATEFORMAT(user.getDateformat().getFormat()); itinerary.set_TIMEFORMAT(user.getTimeformat().getFormat()); } //Allow modifications to the forward. return mapping.findForward(TracingConstants.ENTER_FORWARD_ON_HAND); } }
true
03659c3796cf5867e929f2a3fdc43475d4bd000a
Java
Djiffit/advent-of-code
/aoc-2017/src/aoc/solutions/Day_14.java
UTF-8
3,969
2.828125
3
[]
no_license
package aoc.solutions; import aoc.misc.Day; import java.io.IOException; import java.math.BigInteger; import java.util.*; public class Day_14 implements Day { public Object part1() throws IOException { String input = readDay(14); return countActiveBits("hxtvlmkl"); } public Object part2() throws IOException { return findNumberOfRegions(); } List<char[]> binaries = new ArrayList<>(); void dfs(int y, int x) { binaries.get(y)[x] = '2'; if (y > 0 && binaries.get(y - 1)[x] == '1') dfs(y - 1, x); if (y < 127 && binaries.get(y + 1)[x] == '1') dfs(y + 1, x); if (x > 0 && binaries.get(y)[x - 1] == '1') dfs(y, x - 1); if (x < 127 && binaries.get(y)[x + 1] == '1') dfs(y, x + 1); } int findNumberOfRegions() { int currNum = 0; for (int y = 0; y < 128; y++) { for (int x = 0; x < 128; x++) { if (binaries.get(y)[x] == '1') { dfs(y, x); currNum += 1; } } } return currNum; } int countActiveBits(String input) { int total = 0; Day_10 knotter = new Day_10(); for (int i = 0; i < 128; i ++) { String curr = input + '-' + i; String knot = knotter.twist64(curr); StringBuilder binary = new StringBuilder(); for (char c : knot.toCharArray()) { String append = new BigInteger("" + c, 16).toString(2); while (append.length() < 4) append = " " + append; binary.append(append); } for (char c : binary.toString().toCharArray()) if (c == '1') total += 1; binaries.add(binary.toString().toCharArray()); } return total; } public class Scanner { public int severity; public int direction = 1; public int position = 0; Scanner(int severity) { this.severity = severity; } public void step() { this.position += direction; if (this.position == this.severity - 1 || this.position == 0) this.direction = this.direction == 1 ? -1 : 1; } } private HashMap<Integer, Scanner> scanners = new HashMap<>(); private void readScanners(String input) { this.scanners = new HashMap<>(); for (String row : input.split("\n")) { String[] data = row.split(": "); this.scanners.put(Integer.parseInt(data[0]), new Scanner(Integer.parseInt(data[1]))); } } private int countViolationScore(String input, int wait) { readScanners(input); int position = -1; int totalSeverity = 0; for (int i = 0; i < wait; i ++) { for (Scanner s : this.scanners.values()) s.step(); } while (this.scanners.size() > 0) { position++; if (this.scanners.containsKey(position)) { if (this.scanners.get(position).position == 0) totalSeverity += this.scanners.get(position).severity * position; this.scanners.remove(position); } for (Scanner s : this.scanners.values()) s.step(); } return totalSeverity; } private int smallestDelay(String input) { readScanners(input); for (int i = 0; i < 100000001; i++) { boolean valid = true; for (int key : this.scanners.keySet()) { int cycle = (this.scanners.get(key).severity - 1) * 2; if ((i + key) % cycle == 0) { valid = false; break; } } if (valid) return i; } return -1; } }
true
2eda3b3cc0597548a152995c1a8bd03874f63430
Java
allsunnyday/_SYNERGY_GIT
/HangerApplication/app/src/main/java/com/example/geehy/hangerapplication/EditClosetActivity.java
UTF-8
555
1.695313
2
[]
no_license
package com.example.geehy.hangerapplication; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import com.bumptech.glide.Glide; public class EditClosetActivity extends AppCompatActivity { ImageView imageView; private SharedPreferences appData; private String path; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_closet); } }
true
f62870e0ee3448672a5df4a776c62d8eb2bc72fe
Java
antew/DataStructuresInJava
/src/com/antew/lang/util/DequeAsLinkedList.java
UTF-8
1,311
3.0625
3
[]
no_license
package com.antew.lang.util; import com.antew.lang.Deque; import com.antew.lang.exception.ContainerEmptyException; import com.antew.lang.exception.ContainerFullException; public class DequeAsLinkedList extends QueueAsLinkedList implements Deque { @Override public Object getTail() throws ContainerEmptyException { if (count == 0) throw new ContainerEmptyException(); return queue.getTail(); } @Override public void enqueueHead(Object object) throws ContainerFullException { queue.prepend(object); count++; } @Override public void enqueueTail(Object object) throws ContainerFullException { queue.append(object); count++; } @Override public Object dequeueHead() throws ContainerEmptyException { if (count == 0) throw new ContainerEmptyException(); Object retVal = queue.getHead(); queue.remove(retVal); count--; return retVal; } @Override public Object dequeueTail() throws ContainerEmptyException { if (count == 0) throw new ContainerEmptyException(); Object retVal = queue.getTail(); queue.remove(retVal); count--; return retVal; } }
true
02bc8e247b860edc4ea77da1e426cb34a470fd92
Java
amine-ben/DOCL
/docl-parent/fr.inria.diverse.docl/src-gen/fr/inria/diverse/docl/docl/impl/OclTypeImpl.java
UTF-8
821
1.625
2
[]
no_license
/** * generated by Xtext 2.10.0 */ package fr.inria.diverse.docl.docl.impl; import fr.inria.diverse.docl.docl.DoclPackage; import fr.inria.diverse.docl.docl.OclType; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ocl Type</b></em>'. * <!-- end-user-doc --> * * @generated */ public class OclTypeImpl extends MinimalEObjectImpl.Container implements OclType { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected OclTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DoclPackage.Literals.OCL_TYPE; } } //OclTypeImpl
true
d11f544bf350dd7babb3c7f2de753f657d09305a
Java
bungeni-org/bungeni-editor
/utils/NumberingScheme/trunk/Numbering/src/org/bungeni/numbering/impl/GeneralNumberer.java
UTF-8
948
2.71875
3
[]
no_license
/* * GeneralNumberer.java * * Created on March 18, 2008, 2:12 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.bungeni.numbering.impl; /** * generic wrapper for abstractnumberer, puts dummy place holders for abstract methods from abstractnumberer. * Extend and override this class as neccessary (see schemeNumeric for an example) * @author Administrator */ public class GeneralNumberer extends BaseNumberer{ /** Creates a new instance of GeneralNumberer */ public GeneralNumberer() { } public String toWords(long l) { return null; } public String toOrdinalWords(String string, long l, int i) { return null; } public String monthName(int i, int i0, int i1) { return null; } public String dayName(int i, int i0, int i1) { return null; } }
true
f7d927a2a4a693b60b03187c75ea438e9d37eb49
Java
CristianGM23/ModeladoNotaciones
/BPMN/src-gen/bpmn/validation/NatureActivityMakerValidator.java
UTF-8
672
2.015625
2
[]
no_license
/** * * $Id$ */ package bpmn.validation; import bpmn.Activity; import bpmn.TypeNatureActivityMaker; /** * A sample validator interface for {@link bpmn.NatureActivityMaker}. * This doesn't really do anything, and it's not a real EMF artifact. * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended. * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface NatureActivityMakerValidator { boolean validate(); boolean validateType(TypeNatureActivityMaker value); boolean validateActivity(Activity value); }
true
2bb8ecf2bf9cfb255f20ebb9da04b113ab88ddb3
Java
Jarcionek/MTG
/src/server/flags/Search.java
UTF-8
1,086
2.484375
2
[]
no_license
package server.flags; import mtg.Zone; /** * @author Jaroslaw Pawlak */ public class Search extends Action { /** * Determines how many from the top of the zone are to be sent */ public int amount; public String[] cardsIDs; public Zone zone; public int zoneOwner; public Search(int amount, String[] cardsIDs, Zone zone, int requestor, int zoneOwner) { super(requestor); this.amount = amount; this.cardsIDs = cardsIDs; this.zone = zone; this.zoneOwner = zoneOwner; } /** * zoneOwner = -1, cardsIDs = null */ public Search(int cards, Zone zone, int requestor) { this(cards, null, zone, requestor, -1); } @Override public String toString() { String x = "{"; if (cardsIDs != null) { for (String e : cardsIDs) { x += e + ","; } } x += "}"; x = x.replace(",}", "}"); return super.toString() + ", amount = " + amount + ", cardsIDs = " + x + ", zone = " + zone + ")"; } }
true