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
6f22ef02d7b7ad9fae09e0fdfe7c9a1874eb55ba
Java
nibnait/algorithms
/src/main/test/cc/tianbin/demo/java/反射/ReflectTest.java
UTF-8
1,609
3.046875
3
[]
no_license
package cc.tianbin.demo.java.反射; import junit.framework.TestCase; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.junit.Test; import java.lang.reflect.Field; /* */ public class ReflectTest extends TestCase { @Data @NoArgsConstructor @AllArgsConstructor class Person { public int age; public String phone; String getName() { return "xxx"; } String getAddress() { return "lll"; } } @Test public void testCase() throws IllegalAccessException { Field[] fields = null; Class[] declaredClasses = null; try { Class clz = Class.forName(Person.class.getName()); fields = clz.getDeclaredFields(); declaredClasses = clz.getDeclaredClasses(); } catch (Exception e) { } if (declaredClasses != null) { for (int i = 0; i < declaredClasses.length; i++) { String name = declaredClasses[i].getName(); System.out.println(name); } } Person person = new Person(); person.setAge(1); if (fields != null) { for (int i = 0; i < fields.length; i++) { String name = fields[i].getName(); System.out.println(name); String age = String.valueOf(fields[i].get(person)); System.out.println(age); // fields[i].setInt(person, 2); // fields[i].setAccessible(true); } } } }
true
def390d5bbf185244da093a5da1e221bf63a0512
Java
Beyondzhangxin/emergency_platform
/src/main/java/com/aiidc/sps/ep/mapper/BoundMonitorDataMapper.java
UTF-8
429
1.835938
2
[]
no_license
package com.aiidc.sps.ep.mapper; import com.aiidc.sps.ep.entity.BoundMonitorData; public interface BoundMonitorDataMapper { int deleteByPrimaryKey(String id); int insert(BoundMonitorData record); int insertSelective(BoundMonitorData record); BoundMonitorData selectByPrimaryKey(String id); int updateByPrimaryKeySelective(BoundMonitorData record); int updateByPrimaryKey(BoundMonitorData record); }
true
bf2d231812750e4266bbbff0b62491bff2ba0620
Java
dishwalla/Spring-core-HW2
/src/main/java/ua/epam/spring/hometask/Config.java
UTF-8
2,759
2.21875
2
[]
no_license
package ua.epam.spring.hometask; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import ua.epam.spring.hometask.domain.Auditorium; import java.lang.reflect.Array; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Created by dish on 15.10.17. */ @Configuration @EnableAspectJAutoProxy @ComponentScan(basePackages="ua.epam.spring") @PropertySource( value={"classpath:auditorium_a.properties", "classpath:auditorium_b.properties", "classpath:auditorium_o.properties"}) public class Config implements ApplicationContextAware { private ApplicationContext applicationContext; @Bean(name="auditoriumMap") public Map<String, Auditorium> auditoriumMap(){ Environment env = applicationContext.getEnvironment(); env.getProperty("b.name"); env.getProperty("b.number_of_seats"); env.getProperty("b.vip_seats"); env.getProperty("o.name"); env.getProperty("o.number_of_seats"); env.getProperty("o.vip_seats"); Set<Long> aSeats = getSeats(env, "a.vip_seats"); Set<Long> bSeats = getSeats(env, "b.vip_seats"); Set<Long> oSeats = getSeats(env, "o.vip_seats"); Auditorium a = new Auditorium(env.getProperty("a.name"), Long.parseLong(env.getProperty("a.number_of_seats")), aSeats); Auditorium b = new Auditorium(env.getProperty("b.name"), Long.parseLong(env.getProperty("b.number_of_seats")), bSeats); Auditorium o = new Auditorium(env.getProperty("o.name"), Long.parseLong(env.getProperty("o.number_of_seats")), oSeats); Map<String, Auditorium> auditoriumMap = new HashMap<>(); auditoriumMap.put("Alfa", a); auditoriumMap.put("Beta", b); auditoriumMap.put("Omega", o); return auditoriumMap; } private Set<Long> getSeats(Environment env, String pName) { return Arrays.stream(env.getProperty(pName).split(",")) .map(e -> Long.parseLong(e)) .collect(Collectors.toSet()); } @Bean public PropertySourcesPlaceholderConfigurer propertyConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
true
ce00647db1fa4f554d4ff345a64c4123283bd2d0
Java
nicoleljc1227/practiceSets
/src/algorithm/struct/BinTree/MaxTree.java
UTF-8
1,715
3.421875
3
[]
no_license
package algorithm.struct.BinTree; /** * Created by xl on 2017/7/31. * 构造MaxTree 牛客在线编程 */ public class MaxTree { public static void main(String[] args) { int[] arr = {2049,933,1444,1695,96,1025,533}; int[] res = buildMaxTree(arr,7); System.out.println(res); } public static int[] buildMaxTree(int[] A, int n) { // write code here int max_left = 0,max_right = 0,max = 0; int pos_left = -1; int pos_right = -1; int[] res = new int[n]; for (int i = 0; i <n ; i++) { max_left = A[i]; max_right = A[i]; if(i!=0){ for (int j = i-1; j >=0 ; j--) { if(A[j]>max_left){ max_left = A[j]; pos_left = j; break; } } }else { max_left = -1; } if(i!=n-1){ for (int j = i+1; j < n ; j++) { if(A[j]>max_right){ max_right = A[j]; pos_right = j; break; } } }else { max_right = -1; } if((max_left==-1||max_left==A[i])&&max_right!=A[i]){ res[i] = pos_right; }else if((max_right==-1||max_right==A[i])&&max_left!=A[i]){ res[i] = pos_left; }else if(max_left!=A[i]&&max_right!=A[i]){ res[i]= max_left<max_right? pos_left:pos_right; }else { res[i] = -1; } } return res; } }
true
5d8e275cfc1fc40b89995b8ea1a9a4e0a3ef4fd3
Java
rafareas/university_projects
/dataManipulation_project/project_java/model/business/MapBusiness.java
UTF-8
1,223
2.921875
3
[]
no_license
package project_java.model.business; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Set; public class MapBusiness implements Serializable, MapBusInterface{ private Map<String,Business> MapBus; public MapBusiness(){ this.MapBus = new HashMap<>(); } public MapBusiness(Business b){ this.MapBus.put(b.getBus_id(), b.clone()); } public MapBusiness(MapBusiness b){ this.MapBus = b.getMap(); } public Map<String,Business> getMap(){ Map<String, Business> aux = new HashMap<>(); for (Business b : this.MapBus.values()) { aux.put(b.getBus_id(), b.clone()); } return aux; } public Set<String> get_key(){ return this.MapBus.keySet(); } public void addS(Business b){ this.MapBus.put(b.getBus_id(), b.clone()); } public String toString(){ StringBuilder s = new StringBuilder(); for (Map.Entry<String,Business> busEntry : this.MapBus.entrySet()){ s.append(busEntry.toString()); } return s.toString(); } public MapBusiness clone(){ return new MapBusiness(this); } }
true
35993ac0f74754388e9705fb9d7136352eff66a4
Java
Ramon0898/HeadsUpDominicano
/app/src/main/java/com/example/ramon/headsupdominicano/MainActivity.java
UTF-8
2,531
2.265625
2
[]
no_license
package com.example.ramon.headsupdominicano; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { /* Nota: Por ahora solo le puse la funcio al Boton deporte, ya cuando sepamos como vaomos a pasar las preguntas, seguiremos implementando en los otros Botones */ TextView deportes; TextView entretenimiento; TextView geografia; TextView historia; TextView arte; TextView quimica; Intent i; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); quimica=findViewById(R.id.Chemistry); quimica.setOnClickListener(this); arte = findViewById(R.id.Art); arte.setOnClickListener(this); historia = findViewById(R.id.History); historia.setOnClickListener(this); geografia=findViewById(R.id.Geografy); geografia.setOnClickListener(this); entretenimiento = findViewById(R.id.entertainment); entretenimiento.setOnClickListener(this); deportes= findViewById(R.id.Sports); deportes.setOnClickListener(this); } @Override public void onClick(View v) {//Asi es mas facil para no crear tantos metodos Onclik, solo creamos el swith y llamamos el id switch (v.getId()) { case R.id.Sports: i = new Intent(MainActivity.this, Deportes.class); startActivity(i); break; case R.id.entertainment: i = new Intent(MainActivity.this, Entretenimiento.class); startActivity(i); break; case R.id.Geografy: i = new Intent(MainActivity.this, Geografia.class); startActivity(i); break; case R.id.History: i = new Intent(MainActivity.this, Historia.class); startActivity(i); break; case R.id.Art: i = new Intent(MainActivity.this, Arte.class); startActivity(i); break; case R.id.Chemistry: i = new Intent(MainActivity.this, Quimica.class); startActivity(i); break; } } }
true
3fee1917266bd923bd133196cc67f32b9ef1423d
Java
ouakiliam/Bank-account-SG
/src/test/java/com/sg/bankaccount/domain/operation/WithdrawOperationTest.java
UTF-8
754
2.703125
3
[]
no_license
package com.sg.bankaccount.domain.operation; import org.junit.Test; import java.time.LocalDateTime; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class WithdrawOperationTest { @Test(expected = IllegalArgumentException.class) public void should_throw_exception_if_amount_less_then_zero() { new WithdrawOperation(LocalDateTime.parse("2021-06-30T10:15:30.00"), 0); } @Test public void when_withdrawal_operation_executed_should_decrease_balance_by_amount() { Operation operation = new WithdrawOperation(LocalDateTime.parse("2021-06-30T10:15:30.00"), 50); double balance = operation.execute(100); assertThat(balance, is(50.0)); } }
true
2434a6181e843daf3b3c23cdfb7b77a724ff28bf
Java
awilliamson/DaFlight
/src/main/java/me/dags/daflight/util/Config.java
UTF-8
1,418
2.234375
2
[]
no_license
package me.dags.daflight.util; import com.google.common.base.Optional; import java.io.File; /** * @author dags_ <dags@dags.me> */ public class Config { private transient File saveFile; public float flySpeed = 1F; public float sprintSpeed = 1F; public float strafeModifier = 1.0F; public float verticalModifier = 1.0F; public float jumpModifier = 2.0F; public float flyBoost = 2.0F; public float sprintBoost = 2.0F; public String fly = "F"; public String sprint = "R"; public String boost = "X"; public String menu = "F9"; public String up = "SPACE"; public String down = "LSHIFT"; public boolean flyToggle = true; public boolean sprintToggle = true; public boolean boostToggle = true; public boolean disabled = false; public boolean hud = true; public boolean speedometer = false; public boolean flight3D = false; public boolean disableFov = true; public void save() { if (saveFile != null) FileUtil.serialize(this, saveFile); } public static Config getOrCreate(File file) { Optional<Config> optional = FileUtil.deserialize(file, Config.class); if (optional.isPresent()) { optional.get().saveFile = file; return optional.get(); } Config config = new Config(); config.saveFile = file; config.save(); return config; } }
true
f852dbea1661cdb6a5a47f4aeab2c90ea68b475a
Java
pabi2/pb2_pabiweb
/nstda.repo/src/pb/repo/admin/model/MainWkfConfigPurchaseUnitModel.java
UTF-8
1,012
1.921875
2
[]
no_license
package pb.repo.admin.model; public class MainWkfConfigPurchaseUnitModel { Long id; String description; String name; Integer ordId; Integer doctypeId; private Long totalRowCount; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOrdId() { return ordId; } public void setOrdId(Integer ordId) { this.ordId = ordId; } public Integer getDoctypeId() { return doctypeId; } public void setDoctypeId(Integer doctypeId) { this.doctypeId = doctypeId; } public Long getTotalRowCount() { return totalRowCount; } public void setTotalRowCount(Long totalRowCount) { this.totalRowCount = totalRowCount; } }
true
c3adb606e4bf4714bc457291ab4cf5435919e855
Java
okyereadugyamfi/jpos-simple-card
/MBanking/src/com/hqsolution/hqserver/client/activity/AddBankAccountActivity.java
UTF-8
825
2.078125
2
[]
no_license
package com.hqsolution.hqserver.client.activity; import com.hqsolution.hqserver.client.listener.OnClickAddBankAccount; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; public class AddBankAccountActivity extends Activity{ private EditText acountName; private EditText accountNumber; private EditText routingNumber; private EditText bankName; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.add_bank_account_screen); setTitle(R.string.create_account_title); Button button = (Button)findViewById(R.id.btn_add_bank_account); button.setOnClickListener(new OnClickAddBankAccount(this)); } }
true
2df90170efbcfe868bc8d8c0f3ab73e5de4e08da
Java
mateusragazzi/Comp-Distribuida
/src/main/java/com/domain/response/HttpResponseDTO.java
UTF-8
145
1.726563
2
[]
no_license
package com.domain.response; public class HttpResponseDTO { public int statusCode; public String contentType; public String body; }
true
35744d7c387b590c48ecb8483ac431c11b7ded81
Java
ufjf-dcc193/2019-1-dcc193-trb3-trb3-marcosaquino-andremagno
/src/main/java/trb3/dcc193/trb3/ControllerEtiquetas.java
UTF-8
2,512
2.234375
2
[]
no_license
package trb3.dcc193.trb3; import java.util.ArrayList; 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.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class ControllerEtiquetas { @Autowired RepositorioEtiqueta repositorioEtiqueta; @Autowired RepositorioItem repositorioItem; @RequestMapping("/etiqueta") public String listar(Model model){ model.addAttribute("etiquetas",repositorioEtiqueta.findAll()); return "etiqueta/listar"; } @RequestMapping("etiqueta/criar") public String criarEtiqueta(Model model){ model.addAttribute("etiqueta",new Etiqueta()); return "etiqueta/criar"; } @RequestMapping("etiqueta/deletar/{id}") public String deletarEtiqueta(@PathVariable Long id){ repositorioEtiqueta.deleteById(id); return "redirect:/etiqueta"; } @RequestMapping("etiqueta/editar/{id}") public String editarEtiqueta(@PathVariable Long id, Model model){ model.addAttribute("etiqueta",repositorioEtiqueta.findById(id).get()); return "etiqueta/editar"; } @RequestMapping("etiqueta/editar/salvar") public String editarsalvarEtiqueta(Etiqueta etiqueta){ repositorioEtiqueta.save(etiqueta); return "redirect:/etiqueta"; } @RequestMapping("etiqueta/salvar") public String salvarTrabalho(Etiqueta etiqueta){ repositorioEtiqueta.save(etiqueta); return "redirect:/etiqueta"; } @RequestMapping("/etiqueta/Itens/editar/{id}") public String listar(@PathVariable Long id, Model model){ List<Item> vin= repositorioItem.findAll(); List<Item> listaItemConteEtiqueta = new ArrayList<>(); for(int i=0;i<vin.size();i++){ List<Etiqueta> e = vin.get(i).getEtiquetas(); for(int r=0;r<e.size();r++){ if(e.get(r).getId()==id){ listaItemConteEtiqueta.add(vin.get(i)); System.out.println("ssss"); } } } model.addAttribute("itens",listaItemConteEtiqueta); model.addAttribute("etiqueta", repositorioEtiqueta.findById(id).get()); return "etiqueta/listarItens"; } }
true
ff9d7fface7c623e85744fc4a1dbf2f1ede1d4b5
Java
cguegi/training
/mapred/ipcount-cascading/src/main/java/ch/ymc/cascading/Driver.java
UTF-8
2,025
2.171875
2
[]
no_license
package ch.ymc.cascading; import java.util.Properties; import cascading.flow.Flow; import cascading.flow.FlowConnector; import cascading.flow.hadoop.HadoopFlowConnector; import cascading.operation.aggregator.Count; import cascading.operation.regex.RegexParser; import cascading.pipe.Each; import cascading.pipe.Every; import cascading.pipe.GroupBy; import cascading.pipe.Pipe; import cascading.property.AppProps; import cascading.scheme.hadoop.TextLine; import cascading.tap.SinkMode; import cascading.tap.Tap; import cascading.tap.hadoop.Hfs; import cascading.tuple.Fields; /** * Cascading based implementation of distinct IP's counting in weblog data. * * @author cguegi * @see http://www.cascading.org/ * */ public class Driver { private static final String REGEX = "^([\\d.]+) \\S+ \\S+ \\[(.+?)\\] \\\"(.+?)\\\" (\\d{3}) (\\d+) \\\"(.*?)\\\" \\\"(.+?)\\\" \\\"SESSIONID=(\\d+)\\\"\\s*"; public static void main(String[] args) { Properties properties = new Properties(); AppProps.setApplicationJarClass( properties, Driver.class ); FlowConnector flowConnector = new HadoopFlowConnector(properties); String inputPath = args[1]; String outputPath = args[2]; // System.out.println("input: " + inputPath); // System.out.println("output: " + outputPath); Tap<?,?,?> source = new Hfs(new TextLine(new Fields("offset", "line")), inputPath); Tap<?,?,?> sink = new Hfs(new TextLine(1), outputPath, SinkMode.REPLACE); Fields apacheFields = new Fields("ip", "date", "request", "status", "byte", "referer", "ua", "cookie"); int[] apacheGroups = {1, 2, 3, 4, 5, 6, 7, 8}; RegexParser parser = new RegexParser(apacheFields, REGEX, apacheGroups); Pipe wcPipe = new Each("ipcount", new Fields("line"), parser, new Fields("ip")); // group on "ips" wcPipe = new GroupBy(wcPipe, new Fields("ip")); wcPipe = new Every(wcPipe, new Count(), new Fields( "ip", "count" )); Flow<?> count = flowConnector.connect(source, sink, wcPipe); count.complete(); } }
true
f13e5ba20f66aab034d8d172e1f46fce38768782
Java
sskelkar/mis-employee-service
/src/main/java/com/maxxton/mis/employee/MisEmployeeServiceApplication.java
UTF-8
352
1.578125
2
[]
no_license
package com.maxxton.mis.employee; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MisEmployeeServiceApplication { public static void main(String[] args) { SpringApplication.run(MisEmployeeServiceApplication.class, args); } }
true
c29f8d4b6426cb6edc1c58a9c317dd7c448bcf43
Java
mohadian/quiver
/quiver/src/main/java/com/zagros/quiver/rest/core/parser/AbstractXmlResponseParser.java
UTF-8
1,570
2.359375
2
[ "Apache-2.0" ]
permissive
package com.zagros.quiver.rest.core.parser; import com.android.volley.NetworkResponse; import com.android.volley.toolbox.HttpHeaderParser; import java.io.UnsupportedEncodingException; /** * Default implemetation for Json parser */ public class AbstractXmlResponseParser extends RestResponseParser<String, String> { public AbstractXmlResponseParser() { } @Override public void parse() throws ParserException { if (mRestResponse == null && mRestAltResponse == null) { throw new ParserException("The response need to be initialized"); } } @Override public void parseError() throws ParserException { if (mRestResponse == null && mRestAltResponse == null) { throw new ParserException("The response need to be initialized"); } } @Override public void setResponseContent(NetworkResponse networkResponse) throws ParserException { String response; try { if (networkResponse.headers != null && HttpHeaderParser.parseCharset(networkResponse.headers) != null) { response = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers)); } else { response = new String(networkResponse.data, "UTF-8"); } } catch (UnsupportedEncodingException e1) { throw new ParserException(e1); } if (response != null && response.length() > 0) { setRestObject(response); } } }
true
f73eda582f78aeee80da2d6d42ef93fdd448c923
Java
chloesyy/ip
/src/main/java/duke/Storage.java
UTF-8
3,619
3.375
3
[]
no_license
package duke; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import static duke.command.AddCommand.addDeadline; import static duke.command.AddCommand.addEvent; import static duke.command.AddCommand.addTodo; /** * Represents the file for data to be loaded from and saved into. */ public class Storage { private String filePath; public Storage(String filePath) { this.filePath = filePath; } /** * Loads data from the file "duke.txt". * Creates a new file if the file does not exist. * * @param tasks Current TaskList. * @param ui Interactions with the user. * @throws IOException If the file is corrupted. */ public void loadFile(TaskList tasks, Ui ui) throws IOException { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } Scanner read = new Scanner(file); while (read.hasNext()) { loadFileTask(read.nextLine(), tasks, ui); } read.close(); } /** * Adds individual tasks from the file into the TaskList. * * @param line Line from the file * @param tasks Current TaskList. * @param ui Interactions with the user. */ public void loadFileTask(String line, TaskList tasks, Ui ui) { String[] taskDetails = line.split(" \\| "); switch (taskDetails[0]) { case "[T]": addTodo(taskDetails[2], tasks, this, true, ui); break; case "[D]": addDeadline(taskDetails[2] + " /by " + taskDetails[3], tasks, this, true, ui); break; case "[E]": addEvent(taskDetails[2] + " /at " + taskDetails[3], tasks, this, true, ui); break; default: // Happens if there is nothing in the list (or any garbage text) return; } // Mark as done if the task is already done if (taskDetails[1].equals("1")) { tasks.getTask(tasks.getSize() - 1).isDone = true; } } /** * Adds a line to the file. * * @param filePath File path of the file to be saved: "duke.txt". * @param line Line to be written into the file. * @param ui Interactions with the user. */ public void writeToFile(String filePath, String line, Ui ui) { try { FileWriter writer = new FileWriter(filePath, true); writer.write(System.lineSeparator() + line); writer.close(); } catch (IOException e) { ui.printIOExceptionError(e); } } /** * Updates a certain line in the file. * * @param oldTaskString Old string to be updated. * @param newTaskString New string to be updated to. * @throws IOException If the file is corrupted. */ public void updateFile(String oldTaskString, String newTaskString) throws IOException { File file = new File("duke.txt"); Scanner scanner = new Scanner(file); StringBuffer buffer = new StringBuffer(); // Puts everything from file into buffer while (scanner.hasNext()) { buffer.append(scanner.nextLine() + System.lineSeparator()); } scanner.close(); // Puts everything from buffer into String String fileContents = buffer.toString(); // Update the file fileContents = fileContents.replace(oldTaskString, newTaskString); FileWriter writer = new FileWriter(filePath); writer.append(fileContents); writer.flush(); } }
true
1e05967022078f653f69bd182aadb50f35a5f657
Java
Yogakani/QrCode
/src/main/java/com/yoga/qrCode/QrCodeApplication.java
UTF-8
1,106
1.914063
2
[]
no_license
package com.yoga.qrCode; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import static com.yoga.qrCode.utils.CommonUtils.getHttpStatusCode; @SpringBootApplication @RequestMapping(value = "/") public class QrCodeApplication { public static void main(String[] args) { SpringApplication.run(QrCodeApplication.class, args); } @GetMapping(value = "/") public ResponseEntity<String> appMsg() { return new ResponseEntity<>("Welcome to App", getHttpStatusCode(true)); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } @Bean public ObjectMapper getMapper() { return new ObjectMapper(); } }
true
09065a3dabe65a83e370f1649ca96dd70d4b714a
Java
chetank/PowerBoot
/src/com/powerboot/dao/HikesListIDao.java
UTF-8
459
1.6875
2
[]
no_license
package com.powerboot.dao; import java.util.List; import javax.sql.DataSource; import com.powerboot.model.HikeListModel; public interface HikesListIDao { void setDataSource(DataSource ds); // void create(String name, String lat, String lon); // List<HikesListModel> select(String name, String lat, String lon); List<HikeListModel> selectAll(); // void deleteAll(); // void delete(String name, String lat, String lon); }
true
4cc741f9c26830db76ead68fef4dd230fcfe531c
Java
Aldiyazov/Transpire
/samples/java/sampleExtends.java
UTF-8
310
1.726563
2
[ "MIT" ]
permissive
公開 設計図 sampleExtends 継承 SomeParent { 公開 静的 無 開始(文字列 引数[]){ 親に連絡(引数); 整数 カウント = 10; 整数 合計 = 0; 各(整数 i = 0; i < カウント; i++ ){ 合計 += i; } システム.出力.書き込む("Sum of 10: " + 合計); } }
true
a5118131ba012895fbc1a19712c97c1438a7da40
Java
mexicochief/Java_TestTask
/src/Program/Sort/MergeSortStr.java
UTF-8
7,817
3.484375
3
[]
no_license
package Program.Sort; import Program.File.Upload; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MergeSortStr extends MergeSort { private Map<Integer,String> currentElmStr = new HashMap<>(); // здесь key - номер файла, value - значение строки public MergeSortStr(Upload upload, String nameOut) { super(upload, nameOut); } public void ascendingSorting() { String tempMin; // текущее минимальное значение int pos; // ключ currentElmStr(номер текущего файла) String lastMin; // пред. минимальное значение lastMin = null; ascendingFilling(); // сравниваем элемнты массива м/у собой и записываем в файл меньший while (currentElmStr.size() > 0) { tempMin = findMin().getValue(); pos = findMin().getKey(); if(lastMin == null || hasFirstNumLower(toInt(lastMin),toInt(tempMin))) { write(tempMin); // записываем данные в выходной файл lastMin = tempMin; } String tempElement = getUpload().scanStr(pos); // проверем: не закончился ли файл ? if(tempElement == null) { currentElmStr.remove(pos); continue; } // если не закончился то заносим этот элемент в список currentElmStr.put(pos, tempElement); } writerClose(); } // заполняет currentElmInt первыми строками из файлов private void ascendingFilling() { for (int temp = 0; temp < getUpload().howManyFile(); temp++) { // Тут скорее всего можно сделать проще! int quantity = getUpload().lineCount(temp); if(quantity == 1) { this.currentElmStr.put(temp, getUpload().scanStr(temp)); continue; } else if(quantity == 0) { continue; } hasBreachInOrderA(temp); } } // Проверяет нарушен ли порядок в первом элементе private void hasBreachInOrderA(int fileNumber) { getUpload().mark(fileNumber); if(hasFirstNumLower(toInt(getUpload().scanStr(fileNumber)), toInt(getUpload().scanStr(fileNumber)))) { getUpload().reset(fileNumber); this.currentElmStr.put(fileNumber, getUpload().scanStr(fileNumber)); } else { getUpload().reset(fileNumber); getUpload().scanStr(fileNumber); this.currentElmStr.put(fileNumber, getUpload().scanStr(fileNumber)); } // тут исключить случай, где ошибка в первом элементе } private Map.Entry<Integer,String> findMin() { Map.Entry<Integer,String> minElement = null; String tempMin = null; for (Map.Entry<Integer,String> entry : currentElmStr.entrySet()) { if (tempMin == null || hasFirstNumLower(toInt(entry.getValue()),toInt(tempMin))) { tempMin = entry.getValue(); minElement = entry; } } return minElement; } public void descendingSorting() { String tempMax; // для хранения минимального значения int pos; String lastMax; // хранит прошлое минимальное значение lastMax = null; descendingFilling(); // сравниваем элемнты массива м/у собой и записываем в файл меньший while (currentElmStr.size() > 0) { tempMax = findMax().getValue(); pos = findMax().getKey(); if(lastMax == null || hasFirstNumLower(toInt(tempMax),toInt(lastMax))) { write(tempMax); // записываем данные в выходной файл lastMax = tempMax; } String tempElement = getUpload().scanStr(pos); // оформить получше // проверем: не закончился ли файл ? if(tempElement == null) { currentElmStr.remove(pos); continue; } // если не закончился то заносим этот элемент в список currentElmStr.put(pos, tempElement); } writerClose(); } private void descendingFilling() { for (int temp = 0; temp < getUpload().howManyFile(); temp++) { // Тут скорее всего можно сделать проще! int quantity = getUpload().lineCount(temp); if(quantity == 1) { this.currentElmStr.put(temp, getUpload().scanStr(temp)); continue; } else if(quantity == 0) { continue; } findBreachInOrderD(temp); } } private void findBreachInOrderD(int fileNumber) { getUpload().mark(fileNumber); if(!hasFirstNumLower(toInt(getUpload().scanStr(fileNumber)), toInt(getUpload().scanStr(fileNumber)))) { getUpload().reset(fileNumber); this.currentElmStr.put(fileNumber, getUpload().scanStr(fileNumber)); } else { getUpload().reset(fileNumber); getUpload().scanStr(fileNumber); this.currentElmStr.put(fileNumber, getUpload().scanStr(fileNumber)); } } private Map.Entry<Integer,String> findMax() { Map.Entry<Integer,String> MaxElement = null; String tempMax = null; for (Map.Entry<Integer,String> entry : currentElmStr.entrySet()) { if (tempMax == null || hasFirstNumLower(toInt(tempMax),toInt(entry.getValue()))) { tempMax = entry.getValue(); MaxElement = entry; } } return MaxElement; } // преобразует строку в набор чисел (в ascii представлении) private ArrayList<Integer> toInt(String str) { str = str.toLowerCase(); // Сортировка без учета регистра(сделать нормально) ArrayList<Integer> result = new ArrayList<>(); char[] temp = str.toCharArray(); if (str == null) { return null; } for(char tempChar:temp) { result.add(Integer.valueOf(Character.valueOf(tempChar))); } return result; } // Сравнивает два набора private boolean hasFirstNumLower(ArrayList<Integer> first, ArrayList<Integer> second) { int count = Math.min(first.size(),second.size()); int temp = 0; while(temp < count) { if(first.get(temp) < second.get(temp)) { return true; } else if(first.get(temp) > second.get(temp)) { return false; } else { temp++; } } return true; } }
true
c12aef0cc0aebda9172057bae37e76f8b18615b4
Java
aws/aws-sdk-java
/aws-java-sdk-backupstorage/src/main/java/com/amazonaws/services/backupstorage/model/transform/ListObjectsRequestMarshaller.java
UTF-8
4,075
1.726563
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.backupstorage.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.backupstorage.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ListObjectsRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListObjectsRequestMarshaller { private static final MarshallingInfo<String> STORAGEJOBID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("jobId").build(); private static final MarshallingInfo<String> STARTINGOBJECTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("starting-object-name").build(); private static final MarshallingInfo<String> STARTINGOBJECTPREFIX_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("starting-object-prefix").build(); private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("max-results").build(); private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("next-token").build(); private static final MarshallingInfo<java.util.Date> CREATEDBEFORE_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("created-before").timestampFormat("iso8601").build(); private static final MarshallingInfo<java.util.Date> CREATEDAFTER_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("created-after").timestampFormat("iso8601").build(); private static final ListObjectsRequestMarshaller instance = new ListObjectsRequestMarshaller(); public static ListObjectsRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ListObjectsRequest listObjectsRequest, ProtocolMarshaller protocolMarshaller) { if (listObjectsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listObjectsRequest.getStorageJobId(), STORAGEJOBID_BINDING); protocolMarshaller.marshall(listObjectsRequest.getStartingObjectName(), STARTINGOBJECTNAME_BINDING); protocolMarshaller.marshall(listObjectsRequest.getStartingObjectPrefix(), STARTINGOBJECTPREFIX_BINDING); protocolMarshaller.marshall(listObjectsRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listObjectsRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(listObjectsRequest.getCreatedBefore(), CREATEDBEFORE_BINDING); protocolMarshaller.marshall(listObjectsRequest.getCreatedAfter(), CREATEDAFTER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
true
cffd37f0842846f5f593ecb29ca6747ce9396dbe
Java
aghazy/MIPS-Simulation
/src/PC.java
UTF-8
809
3.0625
3
[]
no_license
public class PC { private int[] address; public PC(int[] address) { this.address = address; } public PC() { address = new int[32]; } public int[] getAddress() { return address; } public void setAddress(int[] address) { this.address = address; } public void increment(){ int decX = Integer.parseInt(stringify(address), 2); int decZ = decX + 4; address = registify(Integer.toBinaryString(decZ)); } private String stringify(int[] reg) { String out=""; for (int i = 0; i < reg.length; i++) { out += reg[i]; } return out; } private int[] registify(String z) { int [] regOut = new int [32]; int i = 31; while ( z.length()!=0 && i>-1) { regOut[i--] = Integer.parseInt(z.charAt(z.length()-1)+""); z = z.substring(0, z.length()-1); } return regOut; } }
true
87d664a88046bb3d1206324be427f92edeff76ce
Java
jinwoongBang/Jobstory
/jobstory/src/main/java/kr/co/jobstory/mypage/user/service/UserApplyService.java
UTF-8
290
1.664063
2
[]
no_license
package kr.co.jobstory.mypage.user.service; import java.util.List; import java.util.Map; import kr.co.jobstory.repository.domain.Apply; import kr.co.jobstory.repository.domain.Scrap; public interface UserApplyService { List<Apply> apply(int memberNo); void applyDelete(int applyNo); }
true
e30c159aeac8d93f91d02aafdffc908a06c2d5c3
Java
emanoel-bruno/Compiler-CP
/compiler/src/main/java/tokens/FloatConstantToken.java
UTF-8
402
2.65625
3
[ "Apache-2.0" ]
permissive
package tokens; import compiler.Token; import compiler.Tag; public class FloatConstantToken extends Token { private final float value; public FloatConstantToken(float value) { super(Tag.FLOAT_CONSTANT); this.value = value; } public float getValue() { return this.value; } public String toString() { return String.valueOf(this.value); } }
true
4d190616b8a2dabfddb16f967ce7c7cfa6d6fb75
Java
vargose/BibleAndroidApp
/app/src/main/java/com/example/mitchell/bible/injection/ServiceModule.java
UTF-8
2,055
2.0625
2
[ "Apache-2.0" ]
permissive
package com.example.mitchell.bible.injection; import android.support.annotation.NonNull; import com.example.mitchell.bible.service.AuthenticationInterceptor; import com.example.mitchell.bible.service.VersionService; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; /** * Created by mitchell on 10/29/16. */ @Module public class ServiceModule { private static final String API_BASE_URL = "https://api.biblia.com"; @Provides public VersionService provideMarvelComicsService() { return buildRetrofit().create(VersionService.class); } @NonNull private Retrofit buildRetrofit() { final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()); final OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.addNetworkInterceptor(new AuthenticationInterceptor()); final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addNetworkInterceptor(httpLoggingInterceptor); final Gson gson = new GsonBuilder().setLenient().create(); return new Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(rxAdapter) .client(builder.build()) .build(); } @Provides public MainThreadSchedulerProvider providesMainThreadSchedulerProvider() { return new MainThreadSchedulerProvider(); } @Provides public IoThreadSchedulerProvider providesIoThreadSchedulerProvider() { return new IoThreadSchedulerProvider(); } }
true
4ff26da0f6a2dffe420254890e529002d2c30dee
Java
msdsunny/CodeSignal-Solutions
/Arcade/Intro/Java/LineEnconding.java
UTF-8
690
3.140625
3
[]
no_license
public final class LineEnconding { String lineEncoding(String s) { String str = "", res = ""; ArrayList<String> list = new ArrayList(); for(int i = 0; i < s.length(); i++) { if(i == 0) { str += s.charAt(i)+""; } else if(s.charAt(i) == s.charAt(i - 1)) { str += s.charAt(i)+""; } else { list.add(str); str = s.charAt(i)+""; } if(i + 1 == s.length()) { list.add(str); } } for(int i = 0; i < list.size(); i++) { int len = list.get(i).length(); if(len > 1) { res += len+""+list.get(i).charAt(0); } else { res += list.get(i).charAt(0)+""; } } return res; } }
true
474e2744ea4d7dd25d074ea834820f515f7a51ce
Java
romulocia/Mentorama_JAVA_do_ZERO
/src/module07/TestaConta.java
UTF-8
1,124
3.40625
3
[]
no_license
package module07; import java.text.SimpleDateFormat; import java.util.Calendar; public class TestaConta { public static void main(String[] args) { Calendar data = Calendar.getInstance(); SimpleDateFormat formatarData = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); Conta contas[] = new Conta[3]; ContaCorrente cc = new ContaCorrente(1, 1, "Banco 01", 100.0, 200.0); ContaPoupanca cp = new ContaPoupanca(2, 1, "Banco 01", 100.0, 15, 0.05); ContaSalario cs = new ContaSalario(3, 1, "Banco 01", 100.0, 3); contas[0] = cc; contas[1] = cp; contas[2] = cs; System.out.println("Obtendo o saldo das contas:"); System.out.println("-------------------------------------------------------------"); for (Conta conta:contas) { System.out.println("Data: " + formatarData.format(data.getTime())); System.out.println(conta); System.out.println("Saldo atual: R$ " + conta.getSaldo()); System.out.println("-------------------------------------------------------------"); } } }
true
1f3100e3aad05944bd9e3abff5e0d1e9cf4fcab2
Java
qeqewewr/Logistics-Website
/src/main/java/fxc/entity/Goodsprice.java
UTF-8
1,556
2.203125
2
[]
no_license
package fxc.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * The persistent class for the wl_goodsprice database table. * */ @Entity @Table(name = "wl_goodsprice") @NamedQuery(name = "Goodsprice.findAll", query = "SELECT g FROM Goodsprice g") public class Goodsprice implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(unique = true, nullable = false) private long id; private float price; // bi-directional many-to-one association to Good @ManyToOne @JoinColumn(name = "GooID") private Good wlGood; // bi-directional many-to-one association to Location @ManyToOne @JoinColumn(name = "LocID") private Location wlLocation; public Goodsprice() { } public long getId() { return this.id; } public void setId(long id) { this.id = id; } public float getPrice() { return this.price; } public void setPrice(float price) { this.price = price; } public Good getWlGood() { return this.wlGood; } public void setWlGood(Good wlGood) { this.wlGood = wlGood; } public Location getWlLocation() { return this.wlLocation; } public void setWlLocation(Location wlLocation) { this.wlLocation = wlLocation; } }
true
fbe6537ebe38d8abcaf75b788414d96af7e88d8b
Java
electricflux/sdapp_server
/src/com/sdapp/server/RegisterServlet.java
UTF-8
3,923
2.78125
3
[]
no_license
package com.sdapp.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sdapp.domain.LicensePlateMsg; import com.sdapp.domain.UserMsg; import com.sdapp.logger.SdLogger; import com.sdapp.persistencemanager.DAO; /** * Servlet implementation class LoginServlet */ public class RegisterServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { SdLogger.getInstance().getLogger().info("Get on registerServlet"); getServletContext().getRequestDispatcher("/WEB-INF/jsp/registerServlet.jsp").forward(req, resp); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SdLogger.getInstance().getLogger().info("Post on RegisterServlet"); /** * Get the parameters */ String username = request.getParameter("username"); String deviceId = request.getParameter("deviceId"); String authToken = request.getParameter("authToken"); String license = request.getParameter("license"); String isDeviceString = request.getParameter("isDevice"); boolean isDevice = false; if (isDeviceString != null && isDeviceString.length() > 0) isDevice = Boolean.parseBoolean(isDeviceString); /** Clean up white-space from license plate string */ license= license.replaceAll("\\s+", ""); license = license.toLowerCase(); boolean result = registerUser(username, deviceId, authToken, license); /** If its device and registration failed, return a 403 */ if ((false == result) && isDevice) { response.setStatus(403); return; } /** Create the response */ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Request Parameters - Registration status: " + String.valueOf(result); out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Parameter Name<TH>Parameter Value(s)"); /** Print parameters as rows */ printParamRow(out,"username", username); printParamRow(out,"deviceId", deviceId); printParamRow(out,"authToken", authToken); printParamRow(out,"license", license); /** End table */ out.println("</TABLE>\n</BODY></HTML>"); } private boolean registerUser(String username, String deviceId, String authToken, String license) { /** * Sanity check */ if ((username != null) && (deviceId != null) && (license != null) && (authToken != null) && (username.length() > 0) && (true == username.contains("@"))) { /** * See if the user object already exists */ UserMsg retrievedUser = DAO.getUser(username,false); if (retrievedUser != null) return false; /** * Create the user object */ UserMsg user = new UserMsg(); user.setUserName(username); user.setAuthToken(authToken); user.setDeviceIdentifier(deviceId); String licenses[] = license.split(LicensePlateMsg.getSEPARATOR()); for (String lic : licenses) { if (lic.length() > 0) { LicensePlateMsg msg = new LicensePlateMsg(); msg.setLicensePlateNumber(lic); user.getLicensePlateList().add(msg); } } /** Save user */ DAO.saveUser(user); SdLogger.getInstance().getLogger().info("Username: "+user.getUserName()); return true; } return false; } private void printParamRow(PrintWriter out, String name, String value) { out.println("<TR><TD>"+name+"\n<TD>"); if (value.length() == 0) out.print("<I>No Value</I>"); else out.print(value); } }
true
24748b9b12d86ee71a4a7f757ff8396d9d284407
Java
vinitasher/Developer
/CrackingCoding/src/arrays/RollTheDice.java
UTF-8
847
3.34375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package arrays; /** * * @author vasher * http://www.geeksforgeeks.org/roll-characters-string/ * */ public class RollTheDice { int MAX_CHARACTERS = 26; public String rollDice(String s, int[] roll){ int n = 0; if(roll != null) { n = roll.length; } int[] rollCount = new int[n+1]; for(int i=0; i<n; i++){ rollCount[0] += 1; rollCount[roll[i]] -= 1; } for(int j=1; j<rollCount.length; j++){ rollCount[j] += rollCount[j-1]; } for(int k=0; k<s.length(); k++){ } } }
true
fc08e5cb61e63647f60312b055edd00bf99ebaff
Java
androidck/LuckyDeer
/app/src/main/java/com/lucky/deer/find/business/fragment/RedEnvelopesDetailFragment.java
UTF-8
14,624
1.820313
2
[]
no_license
package com.lucky.deer.find.business.fragment; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.dykj.requestcore.util.RequestUtils; import com.lucky.deer.R; import com.lucky.deer.base.BaseFragment; import com.lucky.deer.configuration.KeyConstant; import com.lucky.deer.find.business.adapter.RedEnvelopesDetailAdapter; import com.lucky.deer.find.business.redEnvelope.RedEnvelopeInfoActivity; import com.lucky.deer.find.withdraw.FindWithdrawalActivity; import com.lucky.model.request.BaseReq; import com.lucky.model.response.find.redEnvelope.PageBean; import com.lucky.model.response.find.redEnvelope.RedEnvelopesDetailEntity; import com.lucky.model.util.HintUtil; import com.lucky.model.util.RxBus; import java.util.List; import butterknife.BindView; import xyz.yhsj.loadstatusview.LoadStatusView; /** * 红包明细列表 * * @author wangxiangyi * @date 2019/03/26 */ public class RedEnvelopesDetailFragment extends BaseFragment { /** * 收到的红包 */ public static final String RECEIVED_RED_ENVELOPE = "receivedRedEnvelope"; /** * 我发的红包 */ public static final String SENT_RED_ENVELOPE = "sentRedEnvelope"; /** * 共收到/共发出 */ TextView tvIssueOrReceive; /** * 当前资金 */ TextView tvCurrentFunds; /** * 去提现 */ TextView btnWithdrawCash; /** * 下拉刷新控件 */ @BindView(R.id.srl_refresh) SwipeRefreshLayout srlRefresh; /** * 空白页面 */ @BindView(R.id.lsv_load_status) LoadStatusView lsvLoadStatus; /** * 列表 */ @BindView(R.id.rv_list) RecyclerView rvList; /** * 页面标记 */ private String mPageMark; /** * 列表页面 */ private RedEnvelopesDetailAdapter mAdapter; private RedEnvelopesDetailEntity mData; public static RedEnvelopesDetailFragment newInstance(Bundle args) { RedEnvelopesDetailFragment fragment = new RedEnvelopesDetailFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mPageMark = getArguments().getString(mEntity); } } @Override protected int initlayout() { return R.layout.fragment_red_envelopes_detail; } @SuppressLint("CheckResult") @Override protected void initView() { rvList.setLayoutManager(new LinearLayoutManager(mActivity)); mAdapter = new RedEnvelopesDetailAdapter(); if (!TextUtils.isEmpty(mPageMark)) { switch (mPageMark) { case RECEIVED_RED_ENVELOPE: mAdapter.isReceiveRedEnvelope(true); break; case SENT_RED_ENVELOPE: mAdapter.isReceiveRedEnvelope(false); break; default: } } rvList.setAdapter(mAdapter); rvList.addItemDecoration(new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL)); initHeaderLayout(); /*红包明细更新*/ RxBus.getInstance() .toObservable() .subscribe(retrenData -> { if (!TextUtils.isEmpty(retrenData) && KeyConstant.UPDATE_RED_ENVELOPE_DETAILS.equals(retrenData)) { initData(); } }); } @Override protected void initListener() { /*下拉刷新*/ srlRefresh.setOnRefreshListener(this::initData); /*上拉加载*/ mAdapter.setOnLoadMoreListener(this::initData, rvList); /*点击红包明细列表监听*/ mAdapter.setOnItemClickListener((adapter, view, position) -> { startActivity(new Intent(mActivity, RedEnvelopeInfoActivity.class).putExtra(mEntity, mAdapter.getData().get(position).getAdvertId())); }); } @Override protected void initData() { BaseReq baseReq = new BaseReq(); if (srlRefresh != null && srlRefresh.isRefreshing()) { pageCurrent = 1; baseReq.setPageCurrent(pageCurrent); } else if (pageCurrent > 1) { baseReq.setPageCurrent(pageCurrent); } else { showLoadingDialog(); } if (mPageMark != null) { switch (mPageMark) { /*收到的红包*/ case RECEIVED_RED_ENVELOPE: /*查询用户领取红包明细*/ mNetworkRequestInstance.userReceiveRedEnvelope(baseReq) .subscribe(returnData -> { dismissLoadingDialog(); if (srlRefresh != null) { srlRefresh.setRefreshing(false); } if (lsvLoadStatus != null) { lsvLoadStatus.setViewState(LoadStatusView.VIEW_STATE_CONTENT); } if (RequestUtils.isRequestSuccess(returnData)) { mData = returnData.getData(); setData(); List<PageBean> list = mData.getPage(); if (list != null) { if (baseReq.getPageCurrent() == 1) { mAdapter.setNewData(list); if (list.size() >= baseReq.getPageSize()) { pageCurrent++; } else { /*加载结束*/ mAdapter.loadMoreEnd(true); } } else if (list.size() >= baseReq.getPageSize()) { mAdapter.addData(list); /*加载完成*/ mAdapter.loadMoreComplete(); pageCurrent++; } else { mAdapter.addData(list); /*加载结束*/ mAdapter.loadMoreEnd(); } } else { lsvLoadStatus.setViewState(LoadStatusView.VIEW_STATE_EMPTY); mAdapter.notifyDataSetChanged(); } } else if (RequestUtils.isEmpty(returnData)) { lsvLoadStatus.setViewState(LoadStatusView.VIEW_STATE_EMPTY); mAdapter.notifyDataSetChanged(); } else { if (pageCurrent > 1) { /*加载失败*/ mAdapter.loadMoreFail(); } HintUtil.showErrorWithToast(mActivity, returnData.getMsg()); } }); break; /*我发的红包*/ case SENT_RED_ENVELOPE: /*查询用户发放红包明细*/ mNetworkRequestInstance.userIssueRedEnvelope(baseReq) .subscribe(returnData -> { dismissLoadingDialog(); if (srlRefresh != null) { srlRefresh.setRefreshing(false); } if (lsvLoadStatus != null) { lsvLoadStatus.setViewState(LoadStatusView.VIEW_STATE_CONTENT); } if (RequestUtils.isRequestSuccess(returnData)) { mData = returnData.getData(); setData(); List<PageBean> list = mData.getPage(); if (list != null) { if (baseReq.getPageCurrent() == 1) { mAdapter.setNewData(list); if (list.size() >= baseReq.getPageSize()) { pageCurrent++; } else { /*加载结束*/ mAdapter.loadMoreEnd(true); } } else if (list.size() >= baseReq.getPageSize()) { mAdapter.addData(list); /*加载完成*/ mAdapter.loadMoreComplete(); pageCurrent++; } else { mAdapter.addData(list); /*加载结束*/ mAdapter.loadMoreEnd(); } } else { lsvLoadStatus.setViewState(LoadStatusView.VIEW_STATE_EMPTY); mAdapter.notifyDataSetChanged(); } } else if (RequestUtils.isEmpty(returnData)) { lsvLoadStatus.setViewState(LoadStatusView.VIEW_STATE_EMPTY); mAdapter.notifyDataSetChanged(); } else { if (pageCurrent > 1) { /*加载失败*/ mAdapter.loadMoreFail(); } HintUtil.showErrorWithToast(mActivity, returnData.getMsg()); } }); break; default: } } } /** * 初始化头部布局 */ private void initHeaderLayout() { /*获取计划详情信息头部*/ View headerView = LinearLayout.inflate(mActivity, R.layout.fragment_header_red_envelopes_detail, null); getHeaderViewId(headerView); initHeaderListener(); setData(); if (!mAdapter.isHeaderViewAsFlow()) { mAdapter.removeAllHeaderView(); } mAdapter.addHeaderView(headerView); } /** * 获取头部控件 */ private void getHeaderViewId(View headerView) { /* 共收到/共发出*/ tvIssueOrReceive = headerView.findViewById(R.id.tv_issue_or_receive); /*当前资金*/ tvCurrentFunds = headerView.findViewById(R.id.tv_current_funds); /*提现按钮*/ btnWithdrawCash = headerView.findViewById(R.id.btn_withdraw_cash); } /** * 头部监听 */ private void initHeaderListener() { /*点击提现*/ btnWithdrawCash.setOnClickListener(v -> { if (mData != null) { startActivity(new Intent(mActivity, FindWithdrawalActivity.class).putExtra(mEntity, mData)); } }); } /** * 设置头部数据 */ private void setData() { if (TextUtils.isEmpty(mPageMark)) { tvIssueOrReceive.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_received_total), "0.00"))); tvCurrentFunds.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_current_funds), "0.00"))); } else { if (mData != null) { switch (mPageMark) { /*收到的红包*/ case RECEIVED_RED_ENVELOPE: tvIssueOrReceive.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_received_total), TextUtils.isEmpty(mData.getReceiveNum()) ? "0" : mData.getReceiveNum()))); break; /*我发的红包*/ case SENT_RED_ENVELOPE: tvIssueOrReceive.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_issued), TextUtils.isEmpty(mData.getIssueNum()) ? "0" : mData.getIssueNum()))); break; default: } tvCurrentFunds.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_current_funds), TextUtils.isEmpty(mData.getWalletMoney()) ? "0" : mData.getWalletMoney()))); } else { switch (mPageMark) { /*收到的红包*/ case RECEIVED_RED_ENVELOPE: tvIssueOrReceive.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_received_total), "0"))); break; /*我发的红包*/ case SENT_RED_ENVELOPE: tvIssueOrReceive.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_issued), "0"))); break; default: } tvCurrentFunds.setText(Html.fromHtml(String.format(getString(R.string.text_red_envelopes_detail_current_funds), "0.00"))); } } } }
true
836005e5fa3fba1a89d9bb39f40409bcc3404ae6
Java
MavonCmc/OA
/sys-oa/service-admin/src/main/java/cn/yj/admin/frame/shiro/reaml/ShiroRealm.java
UTF-8
4,368
2.25
2
[]
no_license
package cn.yj.admin.frame.shiro.reaml; import cn.yj.admin.ConsVal; import cn.yj.admin.entity.po.User; import cn.yj.admin.frame.shiro.ShiroCredentialsMatcher; import cn.yj.admin.service.IPermissionService; import cn.yj.admin.service.IRoleService; import cn.yj.admin.service.LoginService; import cn.yj.common.LoginUser; import cn.yj.common.Status; import cn.yj.commons.utils.StringUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authc.credential.CredentialsMatcher; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import java.util.*; import java.util.stream.Collectors; /** * <p> * * </p> * * @author 永健 * @since 2020-05-21 22:31:42 */ public class ShiroRealm extends AuthorizingRealm{ private final static Logger LOGGER = LoggerFactory.getLogger(ShiroRealm.class); @Autowired @Lazy private LoginService userService; @Autowired @Lazy private IRoleService roleService; @Autowired @Lazy private IPermissionService permissionService; /** * 授权 * * @param principals * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { LoginUser principal = (LoginUser) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo; if (!principal.isAdmin()) { List<Map<String, Object>> rolesList = principal.getRoles(); Set<String> code = rolesList.stream().map(role -> (String) role.get("code")).collect(Collectors.toSet()); authorizationInfo = new SimpleAuthorizationInfo(code.stream().filter(a -> !StringUtils.isBlank(a)).collect(Collectors.toSet())); authorizationInfo.setStringPermissions(principal.getPermission().stream().filter(a -> !StringUtils.isBlank(a)).collect(Collectors.toSet())); }else { authorizationInfo=new SimpleAuthorizationInfo(); authorizationInfo.addStringPermission("*:*:*"); authorizationInfo.addRole(ConsVal.SUPER_ADMIN_CODE); } return authorizationInfo; } /** * 登陆 * * @param token * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //加盐 计算盐值 保证每个加密后的 MD5 不一样 登录名+随机字符窜 UsernamePasswordToken u_pTaken = (UsernamePasswordToken) token; String username = u_pTaken.getUsername(); User user = userService.selectByLoginName(username); if (user == null) { throw new UnknownAccountException("用户不存在"); } if (user.getStatus().equals(Status.User.禁用.getCode())) { throw new UnknownAccountException("此账户不可用"); } LoginUser loginUser = new LoginUser(); loginUser.setId(user.getId()); loginUser.setName(user.getName()); loginUser.setLoginName(user.getLoginName()); loginUser.setToken(UUID.randomUUID().toString()); loginUser.setEmpCode(user.getEmpCode()); List<Map<String, Object>> maps = roleService.selectRolesNameCodeIdByUserId(user.getId()); maps.forEach(map -> map.forEach((key, val) -> { if ("code".equals(key) && ConsVal.SUPER_ADMIN_CODE.equals(val)) { loginUser.setAdmin(true); } })); loginUser.setRoles(maps); // 权限 loginUser.setPermission(permissionService.selectUserPermissionCodes(user.getId())); if (loginUser.isAdmin()){ Set<String> perms = new HashSet<>(); perms.add("*:*:*"); loginUser.setPermission(perms); } return new SimpleAuthenticationInfo(loginUser, user.getPassword(), null, this.getName()); } @Override public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) { super.setCredentialsMatcher(new ShiroCredentialsMatcher()); } }
true
c06d9710cb47c05bc111f6dd6eaf0bc9cd47256e
Java
zhao-qc/zstack
/storage/src/main/java/org/zstack/storage/volume/DefaultVolumeAttachedJudger.java
UTF-8
648
2.1875
2
[ "Apache-2.0" ]
permissive
package org.zstack.storage.volume; import org.zstack.header.volume.VolumeAttachedJudger; import org.zstack.header.volume.VolumeInventory; import java.util.Collections; import java.util.List; /** * Created by MaJin on 2019/5/30. */ public class DefaultVolumeAttachedJudger implements VolumeAttachedJudger { @Override public Boolean isAttached(VolumeInventory inv) { return inv.getVmInstanceUuid() != null; } @Override public List<String> getAttachedVmUuids(VolumeInventory inv) { return inv.getVmInstanceUuid() == null ? Collections.emptyList() : Collections.singletonList(inv.getVmInstanceUuid()); } }
true
c6c837c59f9e7acc1d2bca70ac7581d7ea656e64
Java
VijayEluri/ProgrammingPearls
/src/Interleaving.java
UTF-8
2,571
4.09375
4
[]
no_license
/** * Given two strings, compute all its interleavings. e.g For "AB" and "CD" we * have: "ABCD" "ACBD" "ACDB" "CABD" "CDAB" "CADB" * * Working: * compute("AB","CD") * A + compute(B,CD) C + compute(AB,D) * B + compute(,CD) || C + compute(B,D) * + C + compute(,D) || + B + compute(D) || D + compute(B) * D + compute(,) || + D + compute(,) || + B + compute(,) * ABCD || ACBD || ACDB * @author chandershivdasani * */ import java.util.*; public class Interleaving { public static void computeInterleavings(String first, String second, StringBuilder result) { /* * When both the strings are empty, print the result string */ if (first.length() == 0 && second.length() == 0) { System.out.println(result); result = new StringBuilder(); } /* * If first string is non-empty, append the first character * to the result and recurse on the remaining. * Check the example in the description. The characters are * being deleted, when we are moving up in the stack * * AB, CD -> A + compute(B,CD) ... */ if(first.length() > 0) { computeInterleavings(first.substring(1), second, result.append(first.charAt(0))); result.deleteCharAt(result.length() - 1); } /* *Do the same thing when second string is non empty *AB,CD -> C + compute(AB,D) ... */ if(second.length() > 0) { computeInterleavings(first,second.substring(1), result.append(second.charAt(0))); result.deleteCharAt(result.length() - 1); } } /* * Check whether the particular pattern is interleaving of two strings */ public static boolean checkInterleaving(String input1, String input2, String pattern) { if(pattern.length() != (input1.length() + input2.length())) { return false; } char[] patternTokens = pattern.toCharArray(); char[] input1Tokens = input1.toCharArray(); char[] input2Tokens = input2.toCharArray(); int j=0, k=0; for(int i = 0; i < patternTokens.length; i++) { if(j < input1.length() && (patternTokens[i] == input1Tokens[j])) j++; else if(k < input2.length() && (patternTokens[i] == input2Tokens[k])) k++; else return false; } return true; } public static void main(String[] args) { //computeInterleavings("ABC", "DEF", new StringBuilder()); System.out.println(checkInterleaving("AB", "CD", "ABCD")); } }
true
2b17fe246b20e9a3349b0e1d80569509dc0b72dc
Java
VitaliiBashta/Trunk
/java/l2trunk/gameserver/network/serverpackets/ObserverStart.java
UTF-8
484
2.015625
2
[]
no_license
package l2trunk.gameserver.network.serverpackets; import l2trunk.gameserver.utils.Location; public class ObserverStart extends L2GameServerPacket { // ddSS private final Location _loc; public ObserverStart(Location loc) { _loc = loc; } @Override protected final void writeImpl() { writeC(0xeb); writeD(_loc.x); writeD(_loc.y); writeD(_loc.z); writeC(0x00); writeC(0xc0); writeC(0x00); } }
true
f5c156762282682bee7322c39729d70945fa9cde
Java
zzcwzhang/catchfishServer
/java/com/fuyun/server/db/dto/LoadMailBack.java
UTF-8
2,054
2.09375
2
[]
no_license
package com.fuyun.server.db.dto; import java.util.Date; public class LoadMailBack { private int result; private String sender; private Date sendTime; private String title; private String content; private int atmType; private int atmCount; private int isReceivced; public LoadMailBack() { super(); } public LoadMailBack(String sender, Date sendTime, String title, String content) { super(); result = 1; this.sender = sender; this.sendTime = sendTime; this.title = title; this.content = content; } public LoadMailBack(String sender, Date sendTime, String title, String content, int atmType, int atmCount) { super(); this.sender = sender; this.sendTime = sendTime; this.title = title; this.content = content; this.atmType = atmType; this.atmCount = atmCount; } public int getResult() { return result; } public void setResult(int result) { this.result = result; } public int getIsReceivced() { return isReceivced; } public void setIsReceivced(int isReceivced) { this.isReceivced = isReceivced; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public Date getSendTime() { return sendTime; } public void setSendTime(Date sendTime) { this.sendTime = sendTime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getAtmType() { return atmType; } public void setAtmType(int atmType) { this.atmType = atmType; } public int getAtmCount() { return atmCount; } public void setAtmCount(int atmCount) { this.atmCount = atmCount; } @Override public String toString() { return "LoadMailBack [sender=" + sender + ", sendTime=" + sendTime + ", title=" + title + ", content=" + content + ", atmType=" + atmType + ", atmCount=" + atmCount + "]"; } }
true
903dd491cb04842e167dead6869c213b56433a7e
Java
Ivanich85/DatabaseControllerWithJDBC
/src/main/java/consoleview/TableViewer.java
UTF-8
2,351
3.234375
3
[]
no_license
package consoleview; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * Created by ivand on 05.04.2018. */ public class TableViewer { //Ширина столбцов в таблице (для форматирования) private static final String SMALL_STRING_WIDTH = " %-10s "; private static final String MIDDLE_STRING_WIDTH = " %-25s "; private static final String LARGE_STRING_WIDTH = " %-50s "; //Имена столбцов в таблице (для форматирования) private static final String ID = "id"; private static final String IS_READ = "is_read"; private static final String DATE_OF_PUBLICATION = "date_of_publication"; private static final String TABLE_IS_EMPTY_MESSAGE = "В таблице нет записей"; public static void showDatabase(ResultSet resultSet) throws SQLException { if (resultSet.next()) { ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); int numberOfColumns = resultSetMetaData.getColumnCount(); //Заголовок таблицы formatTableRecord(resultSetMetaData, numberOfColumns, null); //Тело таблицы do { formatTableRecord(resultSetMetaData, numberOfColumns, resultSet); } while (resultSet.next()); } else { System.out.println(TABLE_IS_EMPTY_MESSAGE); } } //Форматируем ширину колонок private static void formatTableRecord(ResultSetMetaData metaData, int columns, ResultSet resSet) throws SQLException { String formatter; for (int i = 1; i <= columns; i++) { if (metaData.getColumnName(i).equals(ID) || metaData.getColumnName(i).equals(IS_READ)) { formatter = SMALL_STRING_WIDTH; } else if (metaData.getColumnName(i).equals(DATE_OF_PUBLICATION)) { formatter = MIDDLE_STRING_WIDTH; } else { formatter = LARGE_STRING_WIDTH; } if (resSet != null) { System.out.printf(formatter, resSet.getObject(i)); } else { System.out.printf(formatter, metaData.getColumnName(i)); } } System.out.println(); } }
true
8c1fb0e76de8e31ce05762e2ce1a1ee15dd2a84c
Java
goyalshubhangi/practicals_3_year
/It/jsp_javascript/chocotag.java
UTF-8
544
2.328125
2
[ "MIT" ]
permissive
package P6; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class chocotag extends SimpleTagSupport { private String texture; chocobean chocoBean = new chocobean(); public void setTexture(String texture){ this.texture = texture; chocoBean.setTexture(texture); } public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.print("Texture : " + texture); out.println("\tNames : " + chocoBean.getTexture()); } }
true
1dcb0263253d0b7e8dfab47ebdaa51911ab98ce8
Java
Zebrap/WhatToDo
/app/src/main/java/whattodo/whattodo/MainActivity.java
UTF-8
7,064
1.898438
2
[]
no_license
package whattodo.whattodo; import android.content.Intent; import android.content.SharedPreferences; import android.net.wifi.hotspot2.pps.Credential; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.cloudrail.si.CloudRail; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btnLogin,btnRegister; private EditText etUsername, etPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CloudRail.setAppKey("5be18e9b21b62e5228c9e7da"); etUsername = findViewById(R.id.etUsername); etPassword = findViewById(R.id.etPasword); btnLogin = findViewById(R.id.btnLogin); btnRegister = findViewById(R.id.btnRegister); btnLogin.setOnClickListener(this); btnRegister.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnLogin: btnLogin.setEnabled(false); final String username = etUsername.getText().toString(); final String password = etPassword.getText().toString(); String url ="https://whattodowebservice.azurewebsites.net/login?login="+username+"&password="+password; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); String success = jsonObject.getString("result"); String can_rate = jsonObject.getString("can_rate"); String attraction_id = jsonObject.getString("ATTRACTION_ID"); JSONObject jsonPref = new JSONObject(jsonObject.getString("preferences")); String price = jsonPref.getString("Cena"); String distance = jsonPref.getString("Odleglosc"); String food = jsonPref.getString("Jedzenie"); String alcohol = jsonPref.getString("Alkohol"); String group = jsonPref.getString("Grupowe"); String tourism = jsonPref.getString("Zabytki"); String active = jsonPref.getString("Aktywne"); String time = jsonPref.getString("CzasMax"); Log.d("array","array: "+price); if(success.equals("true")){ SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode SharedPreferences.Editor editor = pref.edit(); editor.putString("username",username); editor.putString("price",price); editor.putString("distance",distance); editor.putString("food",food); editor.putString("alcohol",alcohol); editor.putString("group",group); editor.putString("tourism",tourism); editor.putString("active",active); editor.putString("time",time); editor.putString("find",can_rate); editor.putString("attraction_id",attraction_id); editor.commit(); Intent intent = new Intent(MainActivity.this,Main2Activity.class); intent.putExtra("username",username); btnLogin.setEnabled(true); MainActivity.this.startActivity(intent); }else{ AlertDialog.Builder bulder = new AlertDialog.Builder(MainActivity.this); btnLogin.setEnabled(true); bulder.setMessage("Logowanie nieudane") .setNegativeButton("spróbuj ponownie: ",null) .create() .show(); } } catch (JSONException e) { btnLogin.setEnabled(true); Toast.makeText(MainActivity.this, "Logowanie nieudane", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { btnLogin.setEnabled(true); AlertDialog.Builder bulder = new AlertDialog.Builder(MainActivity.this); bulder.setMessage("Error") .setNegativeButton("Error",null) .create() .show(); } }); RequestQueue queue = Volley.newRequestQueue(MainActivity.this); queue.add(stringRequest); break; case R.id.btnRegister: startActivity(new Intent(this,Register.class)); break; } } @Override public void onBackPressed() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
true
d73867069308dffca505d7b757bf3662704e36c5
Java
Soben713/AbdSQL
/src/main/java/db/fieldType/IntFieldType.java
UTF-8
376
2.46875
2
[]
no_license
package db.fieldType; import db.Cell; /** * Created by user on 26/01/16 AD. */ public class IntFieldType extends FieldType { @Override public Cell.CellType[] getCellTypes() { Cell.CellType[] cellTypes = {Cell.CellType.INTEGER, Cell.CellType.NULL}; return cellTypes; } @Override public String toString() { return "INT"; } }
true
e8cfefe1e7b77b6839fbb548a255f72cbbbc1219
Java
WKrC/ssmtest
/src/main/java/com/wkr/service/Impl/ReaderServiceImpl.java
UTF-8
1,032
2.125
2
[]
no_license
package com.wkr.service.Impl; import com.wkr.bean.ReaderBean; import com.wkr.dao.ReaderDao; import com.wkr.service.ReaderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ReaderServiceImpl implements ReaderService { @Autowired ReaderDao readerDao; @Override public ReaderBean fetchReaderByMAC(ReaderBean readerBean) { return readerDao.fetchReaderByMAC(readerBean); } @Override public void saveReaderSetting(ReaderBean readerBean) { readerDao.saveReaderSetting(readerBean); } @Override public List<ReaderBean> getTotalCount() { return readerDao.getTotalCount(); } @Override public void updateReaderSetting(ReaderBean readerBean) { readerDao.updateReaderSetting(readerBean); } @Override public void updateReaderIsOnline(String MAC, Integer isOnline) { readerDao.updateReaderIsOnline(MAC, isOnline); } }
true
e36db7bce234b2b0a3e1319d18a6417502504a19
Java
RamyElkest/SEPR
/src/controller/executor/ChangeNameExecutor.java
UTF-8
3,329
3.46875
3
[]
no_license
package controller.executor; import controller.parser.CommandType; import model.gameEngine.GameEngineInterface; import model.gameEngine.ExecutorEvent; import model.world.Player; /** * Handles the NAME command. The NameExecutor asks the user for their name * and changes the players name to the user input * * @author Yaks */ public class ChangeNameExecutor extends Executor { /** * Constructor * @param gameEngine Object controlling the game */ public ChangeNameExecutor(GameEngineInterface gameEngine) { super(gameEngine); } /** * Called by InputHandler, * Transforms an ExecutorEvent into a String for onInput for execution * @param event Input event to execute */ @Override public void handleInput(ExecutorEvent event) { // Ensure the Name entered is not "quit", if it is simulate a quit command. if(event.getCommand().getType() == CommandType.QUIT){ this.gameEngine.getStandardMessageGenerator().askIfWishToSaveBeforeExitting(); this.gameEngine.getInputHandler().pushExecutor(new ExitExecutor(this.gameEngine)); return; } this.onInput(event.getInput()); } /** * Handles input from the user, a call to this method is simulated on loading the default world * in the gameEngine, with an input parameter of "". * @param input Input from the user */ public void onInput(String input) { //If the user has entered a string as an input if(input != null){ // Split name into words. String [] words = input.split("[ \t]+"); // Don't accept a blank or whitespace name. if (words.length == 0) { gameEngine.getBrowser().println("Name cannot be blank."); } else { // Skip the first index if blank - ignore leading whitespace. int first = ((words[0].length() == 0) ? 1 : 0); // Name is also blank if words.length == 1 and first == 1. // words.length == first is a shortcut for this as we already know words.length != 0 if (words.length == first) { gameEngine.getBrowser().println("Name cannot be blank."); } else { // Titlecase the name if all lowercase (otherwise assume it's properly capitalised), and normalise whitespaces to 1. String name; if (input.toLowerCase().equals(input)) { name = Character.toUpperCase(words[first].charAt(0)) + words[first].substring(1); for (int i = first + 1; i < words.length; i++) { name += " " + Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1).toLowerCase(); } } else { name = words[first]; for (int i = first + 1; i < words.length; i++) { name += " " + words[i]; } } //Set the player's name to the input entered gameEngine.getWorld().getPlayer().setName(name); this.gameEngine.getInputHandler().popExecutor(); //Get the Player Player player = gameEngine.getWorld().getPlayer(); //Output to user that their name has been set gameEngine.getBrowser().println("Name set as: "+ player.getName()); // Display player's name location and description gameEngine.getStandardMessageGenerator().showCurrentPlayerRoom(player.getCurrentRoom()); } } } } }
true
a955e53ee3f41d5dc55cd07b8030a38398f522ce
Java
nbahije/Manage-contacts-with-Spring-Boot-Data-MVC-Security-Thymeleaf
/src/main/java/com/example/dao/ContactRepository.java
UTF-8
385
1.851563
2
[]
no_license
package com.example.dao; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import com.example.entities.Contact; public interface ContactRepository extends JpaRepository<Contact, Long> { public Page<Contact> findByNomContains(String mc,Pageable pageable); }
true
b5f6a3d9a4899ae703c1d5e11a8aa72a8213d488
Java
carllindiii/378-lab2
/PicnicDefense/WinningScreen.java
UTF-8
550
2.828125
3
[]
no_license
import greenfoot.*; /** * Write a description of class WinningScreen here. * * @author (your name) * @version (a version number or a date) */ public class WinningScreen extends Background { public WinningScreen() { setImage(new GreenfootImage("WinningScreen.png")); } /** * Act - do whatever the WinningScreen wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
true
7456df1a47ed4acf0ca6a5c300ad804f33d495f3
Java
imran1007/3BIN
/I314C_Design_Patterns/Revision/Seance10_IPLCommander/src/remote/HTTPUtils.java
UTF-8
5,576
2.84375
3
[]
no_license
package remote; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import javax.net.ssl.HttpsURLConnection; /** * Created by GROLAUX on 20/04/2016. */ public class HTTPUtils { public static class HTTPException extends RuntimeException { private int code; HTTPException(int code, String message) { super(message); this.code = code; } public int getHTTPStatus() { return code; } } public static class HTTPNetworkException extends RuntimeException { HTTPNetworkException(Throwable parent) { super(parent); } } private HTTPUtils() { } public static String performGetCall(String requestURL) { return performGetCall(requestURL, null); } public static String performGetCall(String requestURL, Map<String, String> requestParams) { HttpURLConnection conn = null; try { if (requestParams != null) { requestURL = requestURL + "?" + getPostDataString(requestParams); } URL url = new URL(requestURL); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); String read; while ((read = br.readLine()) != null) { sb.append(read); } br.close(); return sb.toString(); } else { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream(),"UTF-8")); String read; while ((read = br.readLine()) != null) { sb.append(read); } br.close(); throw new HTTPException(responseCode, sb.toString()); } } catch (Exception e) { throw new HTTPNetworkException(e); } finally { if (conn != null) conn.disconnect(); } } public static String performPostCall(String requestURL) { return performPostCall(requestURL, null); } public static String performPostCall(String requestURL, Map<String, String> requestParams) { URL url; HttpURLConnection conn = null; try { url = new URL(requestURL); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); if (requestParams != null) { writer.write(getPostDataString(requestParams)); } writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); String read; String sep=""; while ((read = br.readLine()) != null) { sb.append(sep); sb.append(read); sep="\n"; } br.close(); return sb.toString(); } else { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream(),"UTF-8")); String read; String sep=""; while ((read = br.readLine()) != null) { sb.append(sep); sb.append(read); sep="\n"; } br.close(); throw new HTTPException(responseCode, sb.toString()); } } catch (Exception e) { throw new HTTPNetworkException(e); } finally { if (conn != null) conn.disconnect(); } } private static String getPostDataString(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } }
true
1bf1d963b11a4c1b29129810ad115e9164c6cee7
Java
kKarola1999/eights_two
/src/Game.java
UTF-8
13,000
3.609375
4
[]
no_license
import java.util.ArrayList; import java.util.Scanner; import java.util.Random; import java.util.InputMismatchException; public class Game { /** * Enum type to represent the game status */ public enum Status {CONTINUE, WON, LOST, TIE} public static void main(String[] args) { // Create two players; one computer and one human Player you = new Player("player"); Player player1 = new Player("player1"); // Create a deck of 52 unique, shuffled cards ArrayList<Card> deck = Card.createDeck(); // Initialize the game status Status gameStatus = Status.CONTINUE; String reasonGameOver = ""; String newSuit = ""; // When an "8" is played // Create Scanner to obtain inputs Scanner input = new Scanner(System.in); // Prompt user to begin System.out.println("Press the Enter key to play a crazy game of Crazy Eights ..."); try { System.in.read(); } catch (Exception e) { e.printStackTrace(); } // Randomly select who goes first- Player or Computer Player firstCardPlayer = Rules.randomPlayer(you, player1); Player secondCardPlayer = (firstCardPlayer == you) ? player1 : you; // Deal cards for (int c = 0; c < Rules.CARDS_TO_DEAL; c++) { firstCardPlayer.takeCardFromTopOfDeck(deck); secondCardPlayer.takeCardFromTopOfDeck(deck); } System.out.println(you + " and " + player1 + " were dealt " + Rules.CARDS_TO_DEAL + " cards each."); // Initialize the up card String topCardFaceValue; Card topCard; do { topCard = deck.get(0); deck.remove(0); topCardFaceValue = topCard.getValue(); // Up card cannot be an "8". Throw it back in the deck somewhere. if (topCardFaceValue.equals("8")) { // Randomly place somewhere back in the deck Random rand = new Random(); deck.add(rand.nextInt(deck.size()), topCard); } } while (topCardFaceValue.equals("8")); // Randomly select who goes first- Player or Computer Player nextUp = secondCardPlayer; System.out.println("Up card to start: " + topCard); System.out.println(nextUp + " goes first!\n"); while (gameStatus == Status.CONTINUE) { if (nextUp == you) { boolean needALineBreak = false; // Reset every turn; reserved for scenarios where there are no cards to draw and no cards to play //you.setSkipStatus(false); // If you cannot play a card, you have to take one from the top while (!you.canPlayCardThisTopCard(newSuit, topCard)) { needALineBreak = true; if (deck.size() != 0) { you.takeCardFromTopOfDeck(deck); System.out.println("No cards to play. Player draws a: " + you.getHand().get(you.numberOfCardsInHand() - 1)); } else { you.setSkipStatus(true); System.out.println("No cards to play. No cards to draw from deck. Skipping " + you + "'s turn."); break; } } // For formatting in the terminal if (needALineBreak) System.out.println(); // Update game status for Player if (!you.skipped()) { System.out.println("Cards left ..... " + deck.size()); System.out.println((newSuit.length() == 0) ? "Top card ....... " + topCard : "New suit ....... " + Card.pairTypeWithUnicode(newSuit)); System.out.println(you.getHandAndChoices()); System.out.print("\nYour's decision: "); nextUp=player1; newSuit=""; } // Make sure you can lay down the card boolean validPlay = false; while (!validPlay ) { try { // Sentinel-controlled iteration Card cardChoiceObject = you.playCard(input.nextInt()); if (Rules.checkForValidPlay(newSuit, topCard, cardChoiceObject)) { topCard = cardChoiceObject; you.getHand().remove(cardChoiceObject); // Playing a wild card allows the player to select a new suit if (topCard.getValue().equals("8") && you.numberOfCardsInHand() != 0) { System.out.println("\n" + you.getSuitsAndChoices()); System.out.print("\nYour's decision: "); boolean validSuit = false; do { try { newSuit = Card.CARD_TYPES[input.nextInt() -1]; validSuit = true; validPlay = true; nextUp=player1; } catch (IndexOutOfBoundsException e) { handleException("Invalid selection. Please try again."); } catch (InputMismatchException e) { input.next(); handleException("Invalid selection. Please try again."); } } while (!validSuit); } else { validPlay = true; } } else { handleException("You cannot play that card. Please try again."); } } catch (IndexOutOfBoundsException e) { handleException("Invalid selection. Please try again."); } catch (InputMismatchException e) { input.next(); handleException("Invalid selection. Please try again."); } System.out.println(); } } else { boolean needALineBreak = false; // For formatting in the terminal // Reset every turn; reserved for scenarios where there are no cards to draw and no cards to play //you.setSkipStatus(false); // If you cannot play a card, you have to take one from the top while (!player1.canPlayCardThisTopCard(newSuit, topCard)) { needALineBreak = true; if (deck.size() != 0) { player1.takeCardFromTopOfDeck(deck); System.out.println("No cards to play. Player draws a: " + player1.getHand().get(player1.numberOfCardsInHand() - 1)); } else { player1.setSkipStatus(true); System.out.println("No cards to play. No cards to draw from deck. Skipping " + player1 + "'s turn."); break; } } // For formatting in the terminal if (needALineBreak) System.out.println(); // Update game status for Player if (!player1.skipped()) { System.out.println("Cards left ..... " + deck.size()); System.out.println((newSuit.length() == 0) ? "Top card ....... " + topCard : "New suit ....... " + Card.pairTypeWithUnicode(newSuit)); System.out.println(player1.getHandAndChoices()); System.out.print("\nPlayer's 1 decision: "); nextUp=you; newSuit=""; } // Make sure you can lay down the card boolean validPlay = false; while (!validPlay ) { try { // Sentinel-controlled iteration Card cardChoiceObject = player1.playCard(input.nextInt()); if (Rules.checkForValidPlay(newSuit, topCard, cardChoiceObject)) { topCard = cardChoiceObject; player1.getHand().remove(cardChoiceObject); // Playing a wild card allows the player to select a new suit if (topCard.getValue().equals("8") && player1.numberOfCardsInHand() != 0) { System.out.println("\n" + player1.getSuitsAndChoices()); System.out.print("\nPlayer's 1 decision: "); boolean validSuit = false; do { try { newSuit = Card.CARD_TYPES[input.nextInt() -1]; validSuit = true; validPlay = true; nextUp=you; } catch (IndexOutOfBoundsException e) { handleException("Invalid selection. Please try again."); } catch (InputMismatchException e) { input.next(); handleException("Invalid selection. Please try again."); } } while (!validSuit); } else { validPlay = true; } } else { handleException("You cannot play that card. Please try again."); } } catch (IndexOutOfBoundsException e) { handleException("Invalid selection. Please try again."); } catch (InputMismatchException e) { input.next(); handleException("Invalid selection. Please try again."); } System.out.println(); } } } // See if there is a winner if (you.numberOfCardsInHand() == 0) { gameStatus = Status.WON; reasonGameOver = "Player wins- they were able to get rid of their cards first!"; } else if (player1.numberOfCardsInHand() == 0) { gameStatus = Status.LOST; reasonGameOver = "Computer wins- they were able to get rid of their cards first!"; } else if (deck.size() == 0 ) { gameStatus = Rules.determineWinner(you, player1); if (gameStatus.equals(Status.WON)) { reasonGameOver = "Player wins!- their card total is less than the Computer's card total."; } else if (gameStatus.equals(Status.LOST)) { reasonGameOver = "Computer wins!- their card total is less than the Player's card total."; } else { gameStatus = Status.TIE; reasonGameOver = "Tie!- Player's card total and Computer's card total are the same."; } } else { // Reset this variable once a card has been played after a crazy eight if (!topCard.getValue().equals("8") && newSuit.length() > 0) { newSuit = ""; } // Swap turns nextUp = (nextUp == firstCardPlayer) ? secondCardPlayer : firstCardPlayer; } } // Explain what happened. The game is over. //System.out.println(reasonGameOver); /** * Helper method to reduce code duplication * * @param message The message printed to the console */ private static void handleException(String message) { System.out.println("\n" + message); System.out.print("\nPlayer decision: "); } }
true
9857f9fa91e39071eeac50137a134e5c5de45509
Java
ggslove/siren0413_Algorithms
/src/Decimal.java
UTF-8
888
3.375
3
[]
no_license
import java.util.*; public class Decimal { public static void main(String[] args) { System.out.println(fractionToDecimal(1, 333)); } public static String fractionToDecimal(int numerator, int denominator) { Map<Integer, Integer> map = new HashMap<>(); StringBuilder sb = new StringBuilder(); sb.append(numerator / denominator); numerator = numerator % denominator; if (numerator == 0) { return sb.toString(); } else { sb.append('.'); } while (numerator * 10 % denominator != 0 && !map.containsKey(numerator * 10 / denominator)) { map.put(numerator * 10 / denominator, sb.length()); sb.append(numerator * 10 / denominator); numerator = numerator * 10 % denominator; } if (numerator * 10 % denominator == 0) { return sb.toString(); } sb.insert(map.get(numerator * 10 / denominator), "("); sb.append(")"); return sb.toString(); } }
true
0fee40c0160a5c5b0bf64dec65844f7dfd86954b
Java
xqgdmg/MyAudioRecorder
/app/src/main/java/com/example/qhsj/myaudiorecorder/MainActivity.java
UTF-8
2,797
2.390625
2
[ "Apache-2.0" ]
permissive
package com.example.qhsj.myaudiorecorder; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import com.example.qhsj.myaudiorecorder.utils.MyAudioRecorder; import java.io.File; import java.util.UUID; public class MainActivity extends AppCompatActivity { private TextView tvStarrt; private TextView tvStop; private MyAudioRecorder myAudioRecorder; boolean first = true; private String path; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initRecorder(); initListener(); } private void initRecorder() { myAudioRecorder = new MyAudioRecorder(new MyAudioRecorder.SoundLevelListener() { @Override public void getSoundLevel(int level) { // sv.addSpectrum(level*density*3); Log.e("chris","level=" + level); } }); myAudioRecorder.setMaxLevel(16); } private void initListener() { tvStarrt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myAudioRecorder.isShowLevel = true; Toast.makeText(MainActivity.this,"开始录音!",Toast.LENGTH_SHORT).show(); startRecord(); // 录音 } }); tvStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"停止录音!",Toast.LENGTH_SHORT).show(); myAudioRecorder.stop(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } private void startRecord() { // 创建文件夹 String dirsPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/chris/Record/"; if (!new File(dirsPath).exists()){ new File(dirsPath).mkdirs(); } path = dirsPath + UUID.randomUUID() + ".wav"; Log.e("path1=",path); myAudioRecorder.start(path); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void initView() { tvStarrt = (TextView) findViewById(R.id.tvStarrt); tvStop = (TextView) findViewById(R.id.tvStop); } @Override public void onDestroy() { super.onDestroy(); myAudioRecorder.stop(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }
true
0921916402acfb0552c1f983d4ac9d610460d44c
Java
willshijan/Proyectos
/NinjaStoreAutomatizacion-master/src/main/java/utils/Country.java
UTF-8
209
2.5
2
[]
no_license
package utils; public enum Country { ESTADOS_UNIDOS("United States"); private String country; Country(String country){ this.country = country; } public String country() { return country; } }
true
0301d6b11eee683b9dbbfbf34d7cadd45049fe91
Java
prayatna-jain/ninjasparrow
/src/test/java/com/ninjasparrow/app/domain/FormSubmissionElementTest.java
UTF-8
999
2.15625
2
[]
no_license
package com.ninjasparrow.app.domain; import static org.assertj.core.api.Assertions.assertThat; import com.ninjasparrow.app.web.rest.TestUtil; import java.util.UUID; import org.junit.jupiter.api.Test; class FormSubmissionElementTest { @Test void equalsVerifier() throws Exception { TestUtil.equalsVerifier(FormSubmissionElement.class); FormSubmissionElement formSubmissionElement1 = new FormSubmissionElement(); formSubmissionElement1.setId(UUID.randomUUID()); FormSubmissionElement formSubmissionElement2 = new FormSubmissionElement(); formSubmissionElement2.setId(formSubmissionElement1.getId()); assertThat(formSubmissionElement1).isEqualTo(formSubmissionElement2); formSubmissionElement2.setId(UUID.randomUUID()); assertThat(formSubmissionElement1).isNotEqualTo(formSubmissionElement2); formSubmissionElement1.setId(null); assertThat(formSubmissionElement1).isNotEqualTo(formSubmissionElement2); } }
true
a09a538b36329c4ef694a15ab3e8a025c4a1d1ed
Java
thbl088/pooProject1
/SpaceandPens/src/Modeles/Player.java
UTF-8
8,047
3.25
3
[]
no_license
package Modeles; import java.util.HashMap; public class Player extends Character { private final HashMap<String, Item> INVENTORY; private int healthPotion = 0; private int attackPotion = 0; private int defensePotion = 0; private int critPotion = 0; private Map currentLocation ; private Armor armor ; private Weapon weapon; private final Armor DEFAULT_ARMOR = new Armor("Space suit", "This uniform represents our nation", -1, 0); private final Weapon DEFAULT_WEAPON = new Weapon("Ax", "It is used to break the windshield", -1, 0); private final int COEF_HP_POTION; private final int COEF_ATT_POTION; private final int COEF_DEF_POTION; private final int COEF_CRIT_POTION; private final int DEFAULT_ATTACK; private final int DEFAULT_DEFENSE; public Player(String name){ super(name, new StatisticsPlayer()); HashMap<String, Item> inv = new HashMap<>(); this.armor = DEFAULT_ARMOR; this.weapon = DEFAULT_WEAPON; this.INVENTORY = inv; this.COEF_HP_POTION = 25; this.COEF_ATT_POTION = 2; this.COEF_DEF_POTION = 2; this.COEF_CRIT_POTION = 2; this.DEFAULT_ATTACK = this.stats.getAttack(); this.DEFAULT_DEFENSE = this.stats.getDefense(); } public void addHealthPotion() { this.healthPotion ++; } public void addDefensePotion() { this.defensePotion ++; } public void addAttackPotion() { this.attackPotion ++; } public void addCritPotion() { this.critPotion++; } public void move(Map newLoc) { this.currentLocation = newLoc; } public Map getMapHero() { return this.currentLocation; } public Item getItem(String item) { return this.INVENTORY.get(item); } public String getNbPotion(){ return "health potion : " + this.healthPotion + "\ndefense potion : " + this.defensePotion + "\nattack potion : " + this.attackPotion + "\ncrit potion : " + this.critPotion; } public void useHealthPotion() { if (this.healthPotion > 0) { this.healthPotion -- ; this.getStatistics().addHealth(COEF_HP_POTION); } else { System.out.println("You don't have any health potion."); } } public void useAttackPotion() { if (this.attackPotion > 0) { this.attackPotion-- ; this.getStatistics().changeAttack(this.getAttack() * COEF_ATT_POTION); System.out.println("new attack = " + this.getAttack()); } else { System.out.println("You don't have any attack potion."); } } public void useDefensePotion() { if (this.defensePotion > 0) { this.defensePotion-- ; this.getStatistics().changeDefense(this.getDefense() * COEF_DEF_POTION); System.out.println("new Defense = " + this.getDefense()); } else { System.out.println("You don't have any defense potion."); } } public void useCritPotion() { if (this.critPotion > 0) { this.critPotion-- ; this.getStatistics().changeCritical(this.getCrit() * COEF_CRIT_POTION); System.out.println("new Critic = " + this.getCrit()); } else { System.out.println("You don't have any crit potion."); } } public void printInventory() { if (!this.INVENTORY.isEmpty()){ for (String i : this.INVENTORY.keySet()) { System.out.println(i); } } else { System.out.println("Inventory is empty."); } } public void removeEquipment(Item item){ if ( item instanceof Weapon && item != DEFAULT_WEAPON) { removeWeapon(((Weapon)item)); } else if ( item instanceof Armor && item != DEFAULT_ARMOR){ removeArmor(((Armor)item)); } else{ System.out.println(item.getName() + " isn't removable."); } showEquipement(); } public void removeWeapon(Weapon item) { // Permet d'enlever son arme on vérifie bien qui n'enlève pas celle de base if (item == DEFAULT_WEAPON) { System.out.println("You can't remove your default weapon."); } else { this.stats.changeAttack(this.DEFAULT_ATTACK + DEFAULT_WEAPON.getAttackBonus()); this.weapon = DEFAULT_WEAPON; } } public void removeArmor(Armor item) { if (item == DEFAULT_ARMOR) { System.out.println("You can't remove your default armor."); } else { this.stats.removeDefense(this.DEFAULT_DEFENSE + DEFAULT_ARMOR.getDefenseBonus()); this.armor = DEFAULT_ARMOR; } } public void addInventory(Item item) { this.INVENTORY.put(item.getName(), item); } public void addEquipment(Item item) { // Permet d'équiper un objet retour avec un print si on peut pas if ( item instanceof Weapon ) { equiWeapon(((Weapon)item)); } else if ( item instanceof Armor ){ equiArmor(((Armor)item)); } else{ System.out.println(item.getName() + "isn't equipable."); } } public void equiWeapon(Weapon item) { // On équipe la nouvelle arme if ( item != this.weapon){ this.stats.removeAttack(this.weapon.getAttackBonus()); // On retire l'ancienne arme this.stats.addAttack(item.getAttackBonus()); this.weapon = item; showEquipement(); } else{ System.out.println("You have already this weapon equiped."); } } public void equiArmor(Armor item) { // On équipe la nouvelle défense if ( item != this.armor){ this.stats.removeDefense(this.armor.getDefenseBonus()); // On retire les bonus de def de l'ancienne arme this.stats.addDefense(item.getDefenseBonus()); this.armor = item; showEquipement(); } else{ System.out.println("You have already this armor equiped."); } } public void showEquipement() { System.out.println("You are equipped with the current weapon : " + this.weapon.getName() + " and the current armor : " + this.armor.getName()); } public void removeInventory(Item item) { this.INVENTORY.remove(item.getName()); } public boolean hasItem(String item) {return this.INVENTORY.containsKey(item);} public void buyItem(String nameItem) { //Permet d'acheter un item Shop shop = (Shop) this.currentLocation ; if (shop.getItem(nameItem)!= null ){ Item item = shop.getItem(nameItem); if ( item.getPrice() < this.stats.getMoney() ){ // Vérifie si le joueur possède accés d'argent puis on l'ajoute à dans l'inventaire et l iteme n'ai plus dans le shop addInventory(item); this.stats.removeMoney(item.getPrice()); shop.removeItem(nameItem); } else{ System.out.println("Xavier [Marchand] :\"Need more money rogue!\" "); } } else { System.out.println("Xavier [Marchand] :\"The shop doesn't sell this item.\""); } } public void sellItem(String nameItem) { if (this.hasItem(nameItem)) { Item item = getItem(nameItem); if ( item.getPrice() < 0) { // Vérifie si le prix de litem est supérieur à 0 car les items pour avancer dans l'histoire on un prix négatif System.out.println("Xavier [Marchand] :\"This item is so important.\""); } else{ if( item == this.weapon || item == this.armor ){ removeEquipment(item); } this.stats.addMoney(item.getPrice() / 2); removeInventory(item); System.out.println("Xavier [Marchand] :\"Thanks for your patronage.\"" ); } } else { System.out.println("Xavier [Marchand] :\"You don't have this item.\"" ); } } public void buyPotion(String potionType){ Shop shop = (Shop) this.currentLocation ; switch (potionType) { case "health_potion" : { this.stats.removeMoney(shop.getPotionCost()); addHealthPotion(); } case "attack_potion" : { this.stats.removeMoney(shop.getPotionCost()); addAttackPotion(); } case "defense_potion" : { this.stats.removeMoney(shop.getPotionCost()); addDefensePotion(); } case "crit_potion" : { this.stats.removeMoney(shop.getPotionCost()); addCritPotion(); } default : System.out.println("We don't have that kind of potion here."); } } @Override public String toString() { return "player name : " + this.getName() + "\nhealth : " + this.getHealth() + "\nattack : " + this.getAttack() + "\ndefense : " + this.getDefense() + "\ncritical : " + this.getCrit() + "\n"; } }
true
2401e8a30141943f9a992fe9937256a2902699e9
Java
OnMyHorizon/awayFromSchool-Unit-13-
/src/Unit16/FancySnowFlake.java
UTF-8
2,071
3.34375
3
[]
no_license
package Unit16; //(c) A+ Computer Science //www.apluscompsci.com //Name - import java.awt.Color; import java.awt.*; import java.awt.Graphics; import java.awt.Polygon; //extend the AbstractShape class to make a FancySnowFlake class public class FancySnowFlake extends AbstractShape { public FancySnowFlake(int x, int y, int w, int h, Color c, int xspd, int yspd) { super(x,y,w,h,c,xspd,yspd); } public void draw(Graphics window) { window.setFont(new Font("TimesRoman", Font.PLAIN, this.getWidth()*4)); Polygon p = new Polygon(); p.addPoint(this.getXPos(), this.getYPos()); p.addPoint(this.getXPos() + this.getWidth(), this.getYPos()+getHeight()); p.addPoint(this.getXPos() + (2 *this.getWidth()), this.getYPos()); p.addPoint(this.getXPos() + this.getWidth(), this.getYPos()-getHeight()); Polygon p1 = new Polygon(); p1.addPoint(this.getXPos()+this.getWidth()/5, this.getYPos()); p1.addPoint(this.getXPos() + this.getWidth(), this.getYPos()+getHeight() - getHeight()/5); p1.addPoint(this.getXPos() + (2 *this.getWidth()) - this.getWidth()/5, this.getYPos()); p1.addPoint(this.getXPos() + this.getWidth(), this.getYPos()-getHeight() + getHeight()/5); Polygon p2 = new Polygon(); p1.addPoint(this.getXPos()+this.getWidth()/2, this.getYPos()); p1.addPoint(this.getXPos() + this.getWidth(), this.getYPos()+getHeight() - getHeight()/2); p1.addPoint(this.getXPos() + (2 *this.getWidth()) - this.getWidth()/2, this.getYPos()); p1.addPoint(this.getXPos() + this.getWidth(), this.getYPos()-getHeight() + getHeight()/2); window.drawPolygon(p); window.drawPolygon(p1); window.drawPolygon(p2); //window.drawPolygon(p3); window.setColor(getColor()); window.fillOval(this.getXPos() + this.getWidth()/2, this.getYPos() - getHeight()/2, this.getWidth(), getHeight()); window.drawString("+", this.getXPos() + this.getWidth()/100, this.getYPos() + getHeight()+getHeight()/3); } public void moveAndDraw(Graphics window) { setYPos(getYPos() + getYSpeed()); draw(window); } }
true
263335a4d75c25a061d6987fcc50b4fb4e43ee62
Java
Vipra7/Assignments
/control statement/in class/src/afterdecimal.java
UTF-8
555
3.796875
4
[]
no_license
import java.util.*; public class afterdecimal { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print(" Enter 1st number : "); double n1 = input.nextDouble(); System.out.print("\n Enter 2nd number : "); double n2 = input.nextDouble(); n1 = n1*1000; n2 = n2*1000; if(n1==n2) System.out.println("The two numbers ARE equal upto 3 places"); else System.out.println("The two numbers ARE NOT equal upto 3 places"); } }
true
0231f8b0f32132c2a8adbb905c844f8075634b02
Java
hungitleadpro/gcoin-demo
/src/main/java/com/feature/gcoin/dto/reponse/TransactionLogReponse.java
UTF-8
760
1.898438
2
[]
no_license
package com.feature.gcoin.dto.reponse; import com.feature.gcoin.dto.TransactionLogDTO; import java.util.List; public class TransactionLogReponse { private List<TransactionLogDTO> voteTransactionLog; private List<TransactionLogDTO> coinTransactionLog; public List<TransactionLogDTO> getVoteTransactionLog() { return voteTransactionLog; } public void setVoteTransactionLog(List<TransactionLogDTO> voteTransactionLog) { this.voteTransactionLog = voteTransactionLog; } public List<TransactionLogDTO> getCoinTransactionLog() { return coinTransactionLog; } public void setCoinTransactionLog(List<TransactionLogDTO> coinTransactionLog) { this.coinTransactionLog = coinTransactionLog; } }
true
55dd38196075be32bacb81ef05fb872bfdd43746
Java
TilStehle/Cross-Platform-Traceability
/src/preferences/SettingsPropertyProvider.java
UTF-8
3,856
2.375
2
[ "MIT" ]
permissive
package preferences; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.ui.Messages; /** * Created by Gerrit Greiert on 05.12.16. */ public class SettingsPropertyProvider { public static final String J2SWIFT_TARGET_PATH = "J2Swift_targetPath"; public static final String J2SWIFT_CONFIG_FILE_PATH = "J2Swift_configFilePath"; public static final String J2SWIFT_TARGET_PROJECT_PATH = "J2Swift_targetProjectPath"; public static final String J2SWIFT_TRACEABILITY_FILE_PATH = "J2Swift_traceabilityFilePath"; /** * Tries to return the target path string and shows prompt if it isn't configured * @return * @throws MissingPropertyException */ public static String getTargetPath() throws MissingPropertyException { PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); String targetPath = propertiesComponent.getValue(J2SWIFT_TARGET_PATH, ""); if (targetPath.equals("")) { //if no target path is set show prompt int answer = Messages.showOkCancelDialog("Please configure a target path. Would you like to open the " + "preferences?", "Missing target path", Messages.getQuestionIcon()); if (answer == 0) ShowSettingsUtil.getInstance().showSettingsDialog(null, Settings.class); throw new MissingPropertyException("No target path configured in the preferences"); } return targetPath; } /** * Tries to return the config path string and shows prompt if it isn't configured * @return * @throws MissingPropertyException */ public static String getConfigPath() throws MissingPropertyException{ PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); String configPath = propertiesComponent.getValue(J2SWIFT_CONFIG_FILE_PATH, ""); if (configPath.equals("")) { //if no config path is set show prompt int answer = Messages.showOkCancelDialog("Please configure a config path. Would you like to open the " + "preferences?", "Missing config path", Messages.getQuestionIcon()); if (answer == 0) ShowSettingsUtil.getInstance().showSettingsDialog(null, Settings.class); throw new MissingPropertyException("No config path configured in the preferences"); } return configPath; } /** * Tries to return the traceability file path string and shows prompt if it isn't configured * @return * @throws MissingPropertyException */ public static String getTraceabilityFilePath() throws MissingPropertyException{ PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); String configPath = propertiesComponent.getValue(J2SWIFT_TRACEABILITY_FILE_PATH, getTargetPath()); if (configPath.equals("")) { //if no config path is set show prompt int answer = Messages.showOkCancelDialog("Please configure a traceability path. Would you like to open the " + "preferences?", "Missing traceability path", Messages.getQuestionIcon()); if (answer == 0) ShowSettingsUtil.getInstance().showSettingsDialog(null, Settings.class); throw new MissingPropertyException("No config path configured in the preferences"); } return configPath; } /** * Tries to return the target XCode project file path string * @return */ public static String getTargetProjectFilePath(){ PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); String targetProjectPath = propertiesComponent.getValue(J2SWIFT_TARGET_PROJECT_PATH, ""); return targetProjectPath; } }
true
9f9759ed524e42a762c67cd6270f9da91b964bd0
Java
JonasXPX/Mito
/src/me/jonasxpx/mito/Mito.java
ISO-8859-1
4,218
2.03125
2
[]
no_license
package me.jonasxpx.mito; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import me.jonasxpx.mito.Primary.Messages; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.event.DespawnReason; import net.citizensnpcs.api.npc.NPC; public class Mito { private JavaPlugin jp; private String nickMito = null; private Long lastlogin = null; public Mito(JavaPlugin jp){ this.jp = jp; } public String getMito(){ if(nickMito == null){ if(jp.getConfig().contains("Mito")){ setMitoString(jp.getConfig().getString("Mito")); return this.nickMito; }else return null; } else return nickMito; } public void setMito(Player player, boolean quiet){ jp.getConfig().set("Mito", player == null ? null : player.getName()); jp.saveConfig(); setMitoString(player == null ? null : player.getName()); updateLastLogin(); if(!quiet){ Messages.CATCHED.getArray().forEach(msg -> Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', msg.replaceAll("@player", player.getName())))); Location loc = player.getLocation(); loc.getWorld().strikeLightningEffect(player.getLocation().add(2, 0, 0)); loc.getWorld().strikeLightningEffect(player.getLocation().add(-2, 0, 0)); loc.getWorld().strikeLightningEffect(player.getLocation().add(0, 0, 2)); loc.getWorld().strikeLightningEffect(player.getLocation().add(0, 0, -2)); loc.getWorld().strikeLightningEffect(player.getLocation().add(-2, 0, 2)); loc.getWorld().strikeLightningEffect(player.getLocation().add(2, 0, -2)); for(Player players : jp.getServer().getOnlinePlayers()){ players.playSound(players.getLocation(), Sound.ENDERDRAGON_GROWL, 1, 1); } } if(player != null && Primary.isEnabledCitizens) updateSkin(player.getName()); } public void setMito(OfflinePlayer player, boolean quiet){ jp.getConfig().set("Mito", player == null ? null : player.getName()); jp.saveConfig(); setMitoString(player == null ? null : player.getName()); updateLastLogin(); if(!quiet){ Messages.CATCHED.getArray().forEach(msg -> Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', msg.replaceAll("@player", player.getName())))); for(Player players : jp.getServer().getOnlinePlayers()){ players.playSound(players.getLocation(), Sound.ENDERDRAGON_GROWL, 1, 1); } } if(player != null && Primary.isEnabledCitizens) updateSkin(player.getName()); } public void updateLastLogin(){ this.lastlogin = System.currentTimeMillis(); jp.getConfig().set("LastLogin", lastlogin); jp.saveConfig(); } public Long getLastLogin(){ return this.lastlogin == null ? jp.getConfig().getLong("LastLogin") : this.lastlogin; } public void notification(boolean b){ jp.getConfig().set("notificacao", b); jp.saveConfig(); } public boolean hasNotification(){ return jp.getConfig().getBoolean("notificacao"); } public Long getSecondsFromTheLastLogin(){ return (System.currentTimeMillis() / 1000) - (getLastLogin() / 1000); } public void setMitoString(String mito){ this.nickMito = mito; } public static void updateSkin(String mito){ NPC mitoNpc = CitizensAPI.getNPCRegistry().getById(0); mitoNpc.setName(("5" + mito).length() > 16 ? ("5" + mito).substring(0, 16) : ("5" + mito)); Location tempLoc = new Location(Bukkit.getWorld("endcraft"), 1214.5, 9.5, 251.6); mitoNpc.despawn(DespawnReason.PENDING_RESPAWN); mitoNpc.spawn(tempLoc); } /** * Adiciona um efeito de potion no jogador. * @param player Jogador. * @param ef Efeito. * @param dura Durao em segundos. * @param ampl 0 = 1. */ public static void addEffects(Player player, PotionEffectType ef, int dura, int ampl){ if(player.hasPotionEffect(ef)){ return; } player.addPotionEffect(new PotionEffect(ef, dura * 20, ampl)); } }
true
36162084d2f5fd7fb3f61f2f70e444424359ac4e
Java
85479676/spring-boot-api-project-seed
/src/main/java/com/company/project/model/OauAccessToken.java
UTF-8
4,823
1.9375
2
[]
no_license
package com.company.project.model; import java.util.Date; import javax.persistence.*; @Table(name = "OAU_ACCESS_TOKEN") public class OauAccessToken { @Id @Column(name = "AIID") private Long aiid; @Column(name = "DATIME_SYS") private Date datimeSys; @Column(name = "DATIME_UNIX") private Long datimeUnix; @Column(name = "TOKEN") private String token; @Column(name = "OPEN_ID") private String openId; @Column(name = "DOMAIN_UNID") private String domainUnid; @Column(name = "OAUTH_CLIENT_ID") private Long oauthClientId; @Column(name = "EXPIRES_IN") private Integer expiresIn; @Column(name = "TOKEN_TYPE") private String tokenType; @Column(name = "REFRESH_TOKEN") private String refreshToken; @Column(name = "AUTH_CODE") private String authCode; @Column(name = "ATTA") private String atta; @Column(name = "IP4") private String ip4; @Column(name = "IP6") private String ip6; @Column(name = "FLAG_EXPIRED") private Boolean flagExpired; @Column(name = "FLAG_AVA") private Boolean flagAva; /** * @return AIID */ public Long getAiid() { return aiid; } /** * @param aiid */ public void setAiid(Long aiid) { this.aiid = aiid; } /** * @return DATIME_SYS */ public Date getDatimeSys() { return datimeSys; } /** * @param datimeSys */ public void setDatimeSys(Date datimeSys) { this.datimeSys = datimeSys; } /** * @return DATIME_UNIX */ public Long getDatimeUnix() { return datimeUnix; } /** * @param datimeUnix */ public void setDatimeUnix(Long datimeUnix) { this.datimeUnix = datimeUnix; } /** * @return TOKEN */ public String getToken() { return token; } /** * @param token */ public void setToken(String token) { this.token = token; } /** * @return OPEN_ID */ public String getOpenId() { return openId; } /** * @param openId */ public void setOpenId(String openId) { this.openId = openId; } /** * @return DOMAIN_UNID */ public String getDomainUnid() { return domainUnid; } /** * @param domainUnid */ public void setDomainUnid(String domainUnid) { this.domainUnid = domainUnid; } /** * @return OAUTH_CLIENT_ID */ public Long getOauthClientId() { return oauthClientId; } /** * @param oauthClientId */ public void setOauthClientId(Long oauthClientId) { this.oauthClientId = oauthClientId; } /** * @return EXPIRES_IN */ public Integer getExpiresIn() { return expiresIn; } /** * @param expiresIn */ public void setExpiresIn(Integer expiresIn) { this.expiresIn = expiresIn; } /** * @return TOKEN_TYPE */ public String getTokenType() { return tokenType; } /** * @param tokenType */ public void setTokenType(String tokenType) { this.tokenType = tokenType; } /** * @return REFRESH_TOKEN */ public String getRefreshToken() { return refreshToken; } /** * @param refreshToken */ public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } /** * @return AUTH_CODE */ public String getAuthCode() { return authCode; } /** * @param authCode */ public void setAuthCode(String authCode) { this.authCode = authCode; } /** * @return ATTA */ public String getAtta() { return atta; } /** * @param atta */ public void setAtta(String atta) { this.atta = atta; } /** * @return IP4 */ public String getIp4() { return ip4; } /** * @param ip4 */ public void setIp4(String ip4) { this.ip4 = ip4; } /** * @return IP6 */ public String getIp6() { return ip6; } /** * @param ip6 */ public void setIp6(String ip6) { this.ip6 = ip6; } /** * @return FLAG_EXPIRED */ public Boolean getFlagExpired() { return flagExpired; } /** * @param flagExpired */ public void setFlagExpired(Boolean flagExpired) { this.flagExpired = flagExpired; } /** * @return FLAG_AVA */ public Boolean getFlagAva() { return flagAva; } /** * @param flagAva */ public void setFlagAva(Boolean flagAva) { this.flagAva = flagAva; } }
true
7c5947d4f999b3f3b6a6eb53d25cfbbdd2248189
Java
Nhat-Tao-0906/importExportJava
/import_export_excel/src/main/java/com/example/import_export_excel/model/request/UserRequest.java
UTF-8
268
1.828125
2
[]
no_license
package com.example.import_export_excel.model.request; import java.util.Date; import lombok.Data; @Data public class UserRequest { private String name; private int age; private Date birth_day; private String phone; private String address; }
true
b362d4ba0a2649e7a01593af572c208f723def75
Java
tsuzcx/qq_apk
/com.tencent.qqlite/classes.jar/euj.java
UTF-8
676
1.632813
2
[]
no_license
import android.graphics.drawable.Drawable; import com.tencent.mobileqq.util.ImageCreator; import com.tencent.mobileqq.util.ImageWorker; public class euj implements ImageCreator { String jdField_a_of_type_JavaLangString; public euj(ImageWorker paramImageWorker, String paramString) { this.jdField_a_of_type_JavaLangString = paramString; } public Drawable a() { return this.jdField_a_of_type_ComTencentMobileqqUtilImageWorker.a(this.jdField_a_of_type_JavaLangString); } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.qqlite\classes.jar * Qualified Name: euj * JD-Core Version: 0.7.0.1 */
true
8b7a590cf815d2ae88225ced1f267f41b8e9abb5
Java
thiagohrcosta/Criptograia-Julio-Cesar-Codenation
/src/main/java/challenge/CriptografiaCesariana.java
UTF-8
1,587
3.375
3
[]
no_license
package challenge; import java.util.ArrayList; import java.util.List; public class CriptografiaCesariana implements Criptografia { public String mainCode(String texto) { String setLowerCase = texto.toLowerCase(); return setLowerCase; } public String checkTexto(String texto) { if (texto.isEmpty()) throw new IllegalArgumentException("Error! Texto can´t be empty"); if (texto == null) throw new NullPointerException("Error! Texto can´t be null"); return texto; } private String doCryptoOrDecrypto(String texto, int encodeOrDecode) { int txtSize = texto.length(); String newCode = ""; for (int i = 0; i < txtSize; i++) { char letter = (char) (mainCode(texto).charAt(i) + encodeOrDecode); if (Character.isWhitespace(mainCode(texto).charAt(i))) { newCode += " "; } else if (Character.isDigit(mainCode(texto).charAt(i))) { newCode += mainCode(texto).charAt(i); } else if (letter > 'z') { newCode += (char) (mainCode(texto).charAt(i) - (26 - encodeOrDecode)); } else { newCode += (char) (mainCode(texto).charAt(i) + encodeOrDecode); } } return newCode; } @Override public String criptografar(String texto) { checkTexto(texto); return doCryptoOrDecrypto(texto, 3); } @Override public String descriptografar(String texto) { checkTexto(texto); return doCryptoOrDecrypto(texto, -3); } }
true
edeec1572ba277bdc21a0be2ffd6b4c95aa9f1e9
Java
SimonePan/java-demo
/src/main/java/com/example/demo/thread/unsafe/NoVisibility.java
UTF-8
988
3.28125
3
[]
no_license
package com.example.demo.thread.unsafe; import lombok.extern.slf4j.Slf4j; /** * @description: 在没有同步的情况下共享变量(X) * @author: Grace.Pan * @create: 2019-12-18 20:08 */ @Slf4j public class NoVisibility { private static boolean ready; private static int number; private static class ReaderThread extends Thread { @Override public void run() { while (!ready) { // 释放CPU,不释放锁,允许优先级相同或更高的线程抢占资源。也可能自己再次获得CPU。 Thread.yield(); } log.info("number=" + number); } } /** * 当主线程写入number,然后在没有同步情况下写入read,那么读线程看到的顺序可能与写入的顺序完全相反。 * * @param args */ public static void main(String[] args) { new ReaderThread().start(); number = 24; ready = true; } }
true
478e22ac9ea405e7c606d60193876271b0991edc
Java
ErminDZ/booking
/src/main/java/business/services/AddNewBookingFacade.java
UTF-8
765
2.453125
2
[]
no_license
package business.services; import business.entities.Booking; import business.exceptions.UserException; import business.persistence.BookingMapper; import business.persistence.Database; import java.time.LocalDate; import java.util.Date; public class AddNewBookingFacade { private BookingMapper bookingMapper; public AddNewBookingFacade(Database database){this.bookingMapper = new BookingMapper(database);} public Booking addNewBooking(int user_id, String booking_date, boolean booking_status, int item_id, int days, String comment) throws UserException { Booking booking = new Booking(user_id, booking_date, booking_status, item_id, days, comment); booking = bookingMapper.addNewBooking(booking); return booking; } }
true
6b27a731647dff5d040386c1d2cbce58be042d07
Java
NebukadNesar/simurg
/src/com/example/helper/AlertDialogManager.java
UTF-8
1,670
2.90625
3
[]
no_license
package com.example.helper; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class AlertDialogManager { /** * Function to display simple Alert Dialog * * @param context * - application context * @param title * - alert dialog title * @param message * - alert message * @param status * - success/failure (used to set icon) - pass null if you don't * want icon **/ boolean bool = false; public void showAlertDialog(Context context, String title, String message, Boolean status) { AlertDialog alertDialog = new AlertDialog.Builder(context).create(); // Setting Dialog Title alertDialog.setTitle(title); // Setting Dialog Message alertDialog.setMessage(message); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // Showing Alert Message alertDialog.show(); } /** * confirm alert * * @param context * @param msg * @return */ public boolean showConfirmAlert(Context context, String msg) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Confirm"); builder.setMessage(msg) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { bool = true; } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { bool = false; } }); builder.create().show(); return bool; } }
true
0d74a568f549a79382c6b8430329bf28e3f03a4c
Java
hut8/fractus
/src/fractus/crypto/PublicKeyDirectory.java
UTF-8
2,058
2.609375
3
[]
no_license
package fractus.crypto; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.bouncycastle.jce.interfaces.ECPublicKey; import org.bouncycastle.math.ec.ECPoint; import fractus.main.BinaryUtil; import fractus.net.ServerConnector; public class PublicKeyDirectory { private final static Logger log; static { log = Logger.getLogger(PublicKeyDirectory.class); } private Map<ECPoint, String> keyUserMap; private ServerConnector serverConnector; public PublicKeyDirectory(ServerConnector serverConnector) { this.serverConnector = serverConnector; this.keyUserMap = new HashMap<ECPoint, String>(); } public synchronized String identifyKey(byte[] encodedKey) throws InvalidKeySpecException { log.debug("Identifying key material: " + BinaryUtil.encodeData(encodedKey)); // Convert public key data to ECPoint X509EncodedKeySpec ks = new X509EncodedKeySpec(encodedKey); KeyFactory kf; try { kf = java.security.KeyFactory.getInstance("ECDH"); } catch (NoSuchAlgorithmException e) { log.error("Cryptography error: could not initialize ECDH keyfactory!", e); throw new RuntimeException(e); } ECPublicKey remotePublicKey = (ECPublicKey)kf.generatePublic(ks); ECPoint remotePoint = remotePublicKey.getQ(); log.debug("Computed target Q point from given ECPublicKey"); // Look in local table if (!keyUserMap.containsKey(remotePoint)) { String authoritiveAnswer = null; try { authoritiveAnswer = this.serverConnector.identifyKey(encodedKey); } catch (Exception e) { log.warn("Could not retrieve authoritive answer of public key from server",e); } if (authoritiveAnswer == null) { log.info("Could not identify public key: " + BinaryUtil.encodeData(encodedKey)); return null; } keyUserMap.put(remotePoint, authoritiveAnswer); } return keyUserMap.get(remotePoint); } }
true
2d442c8127076521faa0607eada91d6ef8e1844b
Java
lanjie911/gcprofile
/src/main/java/cn/bj/brook/algorithm/sort/BubbleSort.java
UTF-8
1,683
4.15625
4
[]
no_license
package cn.bj.brook.algorithm.sort; /** * 01-冒泡排序 * 复杂度O(n^2) * 这是一个把元素不停向右推的过程 * 4 3 2 1 * -> 3 4 2 1 * -> 3 2 4 1 * -> 3 2 1 4 * ----------------第一轮 * -> 2 3 1 4 * -> 2 1 3 4 * ----------------第二轮 * -> 1 2 3 4 * ----------------第三轮 * 所以总循环次数最差就是n-1轮,每次内部循环都是从0 开始 * <p> * 其反向算法请参考 * * @see cn.bj.brook.algorithm.sort.reverse.ReverseBubbleSort#sort(int[]) */ public class BubbleSort implements SortFunction { public static SortFunction newInstance() { return new BubbleSort(); } public void sort(int[] arr) { // 外循环只需要n-1次 // 比如 321最多只需要遍历2轮就可以顺位 // 再比如4321最多只需要遍历3轮就可以顺位 for (int i = 0; i < arr.length-1; i++) { // 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。 boolean flag = true; // 内循环是比较前后的一对儿,所以最多只能到长度-1 for (int j = 0; j < arr.length - i; j++) { if (arr[j] > arr[j + 1]) { int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; flag = false; } } if (flag) { break; } } } public static void main(String[] args) { SortAlgorithmFrame frame = new SortAlgorithmFrame(100, 8); frame.sort(BubbleSort.newInstance()); } }
true
bc25f64b89c60ca4591173a3f32abcd544177446
Java
asarnow/sfsuxmas
/src/com/sfsu/xmas/filter/SAddProbeNote.java
UTF-8
2,999
2.234375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.sfsu.xmas.filter; import com.sfsu.xmas.servlet.ServletUtil; import com.sfsu.xmas.session.SessionAttributeManager; import com.sfsu.xmas.session.SessionAttributes; import com.sfsu.xmas.session.YearLongCookie; import com.sfsu.xmas.util.StringUtils; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SAddProbeNote extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String sessionID = SessionAttributeManager.getSessionID(request); if (sessionID == null) { response.addCookie(new YearLongCookie(SessionAttributes.SESSION_IDENTIFIER, ServletUtil.getNewSessionID(request))); } String probeID = request.getParameter("probe_id"); String probeNote = request.getParameter("probe_note"); if (probeNote != null && !probeNote.equals("")) { probeNote = StringUtils.clean(probeNote); SessionAttributeManager.getActiveKnowledgeLibrary(request).addProbeUserNote(probeNote, probeID); out.append("1"); } else { SessionAttributeManager.getActiveKnowledgeLibrary(request).removeProbeUserNote(probeID); out.append("0"); } } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
3c8ecf59c0e19124142990a3f544d4e7bb177d1c
Java
jamiegrech/RS07v2
/src/org/harrynoob/hbot/callbacks/PaintCallback.java
UTF-8
383
2.484375
2
[]
no_license
package org.harrynoob.hbot.callbacks; import java.awt.*; /** * Do not use this without permission. * User: harrynoob * Date: 24-2-13 * Time: 11:28 */ public class PaintCallback { public static void callback(Graphics g) { g.setFont(new Font("Arial", Font.PLAIN, 20)); g.setColor(Color.black); g.drawString("yap it works bitches", 30, 30); } }
true
4ea83bc1e45c3997ec6b0bf42558ec390c31fb14
Java
UltimateJupiter/LeetCode-Java
/reverseIntegers.java
UTF-8
397
3.046875
3
[]
no_license
class Solution { public int reverse(int x) { boolean revert = x < 0; if (revert) x = -x; int ret = 0; while(x > 0){ if (ret > Integer.MAX_VALUE/10 || (ret == Integer.MAX_VALUE / 10 && x%10 > 7)) return 0; ret = ret * 10; ret += x%10; x = x/10; } if (revert) ret = -ret; return ret; } }
true
0f1b86328940a7c6bec374ffdc5117d4cb62a3ec
Java
kolodindv/JavaHibernate
/hiberSqlEx/src/main/java/DAO/Impl/SportsmanDao.java
UTF-8
2,746
2.453125
2
[]
no_license
package DAO.Impl; import DAO.ISportsmanDao; import DAO.HibernateUtil.HibernateUtil; import Entities.Sportsman; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import java.util.ArrayList; import java.util.List; public class SportsmanDao implements ISportsmanDao { private static SessionFactory sessionFactory; public SportsmanDao() { sessionFactory = HibernateUtil.getSessionFactory(); } public void addSportsman (Sportsman sportsman) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.save(sportsman); transaction.commit(); session.close(); } public List<Sportsman> getAllSportsmans() { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); List <Sportsman> sportsmanList = new ArrayList<Sportsman>( session.createQuery("from Sportsman").list()); session.getTransaction().commit(); session.close(); return sportsmanList; } public void printAllSportsmans() throws JsonProcessingException { Session session = sessionFactory.openSession(); } public List<Sportsman> searchSportsmanById(int id) throws JsonProcessingException { Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(Sportsman.class).add(Restrictions.idEq(id)); return criteria.list(); } public List <Sportsman> searchSportsmanByFirstName(String firstName) throws JsonProcessingException { Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(Sportsman.class).add(Restrictions.like("firstName", firstName)); return criteria.list(); } public List <Sportsman> searchSportsmanByLastName(String lastName) throws JsonProcessingException { Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(Sportsman.class).add(Restrictions.like("lastName", lastName)); return criteria.list(); } public void deleteSportsmanById (int id) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Sportsman sportsman = session.get(Sportsman.class, id); session.delete(sportsman); transaction.commit(); session.close(); } }
true
553f25fcee36c1740b3ec3eddba135df672f3074
Java
ArcoChen/DesignPattern
/DesignPatterns/src/main/java/com/hjc/traing/RedColor.java
UTF-8
161
1.992188
2
[]
no_license
package com.hjc.traing; public class RedColor implements Color { @Override public void setColor() { System.out.println("红色的车"); } }
true
5b33457de98d6f7993397fc2e8d2b64a46b94f90
Java
changanforgithub/resource
/newbiest-common-statemachine/target/classes/com/newbiest/commom/sm/repository/cutomer/StatusRepositoryCustom.java
UTF-8
320
1.867188
2
[]
no_license
package com.newbiest.commom.sm.repository.cutomer; import com.newbiest.base.exception.ClientException; import com.newbiest.commom.sm.model.Status; /** * Created by guoxunbo on 2017/11/5. */ public interface StatusRepositoryCustom { Status getStatus(Long statusModelRrn, String status) throws ClientException; }
true
0f1920f09993e967c0d10c56e7ef7e15186e3f5d
Java
cartory/TecnoParcial1
/src/Utils/Command.java
UTF-8
4,013
2.8125
3
[]
no_license
package Utils; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import java.util.function.BiFunction; import Controllers.*; public class Command { private static final String SPLIT = ";;"; public static enum Operation { Read, Create, Update, Delete, } Map<String, Controller> useCaseMap; Map<Operation, BiFunction<String[], Controller, String>> commandMap; public Command() { this.commandMap = new HashMap<Operation, BiFunction<String[], Controller, String>>() { { put(Operation.Read, (args, controller) -> controller.indexHTML()); put(Operation.Update, (args, controller) -> controller.editHTML(args)); put(Operation.Create, (args, controller) -> controller.createHTML(args)); put(Operation.Delete, (args, controller) -> controller.DeleteHTML(args[0])); } }; this.useCaseMap = new HashMap<String, Controller>() { { put("Gestionar Usuario@usuario", new UserController()); // put("Gestionar Servicio@servicio", new ServiceController()); } }; } public String executeCommand(String useCase, Operation operation, String args[]) { Controller controller = this.useCaseMap.get(useCase); return this.commandMap.get(operation).apply(args, controller); } private String getCommandString(String key, Controller controller) { Object attributes[][] = controller.getATTRIBS(); String res = ""; for (int i = 0; i < attributes.length; i++) { res += attributes[i][1] + " " + attributes[i][0]; if (i < attributes.length - 1) { res += SPLIT; } } return key + "[" + res + "];"; } private LinkedList<Object> parseCommand(String header, String args[], String subject) { String sub = subject.trim(); LinkedList<Object> parsedList = new LinkedList<Object>(); String partesSubject[] = sub.split("\\["); header = partesSubject[0]; String cuerpo[] = partesSubject[1].split("\\]"); if (cuerpo.length != 0) { args = cuerpo[0].split("\\;;"); for (int i = 0; i < args.length; i++) { args[i] = args[i].trim(); } } parsedList.push(header); parsedList.push(args); return parsedList; } public String getInfoHTML() { String[][] table = new String[this.useCaseMap.size() * 4 + 1][3]; table[0][2] = "COMANDO"; table[0][1] = "OPERACIÓN"; table[0][0] = "CASO DE USO"; int i = 1; Operation operations[] = Operation.values(); for (Map.Entry<String, Controller> set : this.useCaseMap.entrySet()) { String[] keys = set.getKey().split("@"); Operation operation = operations[(i - 1) % 4]; table[i][0] = "CU" + i + ". " + keys[0]; table[i][1] = "OPERACIÓN : " + operation; table[i][2] = getCommandString(keys[1] + operation, set.getValue()); i++; } // TODO: MUST CALL RENDER CLASS return table.toString(); } public String getResponseHTML(String subject) { String header = ""; String data[] = null; LinkedList<Object> parsedData = parseCommand(header, data, subject); header = (String) parsedData.get(1); data = (String[]) parsedData.get(0); String message = null; for (String key : this.useCaseMap.keySet()) { for (Operation op : Operation.values()) { if (header.toLowerCase().equals(key.toLowerCase() + op.toString().toLowerCase())) { message = this.executeCommand(key, op, data); break; } } if (message != null) { break; } } return message; } }
true
9ef5d628177657b4b5387ad4c4c6605fe612d2d4
Java
hmcts/cmc-claim-store
/src/test/java/uk/gov/hmcts/cmc/claimstore/services/notifications/ClaimIssuedNotificationServiceTest.java
UTF-8
7,454
1.742188
2
[ "MIT" ]
permissive
package uk.gov.hmcts.cmc.claimstore.services.notifications; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import uk.gov.hmcts.cmc.claimstore.services.notifications.content.NotificationTemplateParameters; import uk.gov.hmcts.cmc.domain.exceptions.NotificationException; import uk.gov.hmcts.cmc.domain.models.Claim; import uk.gov.hmcts.cmc.domain.models.sampledata.SampleClaim; import uk.gov.service.notify.NotificationClientException; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.cmc.claimstore.appinsights.AppInsights.REFERENCE_NUMBER; import static uk.gov.hmcts.cmc.claimstore.appinsights.AppInsightsEvent.NOTIFICATION_FAILURE; @RunWith(MockitoJUnitRunner.class) public class ClaimIssuedNotificationServiceTest extends BaseNotificationServiceTest { private final String reference = "claimant-issue-notification-" + claim.getReferenceNumber(); private ClaimIssuedNotificationService service; @Before public void beforeEachTest() { service = new ClaimIssuedNotificationService(notificationClient, properties, appInsights); when(properties.getFrontendBaseUrl()).thenReturn(FRONTEND_BASE_URL); when(properties.getRespondToClaimUrl()).thenReturn(RESPOND_TO_CLAIM_URL); } @Test(expected = NotificationException.class) public void emailClaimantShouldThrowRuntimeExceptionWhenNotificationClientThrows() throws Exception { when(notificationClient.sendEmail(anyString(), anyString(), anyMap(), anyString())) .thenThrow(mock(NotificationClientException.class)); service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(appInsights).trackEvent(eq(NOTIFICATION_FAILURE), eq(REFERENCE_NUMBER), eq(reference)); } @Test(expected = IllegalStateException.class) public void emailClaimantShouldThrowExceptionIfIssuedOnDateIsMissing() { claim = claim.toBuilder().issuedOn(null).build(); service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); } @Test public void emailClaimantShouldSendEmailUsingPredefinedTemplate() throws Exception { service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail( eq(CLAIMANT_CLAIM_ISSUED_TEMPLATE), anyString(), anyMap(), anyString()); } @Test public void emailClaimantShouldSendToClaimantEmail() throws Exception { service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail( anyString(), eq(USER_EMAIL), anyMap(), anyString()); } @Test public void emailClaimantShouldPassClaimReferenceNumberInTemplateParameters() throws Exception { service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail( eq(CLAIMANT_CLAIM_ISSUED_TEMPLATE), anyString(), templateParameters.capture(), anyString()); assertThat(templateParameters.getValue()) .containsEntry(NotificationTemplateParameters.CLAIM_REFERENCE_NUMBER, claim.getReferenceNumber()); } @Test public void emailClaimantShouldPassFrontendHostInTemplateParameters() throws Exception { service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail( eq(CLAIMANT_CLAIM_ISSUED_TEMPLATE), anyString(), templateParameters.capture(), anyString()); assertThat(templateParameters.getValue()) .containsEntry(NotificationTemplateParameters.FRONTEND_BASE_URL, FRONTEND_BASE_URL); } @Test public void emailClaimantShouldPassNameInTemplateParameters() throws Exception { service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail( eq(CLAIMANT_CLAIM_ISSUED_TEMPLATE), anyString(), templateParameters.capture(), anyString()); String name = claim.getClaimData().getClaimant().getName(); assertThat(templateParameters.getValue()) .containsEntry(NotificationTemplateParameters.CLAIMANT_NAME, name); } @Test public void emailClaimantShouldPassRepresentativeNameInTemplateParameters() throws Exception { service.sendMail(SampleClaim.getDefaultForLegal(), USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail( eq(CLAIMANT_CLAIM_ISSUED_TEMPLATE), anyString(), templateParameters.capture(), anyString()); assertThat(templateParameters.getValue()) .containsEntry(NotificationTemplateParameters.CLAIMANT_NAME, USER_FULLNAME); } @Test public void emailClaimantShouldUseClaimReferenceNumberForNotificationReference() throws Exception { service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail(anyString(), anyString(), anyMap(), eq(reference)); } @Test public void newFeatureFlagShouldBeTrueIfClaimHasFeatures() throws Exception { Claim claim = SampleClaim.builder().withFeatures(Collections.singletonList("sampleFeatures")).build(); service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail(anyString(), anyString(), templateParameters.capture(), anyString()); assertThat(templateParameters.getValue()).containsEntry(NotificationTemplateParameters.NEW_FEATURES, "true"); } @Test public void newFeatureFlagShouldBeFalseIfClaimHasNoFeatures() throws Exception { Claim claim = SampleClaim.builder().withFeatures(Collections.emptyList()).build(); service.sendMail(claim, USER_EMAIL, null, CLAIMANT_CLAIM_ISSUED_TEMPLATE, reference, USER_FULLNAME); verify(notificationClient).sendEmail(anyString(), anyString(), templateParameters.capture(), anyString()); assertThat(templateParameters.getValue()).containsEntry(NotificationTemplateParameters.NEW_FEATURES, "false"); } @Test public void recoveryShouldNotLogPII() { NotificationException exception = new NotificationException("expected exception"); try { service.logNotificationFailure( exception, null, "hidden@email.com", null, null, "reference", null ); Assert.fail("Expected a NotificationException to be thrown"); } catch (NotificationException expected) { assertWasLogged("Failure: failed to send notification (reference) due to expected exception"); assertWasNotLogged("hidden@email.com"); } } }
true
95a656773f290eff0aaa8de4d8e5af60df6a60d1
Java
cesarfex/grafico-app
/graficos/src/main/java/com/devmedia/primefaces/mb/CandidatoManagedBean.java
UTF-8
983
2.203125
2
[]
no_license
package com.devmedia.primefaces.mb; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import com.devmedia.primefaces.model.Candidato; import com.santana.primefaces.dao.CandidatoDAO; @ManagedBean(name = "CandidatoMB") @ViewScoped public class CandidatoManagedBean { private CandidatoDAO candidatoDAO = new CandidatoDAO(); private Candidato candidato = new Candidato(); public void cadastraCandidato() { candidatoDAO.salvar(candidato); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso!", "Candidato Cadastrado com Sucesso!")); } // getters and setters public Candidato getCandidato() { return candidato; } public void setCandidato(Candidato candidato) { this.candidato = candidato; } public List<Candidato> getCandidatos() { return candidatoDAO.getAll(); } }
true
966bc131f5884063a14195168a24e86789677d2c
Java
iain-davis/Mumue
/src/main/java/org/mumue/mumue/connection/states/PlayerAuthentication.java
UTF-8
2,377
2.40625
2
[]
no_license
package org.mumue.mumue.connection.states; import javax.inject.Inject; import javax.inject.Singleton; import org.mumue.mumue.configuration.ApplicationConfiguration; import org.mumue.mumue.connection.Connection; import org.mumue.mumue.importer.GlobalConstants; import org.mumue.mumue.player.Player; import org.mumue.mumue.player.PlayerBuilder; import org.mumue.mumue.player.PlayerRepository; import org.mumue.mumue.text.TextMaker; import org.mumue.mumue.text.TextName; @Singleton class PlayerAuthentication implements ConnectionState { private final ConnectionStateProvider connectionStateProvider; private final PlayerBuilder playerBuilder; private final PlayerRepository playerRepository; private final TextMaker textMaker; @Inject public PlayerAuthentication(ConnectionStateProvider connectionStateProvider, PlayerBuilder playerBuilder, PlayerRepository playerRepository, TextMaker textMaker) { this.connectionStateProvider = connectionStateProvider; this.playerBuilder = playerBuilder; this.playerRepository = playerRepository; this.textMaker = textMaker; } @Override public ConnectionState execute(Connection connection, ApplicationConfiguration configuration) { String loginId = connection.getInputQueue().pop(); String password = connection.getInputQueue().pop(); Player player; if (isValid(loginId)) { player = playerRepository.get(loginId, password); if (player.getId() == GlobalConstants.REFERENCE_UNKNOWN) { String text = textMaker.getText(TextName.LoginFailed, configuration.getServerLocale()); connection.getOutputQueue().push(text); return connectionStateProvider.get(LoginIdPrompt.class); } else { String text = textMaker.getText(TextName.LoginSuccess, configuration.getServerLocale()); connection.getOutputQueue().push(text); } } else { player = playerBuilder.withLoginId(loginId).build(); playerRepository.add(player, password); } connection.setPlayer(player); return connectionStateProvider.get(PlayerConnected.class); } public boolean isValid(String loginId) { return playerRepository.get(loginId).getId() != GlobalConstants.REFERENCE_UNKNOWN; } }
true
699d9f4216c4e88d0bf69d444c35a330b1053415
Java
yr-nice/cctv
/src/com/mu/util/collection/ListUtil.java
UTF-8
435
2.421875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.mu.util.collection; import java.util.ArrayList; /** * * @author Peng mu */ public class ListUtil { static public ArrayList getUniqueList(ArrayList list) { ArrayList re = new ArrayList(); for(Object o : list) if(!re.contains(o)) re.add(o); return re; } }
true
1a768bcea234810cbb468f7d06b83906033b37f6
Java
Kalaimaha/Documentum
/Java Services/Java services/src/com/dfc/usermanagement/UserManagement.java
UTF-8
3,196
2.5625
3
[]
no_license
/* 1. Creating User 2. Add User to Group 3. Remove Users from Group */ package com.dfc.usermanagement; import com.documentum.fc.client.DfClient; import com.documentum.fc.client.IDfGroup; import com.documentum.fc.client.IDfSession; import com.documentum.fc.client.IDfSessionManager; import com.documentum.fc.client.IDfUser; import com.documentum.fc.common.DfException; import com.documentum.fc.common.DfId; import com.documentum.fc.common.DfLoginInfo; import com.documentum.fc.common.IDfId; import com.documentum.fc.common.IDfLoginInfo; public class UserManagement { static IDfSessionManager sessionMrg = null; static IDfSession session = null; public static void createUser(String user_name, String user_login_name, String user_password, String user_address) { try { IDfLoginInfo loginInfo = new DfLoginInfo(); loginInfo.setUser("dmadmin"); loginInfo.setPassword("Sedin@123456"); sessionMrg = DfClient.getLocalClient().newSessionManager(); // 'DocRepo' is a repository name sessionMrg.setIdentity("DocRepo", loginInfo); session = sessionMrg.getSession("DocRepo"); IDfUser user = (IDfUser) session.newObject("dm_user"); user.setUserName(user_name); user.setUserLoginName(user_login_name); user.setUserPassword(user_password); user.setUserAddress(user_address); user.save(); } catch (DfException e) { e.printStackTrace(); } finally { if (sessionMrg != null && session != null) { sessionMrg.release(session); } } } public static void addUserToGroup(String username, String group_id) { try { IDfLoginInfo loginInfo = new DfLoginInfo(); loginInfo.setUser("dmadmin"); loginInfo.setPassword("Sedin@123456"); sessionMrg = DfClient.getLocalClient().newSessionManager(); // 'DocRepo' is a repository name sessionMrg.setIdentity("DocRepo", loginInfo); session = sessionMrg.getSession("DocRepo"); IDfId convertStrToID = new DfId(group_id);// While using in xcpDesigner, not able to use IDfId directly // while mapping so converting string to ID inside the code IDfGroup group = (IDfGroup) session.getObject(convertStrToID); group.addUser(username); group.save(); } catch (DfException e) { e.printStackTrace(); } finally { if (sessionMrg != null && session != null) { sessionMrg.release(session); } } } public static void removeUsersFromGroup(String username, String group_id) { try { IDfLoginInfo loginInfo = new DfLoginInfo(); loginInfo.setUser("dmadmin"); loginInfo.setPassword("Sedin@123456"); sessionMrg = DfClient.getLocalClient().newSessionManager(); // 'DocRepo' is a repository name sessionMrg.setIdentity("DocRepo", loginInfo); session = sessionMrg.getSession("DocRepo"); IDfId convertStrToID = new DfId(group_id);// While using in xcpDesigner, not able to use IDfId directly // while mapping so converting string to ID inside the code IDfGroup group = (IDfGroup) session.getObject(convertStrToID); group.removeUser(username); group.save(); } catch (DfException e) { e.printStackTrace(); } finally { if (sessionMrg != null && session != null) { sessionMrg.release(session); } } } }
true
b61638e62484c168bdc312d3910b2f1c56fa74bc
Java
SHOKHZODJURAEV/src
/day_12Scanner/NameOfMonth.java
UTF-8
1,396
3.5625
4
[]
no_license
package day_12Scanner; import java.util.Scanner; public class NameOfMonth { public static void main(String[] args) { Scanner Variable = new Scanner (System.in); System.out.println("Enter number:"); System.out.println(" Enter number:"); int number = Variable.nextInt(); String result = ""; switch(number){ case 1: result = "Jan"; break; case 2: result = "Feb"; break; case 3: result = "March"; break; case 4: result = "April"; break; case 5: result = "May"; break; case 6: result = "June"; break; case 7: result = "July"; break; case 8: result = "July"; break; case 9: result = "July"; break; case 10: result = "July"; break; case 11: result = "July"; break; case 12: result = "July"; break; default: result = "Invalid number"; } System.out.println(result); } }
true
7c728828f687e6f75796871bce2bc79de8272133
Java
kumarvishal09/carbondata
/core/src/main/java/org/carbondata/query/reader/ResultTempFileReader.java
UTF-8
5,398
2.015625
2
[ "Apache-2.0" ]
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.carbondata.query.reader; import java.io.DataInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.carbondata.core.datastorage.store.FileHolder; import org.carbondata.core.datastorage.store.impl.FileFactory; import org.carbondata.core.datastorage.store.impl.FileFactory.FileType; import org.carbondata.core.util.CarbonUtil; import org.carbondata.query.aggregator.MeasureAggregator; import org.carbondata.query.reader.exception.ResultReaderException; import org.carbondata.query.wrappers.ByteArrayWrapper; public class ResultTempFileReader { /** * temp file */ private String inFilePath; /** * read stream */ private DataInputStream stream; /** * entry count */ private int entryCount; /** * number record read */ private int numberOfRecordRead; /** * fileBufferSize */ private int fileBufferSize; /** * keySize */ private int keySize; /** * MeasureAggregator */ private MeasureAggregator[] measureAggregator; /** * byteArrayWrapper */ private ByteArrayWrapper byteArrayWrapper; /** * CarbonSortTempFileChunkHolder Constructor * * @param inFile temp file * @param recordSize measure count * @param keySize mdkey length */ public ResultTempFileReader(String inFilePath, int keySize, final MeasureAggregator[] measureAggregator, int fileBufferSize) { // set temp file this.inFilePath = inFilePath; // key size this.keySize = keySize; // measure aggregator this.measureAggregator = measureAggregator; //fileBufferSize this.fileBufferSize = fileBufferSize; // byte array wrapper this.byteArrayWrapper = new ByteArrayWrapper(); // out stream } /** * This method will be used to initialize * * @throws CarbonSortKeyAndGroupByException problem while initializing */ public void initialize() throws ResultReaderException { FileHolder fileHolder = null; try { FileType fileType = FileFactory.getFileType(inFilePath); fileHolder = FileFactory.getFileHolder(fileType); if (fileType.equals(FileType.HDFS)) { this.entryCount = fileHolder.readInt(inFilePath, 0); } else { fileHolder = FileFactory.getFileHolder(fileType); this.entryCount = fileHolder.readInt(inFilePath, 0); } this.stream = FileFactory.getDataInputStream(inFilePath, fileType, this.fileBufferSize); this.stream.readInt(); } catch (FileNotFoundException e) { throw new ResultReaderException(e); } catch (IOException e) { throw new ResultReaderException(e); } finally { if (null != fileHolder) { fileHolder.finish(); } } } /** * This method will be used to read new row from file * * @throws CarbonSortKeyAndGroupByException problem while reading */ public void readRow() throws ResultReaderException { try { byte[] mdKey = new byte[this.keySize]; this.stream.readFully(mdKey); // LOGGER.error(CarbonEngineLogEvent.UNIBI_CARBONENGINE_MSG, "Problem while // reading mdkey from pagination temp file"); this.byteArrayWrapper.setMaskedKey(mdKey); for (int i = 0; i < this.measureAggregator.length; i++) { this.measureAggregator[i].readData(this.stream); } numberOfRecordRead++; } catch (FileNotFoundException e) { throw new ResultReaderException(this.inFilePath + " No Found ", e); } catch (IOException e) { throw new ResultReaderException(" Problem while reading" + this.inFilePath, e); } } /** * below method will be used to get the row * * @return row */ public byte[] getRow() { return this.byteArrayWrapper.getMaskedKey(); } /** * Below method will be used to close stream */ public void closeStream() { CarbonUtil.closeStreams(this.stream); } /** * below method will be used to check whether any more records are present in file or not * * @return more row present in file */ public boolean hasNext() { return this.numberOfRecordRead < this.entryCount; } /** * This method will return the data array * * @param index * @return */ public MeasureAggregator[] getMeasures() { return this.measureAggregator; } /** * This method will return the key array * * @return */ public byte[] getKey() { return this.byteArrayWrapper.getMaskedKey(); } public void setMeasureAggs(final MeasureAggregator[] aggs) { this.measureAggregator = aggs; } }
true
29ff31fe8c71af0dedec8e39d8d874034cadb641
Java
paulapithon/Chess
/Board.java
UTF-8
2,745
4.1875
4
[]
no_license
public class Board { /** * Board matrix containing all pieces */ private Piece[][] pieces = new Piece[8][8]; /** * Initialize board with correct pieces */ public void initBoard() { //Initialize white colors on up row Rook rook = new Rook(Color.WHITE); pieces[0][0] = rook; Bishop bishop = new Bishop(Color.WHITE); pieces[0][1] = bishop; Knight horse = new Knight(Color.WHITE); pieces[0][2] = horse; King king = new King(Color.WHITE); pieces[0][3] = king; Queen queen = new Queen(Color.WHITE); pieces[0][4] = queen; //Initialize black colors on down row Rook rook2 = new Rook(Color.BLACK); pieces[7][0] = rook2; Bishop bishop2 = new Bishop(Color.BLACK); pieces[7][1] = bishop2; Knight horse2 = new Knight(Color.BLACK); pieces[7][2] = horse2; King king2 = new King(Color.BLACK); pieces[7][3] = king2; Queen queen2 = new Queen(Color.BLACK); pieces[7][4] = queen2; } /** * Validate if movement is possible and perform it * @param movement performed by player * @param playerColor color of the current player * @return if the play succeeded or not, if it was a capture or a checkmate */ public Play movePiece(Movement movement, Color playerColor) { Piece piece = pieces[movement.getFromX()][movement.getFromY()]; //Check if there is a piece on that square if(piece == null) { return Play.FAIL; } //Check if piece color is the same as players if (piece.getColor() != playerColor) { return Play.FAIL; } //Check if piece can perform movement if (piece.validateMovement(movement)){ Piece captured = pieces[movement.getToX()][movement.getToY()]; //Replace initial piece pieces[movement.getFromX()][movement.getFromY()] = null; pieces[movement.getToX()][movement.getToY()] = piece; //Check if there was another piece in square if (captured != null) { //Check if piece is a different color and user can capture ir if (captured.getColor() == playerColor) { return Play.FAIL; } //If piece was a king, checkmate! if (captured instanceof King) { return Play.CHECKMATE; } else { return Play.CAPTURED; } } else { return Play.SUCCESS; } } else { return Play.FAIL; } } /** * @return the pieces */ public Piece[][] getPieces() { return pieces; } }
true
357252d6b01863cbd522102c9eb4f142faec9c42
Java
lixin46/thriftstudy
/src/main/java/com/lixin/demo/Client.java
UTF-8
1,303
2.5625
3
[]
no_license
package com.lixin.demo; import com.lixin.thrift.exception.UserNotFountException; import com.lixin.thrift.service.UserService; import com.lixin.thrift.vo.UserVo; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; /** * Created by lixin46 on 2017/10/23. */ public class Client { public static void main(String[] args) throws TTransportException { // 1.创建传输对象 try (TTransport transport = new TSocket("localhost", 9090)) { // 打开连接 transport.open(); // 2.创建协议对象,用于数据IO TProtocol protocol = new TBinaryProtocol(transport); // 3.使用指定的service类创建Client UserService.Client client = new UserService.Client(protocol); UserVo user = client.findUserById(3); System.out.println(user==null?null:String.format("name=%s,age=%d",user.name,user.age)); } catch (UserNotFountException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } } }
true
4af534527c37b9ffc015d8f51017aef45c5f12da
Java
RiversLau/concurrent-study
/src/main/java/com/yoxiang/multi_thread_programming/chapter04/sample01/RunTest.java
UTF-8
572
2.5625
3
[]
no_license
package com.yoxiang.multi_thread_programming.chapter04.sample01; /** * Author: Rivers * Date: 2018/1/7 21:28 */ public class RunTest { public static void main(String[] args) { MyService service = new MyService(); MyThread mt1 = new MyThread(service); MyThread mt2 = new MyThread(service); MyThread mt3 = new MyThread(service); MyThread mt4 = new MyThread(service); MyThread mt5 = new MyThread(service); mt1.start(); mt2.start(); mt3.start(); mt4.start(); mt5.start(); } }
true
556059de6120c4f44d030155b7718a80d85278c5
Java
lockc/java-tooling
/apache-camel/spring-camel/src/main/java/lockc/camel/examples/MyProducer.java
UTF-8
220
2.203125
2
[]
no_license
package lockc.camel.examples; import org.apache.camel.InOnly; /** * Our producer that will send messages to the JMS queue * */ public interface MyProducer { @InOnly void sendMessage(String message); }
true
e12316d54a960341b2f8b8f3eafac7e6f8869308
Java
kaifazu/MyTest
/src/order/Order.java
UTF-8
124
1.851563
2
[]
no_license
package order; public class Order { private void Syso() { System.out.println("这是一个订单李四修改的"); } }
true
9bec9c3991a3dd95a6455713af6a205905768e63
Java
mimarox/jetro
/jetro-transform/src/test/java/net/sf/jetro/transform/beans/WrappingAndAddingSource.java
UTF-8
829
2.78125
3
[ "Apache-2.0" ]
permissive
package net.sf.jetro.transform.beans; import java.util.Objects; public class WrappingAndAddingSource { private Persons person; public Persons getPerson() { return person; } public void setPerson(Persons person) { this.person = person; } @Override public int hashCode() { return Objects.hash(person); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } WrappingAndAddingSource other = (WrappingAndAddingSource) obj; return Objects.equals(person, other.person); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("WrappingAndAddingSource [person=").append(person).append("]"); return builder.toString(); } }
true
be137d8215e8bf8cc38bbad7461a20840dd2a00a
Java
wyltamar/Aulas-Java
/TestSalario.java
WINDOWS-1250
712
2.921875
3
[ "MIT" ]
permissive
package capitulo4; import javax.swing.JOptionPane; public class TestSalario { public static void main(String[] args) { SalarioReajustado salarioReajustado = new SalarioReajustado(); salarioReajustado.setNome(JOptionPane.showInputDialog("Digite seu nome:")); salarioReajustado.setSalarioAtual(Double.parseDouble(JOptionPane.showInputDialog ("Digite seu salrio atual:"))); System.out.println("Nome do funcionrio:" +salarioReajustado.getNome()); System.out.println("Salrio atual:" +salarioReajustado.getSalarioAtual()); salarioReajustado.getReajuste(); System.out.println("Salrio reajustado = " +salarioReajustado.getSalarioReajustado()); } }
true
ec1e3f7634fd478a0db160f893a331733f319e26
Java
lailasharshar/DrinkServer
/src/main/java/com/example/demo/utils/NotifyUtils.java
UTF-8
180
2.1875
2
[]
no_license
package com.example.demo.utils; public class NotifyUtils { public static void notify(String to, String message) { System.out.println("***** TO: " + to + " - " + message); } }
true
215bd25b860c21f2e6b8a1f4398eb63ebe80126e
Java
tankyskey/505
/src/Main.java
UTF-8
537
2.859375
3
[]
no_license
import model.*; public class Main{ public static void main(String args[]){ simulation(); } public static void test(){ City.createMap(10); for(City c : City.getMap()){ System.out.println(c); } Ant a = new Ant(City.getMap().get(0)); System.out.println("pos: " + a.getPos()); a.move(); System.out.println("pos: " + a.getPos()); a.move(); System.out.println("pos: " + a.getPos()); } public static void simulation(){ City.createMap(10); City.fill(); for(City c: City.getMap()) Ant.patrouille(); } }
true
9e8a92673f14b4fb29723df5329af5b994277dac
Java
JoyJava/test
/java8/src/main/java/jvm/TestSizeOfObje.java
UTF-8
529
2.328125
2
[]
no_license
package jvm; import java.lang.instrument.Instrumentation; public class TestSizeOfObje { public static void premain(String agentArgs, Instrumentation inst) { } public static void main(String[] args) { // long objectSize = Instrumentation.getObjectSize(new Object()); System.out.println(); } } class A1 { int a = 1; long b = 2; byte c = 3; // public long sizeOf(){ // // //return Instrumentation.getObjectSize(this); // } } class A2 { long b = 2; int a = 1; byte c = 3; }
true
8583d5ec172b262282c687d7888594786ecac5c4
Java
snowone/hedwig
/hedwig-api/src/main/java/com/hs/mail/container/server/thread/sjt/mgmt/ThreadingGroup.java
UTF-8
1,833
2.875
3
[ "Apache-2.0" ]
permissive
package com.hs.mail.container.server.thread.sjt.mgmt; /** An interface for a threading group collection. Used to accomodate switching from * various types of collection classes. May simply wrap a java.util.ThreadGroup, * or may simply use an array of threads. */ public interface ThreadingGroup { /** Add thread to the wrapped collection. Threads are added by ThreadManager only. * @param thread One working thread. */ public void addThread(Thread thread); /** Remove one thread from the wrapped collection. The collection itself will decide which * thread is returned. FIFO, LIFO, and any other necessary ordering. Thread should be added * back into the collection by the ThreadManager. * @return thread A working thread. */ public Thread removeThread(); public boolean removeThread(Thread thread); /** Similiar to removeThread but the thread reference is maintained in Group. * @return thread A working thread. */ public Thread useThread(); /** Check how many items in work collection. * @return size of work collection. */ public int size(); /** Check last index item in work collection. * @return pointer of work collection. */ public int pointer(); /** Check whether work has one or more work items in collection. * @return true or false if collection empty. */ public boolean isEmpty(); public Thread getThread(int index); /** Destroy can be called by the user code in order to prompt joining and cleanup of all * working threads. Destroy is also called by the finalize method, during garbage collection, * if the user code does not call it explicitly. */ public void destroy(); }
true
aff58d5f8843ae85c4071e3273616ac8ecb5c226
Java
kelemen/JTrim
/subprojects-internal/test-jtrim-concurrent/src/main/java/org/jtrim2/testutils/executor/MockTaskResult.java
UTF-8
494
2.296875
2
[ "Apache-2.0" ]
permissive
package org.jtrim2.testutils.executor; import org.jtrim2.utils.ExceptionHelper; public interface MockTaskResult { public Throwable getThrownError(); public int getCallCount(); public default void verifySuccess() { ExceptionHelper.rethrowIfNotNull(getThrownError()); int callCount = getCallCount(); if (callCount != 1) { throw new AssertionError("Expected to be called exactly once but was called " + callCount + " times."); } } }
true
2624ca0d2d899b7a92a930d7f87975a3dec553a7
Java
MengXin-9/GameSTZB
/GameSTZB/app/src/main/java/com/itgowo/gamestzb/UserActivity.java
UTF-8
5,310
1.921875
2
[ "Apache-2.0" ]
permissive
package com.itgowo.gamestzb; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.itgowo.gamestzb.Base.BaseActivity; import com.itgowo.gamestzb.Base.BaseConfig; import com.itgowo.gamestzb.Entity.UserInfo; import com.itgowo.gamestzb.Manager.UserManager; import com.itgowo.views.SuperDialog; import com.taobao.sophix.SophixManager; public class UserActivity extends BaseActivity { private ImageView userHeadImg; private CheckBox isPlayVideo, isPlayMusic; private Button btnLoginQQ; private View goBackBtn, rebootBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user); Toast.makeText(this, "开发测试版,账户信息未完善,很多功能还只是摆设,请留意后续更新", Toast.LENGTH_LONG).show(); initView(); initListener(); initData(); } public static void go(Activity context, Integer result) { Intent intent = new Intent(context, UserActivity.class); if (result == null) { context.startActivity(intent); } else { context.startActivityForResult(intent, result); } } private void initData() { isPlayVideo.setChecked(BaseConfig.getData(BaseConfig.USER_ISPLAYVIDEO, true)); isPlayMusic.setChecked(BaseConfig.getData(BaseConfig.USER_ISPLAYMUSIC, true)); if (BaseConfig.userInfo==null){ userHeadImg.setImageDrawable(null); }else { Glide.with(userHeadImg).load(BaseConfig.userInfo.getHead()).into(userHeadImg);} refreshLogonBtnStatus(); } private void refreshLogonBtnStatus() { btnLoginQQ.setText(UserManager.isLogin ? R.string.logout : R.string.loginqq); } private void initListener() { isPlayVideo.setOnCheckedChangeListener((buttonView, isChecked) -> { if (BaseConfig.getData(BaseConfig.USER_ISPLAYVIDEO, true) != isChecked) { BaseConfig.putData(BaseConfig.USER_ISPLAYVIDEO, isChecked); setResult(Activity.RESULT_OK); } }); isPlayMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (BaseConfig.getData(BaseConfig.USER_ISPLAYMUSIC, true) != isChecked) { BaseConfig.putData(BaseConfig.USER_ISPLAYMUSIC, isChecked); setResult(Activity.RESULT_OK); } } }); btnLoginQQ.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); if (UserManager.isLogin) { UserManager.logout(); refreshLogonBtnStatus(); // heroCard.refreshInfo(); v.setEnabled(true); } else { UserManager.login4QQ(UserActivity.this, new UserManager.onUserLoginListener() { @Override public void onSuccess(UserInfo userInfo) { // heroCard.refreshInfo(); setResult(Activity.RESULT_OK); refreshLogonBtnStatus(); v.setEnabled(true); } @Override public void onCancel() { } @Override public void onError(Throwable e) { e.printStackTrace(); v.setEnabled(true); showToastShort("登录失败:" + e.getMessage()); } }); } } }); goBackBtn.setOnClickListener(v -> finish()); rebootBtn.setOnClickListener(v -> { SuperDialog dialog = new SuperDialog(context); dialog.setContent("如果App出现问题或者提示重启,请选择确定按钮").setTitle("App退出提示").setButtonTexts("确定", "取消").setListener((isButtonClick, position) -> { if (position == 0) { SophixManager.getInstance().killProcessSafely(); } }).show(); }); } private void initView() { userHeadImg = findViewById(R.id.User_Head_Img); isPlayVideo = findViewById(R.id.isPlayVideo); isPlayMusic = findViewById(R.id.isPlayMusic); btnLoginQQ = findViewById(R.id.btn_login_qq); goBackBtn = findViewById(R.id.goback); rebootBtn = findViewById(R.id.reboot); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); UserManager.onActivityResult(requestCode, resultCode, data); } }
true
71b395937115ea2bd8d8f1937fa55a1a98ffe51e
Java
chongguang/lolMaster
/LoLMasterTest/src/ch/epfl/sweng/lolmaster/api/test/ApiKeysTest.java
UTF-8
505
1.835938
2
[]
no_license
package ch.epfl.sweng.lolmaster.api.test; import android.test.AndroidTestCase; import ch.epfl.sweng.lolmaster.api.ApiKeys; import ch.epfl.sweng.lolmaster.api.ApiKeysManager; /** * @author lcg31439 * */ public class ApiKeysTest extends AndroidTestCase { public void testKeyAccess() { ApiKeys keys = ApiKeysManager.getApiKeys(); assertNotNull("Mashape key should not be null", keys.getMashapeKey()); assertNotNull("Riot key should not be null", keys.getRiotKey()); } // Write more tests }
true
659ce2456b86dd0f3493553ab1d4747ef6cb13af
Java
broly941/University-Application-Boot
/src/test/java/com/loya/springjpaoracledemo/unit/TeacherServiceTest.java
UTF-8
5,957
2.484375
2
[]
no_license
package com.loya.springjpaoracledemo.unit; import com.loya.devi.entity.Teacher; import com.loya.devi.repository.TeacherRepository; import com.loya.devi.service.Impl.entityManagment.TeacherServiceImpl; import com.loya.devi.service.interfaces.BaseService; import com.loya.devi.service.interfaces.EntitiesValidationService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.context.MessageSource; import javax.persistence.EntityNotFoundException; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; /** * Test for Business Logic Service Class * * @author DEVIAPHAN */ @RunWith(MockitoJUnitRunner.class) public class TeacherServiceTest { @InjectMocks TeacherServiceImpl teacherService; @Mock TeacherRepository teacherRepository; @Mock BaseService<Teacher> teacherBaseService; @Mock EntitiesValidationService entitiesValidationService; @Mock MessageSource messageSource; /** * Will return the list if all parameters are correct */ @Test public void getAll() { List<Teacher> teacherList = initializeTeacherList(); when(teacherBaseService.getAll(any(Supplier.class), eq(Locale.ENGLISH), eq("getAll"), eq("teachers"))) .thenReturn(teacherList); assertSame(teacherList, teacherService.getAll(Locale.ENGLISH)); } /** * Will return an empty list if all parameters are correct */ @Test public void getAll_NotFoundTeachers() { when(teacherBaseService.getAll(any(Supplier.class), eq(Locale.ENGLISH), eq("getAll"), eq("teachers"))) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), teacherService.getAll(Locale.ENGLISH)); } /** * Will return a record by ID if all parameters are correct */ @Test public void getById() { Teacher teacher = initializeTeacher((long) 1); when(teacherBaseService.get(eq((long) 1), any(Function.class), eq(Locale.ENGLISH), eq("getById"), eq("teacher"), eq("Get teacher by id"))) .thenReturn(teacher); assertSame(teacher, teacherService.getById((long) 1, Locale.ENGLISH)); } /** * Will thrown out an exception if record by ID cannot found */ @Test(expected = EntityNotFoundException.class) public void getById_NotFoundTeacher() { when(teacherBaseService.get(eq((long) 2), any(Function.class), eq(Locale.ENGLISH), eq("getById"), eq("teacher"), eq("Get teacher by id"))) .thenThrow(EntityNotFoundException.class); teacherService.getById((long) 2, Locale.ENGLISH); } /** * Will return the list if all parameters are correct */ @Test public void getTeachersOfGroupById() { List<Teacher> teacherList = initializeTeacherList(); when(teacherBaseService.getAll(eq((long) 1), any(Function.class), eq(Locale.ENGLISH), eq("getTeachersOfGroupById"), eq("teachers"), eq("Get teachers of group by id"))) .thenReturn(teacherList); assertSame(teacherList, teacherService.getTeachersOfGroupById((long) 1, Locale.ENGLISH)); } /** * Will return a record by name */ @Test public void getTeacherByName() { Optional<Teacher> teacherOptional = Optional.of(initializeTeacher((long) 1)); when(teacherRepository.findByFirstNameAndLastName("First", "Last")) .thenReturn(teacherOptional); assertSame(teacherOptional, teacherService.getTeacherByName("First", "Last")); } /** * Will save a record if all parameters are correct */ @Test public void save() { Teacher teacher = initializeTeacher((long) 1); when(teacherBaseService.save(eq(teacher), any(UnaryOperator.class), eq(Locale.ENGLISH), eq("add"), eq("teacher"))) .thenReturn(teacher); assertSame(teacher, teacherService.save(teacher, Locale.ENGLISH)); } /** * Will return a record if all parameters are correct */ @Test public void updateById() { Teacher teacher = initializeTeacher((long) 1); when(teacherBaseService.get(eq((long) 1), any(Function.class), eq(Locale.ENGLISH), eq("updateById"), eq("teacher"), eq("Update teacher by id"))) .thenReturn(teacher); when(teacherBaseService.save(eq(teacher), any(UnaryOperator.class), eq(Locale.ENGLISH), eq("updateById"), eq("teacher"), eq((long) 1))) .thenReturn(teacher); assertSame(teacher, teacherService.updateById(teacher, (long) 1, Locale.ENGLISH)); } /** * Will thrown out an exception if entity cannot found */ @Test(expected = EntityNotFoundException.class) public void updateById_NotFoundId() { when(teacherBaseService.get(eq((long) 1), any(Function.class), eq(Locale.ENGLISH), eq("updateById"), eq("teacher"), eq("Update teacher by id"))) .thenThrow(EntityNotFoundException.class); teacherService.updateById(initializeTeacher((long) 1), (long) 1, Locale.ENGLISH); } private List<Teacher> initializeTeacherList() { List<Teacher> teacherList = new ArrayList<>(); teacherList.add(initializeTeacher((long) 1)); teacherList.add(initializeTeacher((long) 2)); return teacherList; } private Teacher initializeTeacher(long id) { Teacher teacher = new Teacher(); teacher.setFirstName("First"); teacher.setLastName("Last"); teacher.setId(id); return teacher; } }
true
698ad90f8eb1eafff849fa2c2105e79c9b19be4a
Java
joliebig/featurehouse_fstmerge_examples
/Jmol/rev11338-12038/right-trunk-12038/src/org/jmol/g3d/Normix3D.java
UTF-8
6,194
2.40625
2
[]
no_license
package org.jmol.g3d; import org.jmol.geodesic.Geodesic; import org.jmol.util.BitSetUtil; import javax.vecmath.Vector3f; import javax.vecmath.Matrix3f; import java.util.Random; import java.util.BitSet; import org.jmol.util.Logger; class Normix3D { final static int NORMIX_GEODESIC_LEVEL = Geodesic.standardLevel; private final static int normixCount = Geodesic.getVertexCount(NORMIX_GEODESIC_LEVEL); private final static Vector3f[] vertexVectors = Geodesic.getVertexVectors(); private final static short[][] neighborVertexesArrays = Geodesic.getNeighborVertexesArrays(); private final Vector3f[] transformedVectors; private final byte[] shadeIndexes; private final byte[] shadeIndexes2Sided; private final static boolean TIMINGS = false; private final Matrix3f rotationMatrix = new Matrix3f(); Normix3D() { shadeIndexes = new byte[normixCount]; shadeIndexes2Sided = new byte[normixCount]; transformedVectors = new Vector3f[normixCount]; for (int i = normixCount; --i >= 0; ) transformedVectors[i] = new Vector3f(); if (TIMINGS) { Logger.debug("begin timings!"); for (int i = 0; i < normixCount; ++i) { short normix = getNormix(vertexVectors[i]); System.out.println("draw normix" + i + " {" + vertexVectors[i].x + " " + vertexVectors[i].y + " " + vertexVectors[i].z + "} {0 0 0} \""+i+"\""); if (normix != i) if (Logger.debugging) { Logger.debug("" + i + " -> " + normix); } } Random rand = new Random(); Vector3f vFoo = new Vector3f(); Vector3f vBar = new Vector3f(); Vector3f vSum = new Vector3f(); int runCount = 100000; short[] neighborVertexes = neighborVertexesArrays[NORMIX_GEODESIC_LEVEL]; if (Logger.debugging) Logger.startTimer(); for (int i = 0; i < runCount; ++i) { short foo = (short)(rand.nextDouble() * normixCount); int offsetNeighbor; short bar; do { offsetNeighbor = foo * 6 + (int)(rand.nextDouble() * 6); bar = neighborVertexes[offsetNeighbor]; } while (bar == -1); vFoo.set(vertexVectors[foo]); vFoo.scale(rand.nextFloat()); vBar.set(vertexVectors[bar]); vBar.scale(rand.nextFloat()); vSum.add(vFoo, vBar); vSum.normalize(); } if (Logger.debugging) { Logger.checkTimer("base runtime for " + runCount); Logger.startTimer(); } for (int i = 0; i < runCount; ++i) { short foo = (short)(rand.nextDouble() * normixCount); int offsetNeighbor; short bar; do { offsetNeighbor = foo * 6 + (int)(rand.nextDouble() * 6); bar = neighborVertexes[offsetNeighbor]; } while (bar == -1); vFoo.set(vertexVectors[foo]); vFoo.scale(rand.nextFloat()); vBar.set(vertexVectors[bar]); vBar.scale(rand.nextFloat()); vSum.add(vFoo, vBar); short sum = getNormix(vSum); if (sum != foo && sum != bar) { throw new NullPointerException(); } short sum2 = getNormix(vSum); if (sum != sum2) { Logger.debug("normalized not the same answer?"); throw new NullPointerException(); } } if (Logger.debugging) Logger.checkTimer("normix2 runtime for " + runCount); } } Vector3f[] getTransformedVectors() { return transformedVectors; } boolean isDirectedTowardsCamera(short normix) { return (normix < 0) || (transformedVectors[normix].z > 0); } short getNormix(Vector3f v) { return getNormix(v.x, v.y, v.z, NORMIX_GEODESIC_LEVEL); } Vector3f getVector(short normix) { return vertexVectors[normix]; } private final BitSet bsConsidered = new BitSet(); short getNormix(double x, double y, double z, int geodesicLevel) { short champion; double t; if (z >= 0) { champion = 0; t = z - 1; } else { champion = 11; t = z - (-1); } BitSetUtil.clear(bsConsidered); bsConsidered.set(champion); double championDist2 = x*x + y*y + t*t; for (int lvl = 0; lvl <= geodesicLevel; ++lvl) { short[] neighborVertexes = neighborVertexesArrays[lvl]; for (int offsetNeighbors = 6 * champion, i = offsetNeighbors + (champion < 12 ? 5 : 6); --i >= offsetNeighbors; ) { short challenger = neighborVertexes[i]; if (bsConsidered.get(challenger)) continue; bsConsidered.set(challenger); Vector3f v = vertexVectors[challenger]; double d; d = v.x - x; double d2 = d * d; if (d2 >= championDist2) continue; d = v.y - y; d2 += d * d; if (d2 >= championDist2) continue; d = v.z - z; d2 += d * d; if (d2 >= championDist2) continue; champion = challenger; championDist2 = d2; } } return champion; } short[] inverseNormixes; void calculateInverseNormixes() { inverseNormixes = new short[normixCount]; for (int n = normixCount; --n >= 0; ) { Vector3f v = vertexVectors[n]; inverseNormixes[n] = getNormix(-v.x, -v.y, -v.z, NORMIX_GEODESIC_LEVEL); } } private static byte nullShadeIndex = 50; int getShadeIndex(short normix) { return (normix == ~Graphics3D.NORMIX_NULL || normix == Graphics3D.NORMIX_NULL ? nullShadeIndex : normix < 0 ? shadeIndexes2Sided[~normix] : shadeIndexes[normix]); } void setRotationMatrix(Matrix3f rotationMatrix) { this.rotationMatrix.set(rotationMatrix); for (int i = normixCount; --i >= 0; ) { Vector3f tv = transformedVectors[i]; rotationMatrix.transform(vertexVectors[i], tv); float x = tv.x; float y = -tv.y; float z = tv.z; int shadeIndex = Shade3D.getShadeIndexNormalized(x, y, z); shadeIndexes[i] = (byte) shadeIndex; shadeIndexes2Sided[i] = (byte) (z >= 0 ? shadeIndex : Shade3D.getShadeIndexNormalized(-x, -y, -z)); } } }
true
1d1a1648061b1dbdb99413e3dd8ef1b6c7112b9e
Java
DonaldY/LeetCode-Practice
/src/main/java/chapter10/topic3/LeetCode_1945.java
UTF-8
700
3.03125
3
[ "MIT" ]
permissive
package chapter10.topic3; /** * @author donald * @date 2022/12/15 */ public class LeetCode_1945 { public int getLucky(String s, int k) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); ++i) { char ch = s.charAt(i); sb.append(ch - 'a' + 1); } String digits = sb.toString(); for (int i = 1; i <= k && digits.length() > 1; ++i) { int sum = 0; for (int j = 0; j < digits.length(); ++j) { char ch = digits.charAt(j); sum += ch - '0'; } digits = Integer.toString(sum); } return Integer.parseInt(digits); } }
true
e0f386e6f1e4bd702818f039e87d8417aa0e557e
Java
daravi/modelio
/uml/diagram.editor.sequence/src/org/modelio/diagram/editor/sequence/elements/stateinvariant/GmStateInvariantBodyText.java
UTF-8
4,336
1.804688
2
[]
no_license
/* * Copyright 2013-2018 Modeliosoft * * This file is part of Modelio. * * Modelio is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Modelio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Modelio. If not, see <http://www.gnu.org/licenses/>. * */ package org.modelio.diagram.editor.sequence.elements.stateinvariant; import com.modeliosoft.modelio.javadesigner.annotations.objid; import org.modelio.diagram.elements.common.text.GmElementText; import org.modelio.diagram.elements.core.model.IEditableText; import org.modelio.diagram.elements.core.model.IGmDiagram; import org.modelio.diagram.persistence.IDiagramReader; import org.modelio.diagram.persistence.IDiagramWriter; import org.modelio.metamodel.uml.behavior.interactionModel.StateInvariant; import org.modelio.vcore.smkernel.mapi.MRef; /** * Represents the body text of an StateInvariant. * * @author fpoyer */ @objid ("d9978bb8-55b6-11e2-877f-002564c97630") public class GmStateInvariantBodyText extends GmElementText { /** * Current version of this Gm. Defaults to 0. */ @objid ("d9978bbc-55b6-11e2-877f-002564c97630") private static final int MINOR_VERSION = 0; @objid ("d9978bbf-55b6-11e2-877f-002564c97630") private static final int MAJOR_VERSION = 0; /** * Creates the node. * @param diagram The diagram * @param relatedRef related element reference, must not be <code>null</code>. */ @objid ("d9978bc1-55b6-11e2-877f-002564c97630") public GmStateInvariantBodyText(final IGmDiagram diagram, final MRef relatedRef) { super(diagram, relatedRef); } /** * For deserialization only. */ @objid ("d9978bcc-55b6-11e2-877f-002564c97630") public GmStateInvariantBodyText() { } @objid ("d9978bcf-55b6-11e2-877f-002564c97630") @Override protected String computeText() { return getRelatedElement().getBody(); } @objid ("d9978bd4-55b6-11e2-877f-002564c97630") @Override public IEditableText getEditableText() { StateInvariant theStateInvariant = getRelatedElement(); if (theStateInvariant == null) return null; // else return new IEditableText() { @Override public void setText(String text) { getRelatedElement().setBody(text); } @Override public String getText() { return getRelatedElement().getBody(); } }; } @objid ("d999123a-55b6-11e2-877f-002564c97630") @Override public StateInvariant getRelatedElement() { return (StateInvariant) super.getRelatedElement(); } @objid ("d9991241-55b6-11e2-877f-002564c97630") @Override public void read(IDiagramReader in) { // Read version, defaults to 0 if not found int readVersion = readMinorVersion(in, "GmStateInvariantBodyText."); switch (readVersion) { case 0: { read_0(in); break; } default: { assert (false) : "version number not covered!"; // reading as last handled version: 0 read_0(in); break; } } } @objid ("d9991247-55b6-11e2-877f-002564c97630") @Override public void write(IDiagramWriter out) { super.write(out); // Write version of this Gm if different of 0 writeMinorVersion(out, "GmStateInvariantBodyText.", GmStateInvariantBodyText.MINOR_VERSION); } @objid ("d999124d-55b6-11e2-877f-002564c97630") private void read_0(IDiagramReader in) { super.read(in); } @objid ("d9991252-55b6-11e2-877f-002564c97630") @Override public int getMajorVersion() { return MAJOR_VERSION; } }
true
79a0e4973864e250e394000f0b6f3136f16fae27
Java
PursueMxy/chewu
/app/src/main/java/com/weimu/chewu/module/city/adapter/CitySearchListAdapter.java
UTF-8
1,404
2.15625
2
[]
no_license
package com.weimu.chewu.module.city.adapter; import android.content.Context; import android.view.View; import android.widget.TextView; import com.weimu.chewu.R; import com.weimu.chewu.backend.bean.CityB; import com.weimu.chewu.backend.bean.base.BaseB; import com.weimu.chewu.module.city.adapter.CityAdapter; import com.weimu.chewu.origin.list.mvp.BaseRecyclerMVPAdapter; import com.weimu.universalib.origin.view.list.BaseRecyclerViewHolder; import butterknife.BindView; /** * Author:你需要一台永动机 * Date:2018/5/9 23:28 * Description: */ public class CitySearchListAdapter extends BaseRecyclerMVPAdapter<BaseB, CityB> { public CitySearchListAdapter(Context mContext) { super(mContext); } @Override protected int getItemLayoutRes() { return R.layout.list_city_item; } @Override protected BaseRecyclerViewHolder getViewHolder(View itemView) { return new ItemViewHolder(itemView); } @Override protected void ItemViewChange(BaseRecyclerViewHolder viewHolder, int position) { ItemViewHolder itemHolder = (ItemViewHolder) viewHolder; itemHolder.tvCity.setText(getItem(position).getName()); } class ItemViewHolder extends BaseRecyclerViewHolder { @BindView(R.id.tv_city) TextView tvCity; public ItemViewHolder(View itemView) { super(itemView); } } }
true
6f858e173dfbfef4dc404d5d8270d782efb7c46a
Java
zouhairireda/SpringBootPoc
/src/main/java/pocs/runner/SpringWebApplication.java
UTF-8
803
1.578125
2
[]
no_license
package pocs.runner; import org.apache.camel.spring.boot.CamelSpringBootApplicationController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import pocs.repo.PriceRepository; @SpringBootApplication @ComponentScan(basePackages = "pocs.process") public class SpringWebApplication { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(SpringWebApplication.class, args); //CamelSpringBootApplicationController ctrl = ctx.getBean(CamelSpringBootApplicationController.class); //ctrl.blockMainThread(); } }
true
0d4e8e195bb61fc3d746ef064ea6d266c7ad3824
Java
andjeladjuric/WebProject
/FoodDeliveryApp/src/services/RestaurantService.java
UTF-8
3,000
2.453125
2
[]
no_license
package services; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import beans.Restaurant; import beans.Role; import beans.User; import dao.RestaurantDAO; import dao.UsersDAO; import dto.LoginDTO; import dto.RestaurantDTO; import dto.SignupDTO; @Path("/restaurants") public class RestaurantService { @Context ServletContext ctx; @Context HttpServletRequest request; public RestaurantService() {} @PostConstruct public void init() { if(ctx.getAttribute("restaurants") == null) { String contextPath = ctx.getRealPath(""); ctx.setAttribute("restaurants", new RestaurantDAO(contextPath)); } } @GET @Path("/getAll") @Produces(MediaType.APPLICATION_JSON) public Collection<Restaurant> getPrijave(){ RestaurantDAO dao = (RestaurantDAO) ctx.getAttribute("restaurants"); for (Restaurant p : dao.findAll()) { System.out.println("Ime: "+ p.getName() +"\n"); } return dao.findAll(); } @GET @Path("/getRestaurant") @Produces(MediaType.APPLICATION_JSON) public Restaurant getRestaurant(@QueryParam("id") String id){ RestaurantDAO dao = (RestaurantDAO) ctx.getAttribute("restaurants"); return dao.getById(id); } @POST @Path("/addNewRestaurant") @Consumes(MediaType.APPLICATION_JSON) public void addNewRestaurant(RestaurantDTO rest) { RestaurantDAO dao = (RestaurantDAO) ctx.getAttribute("restaurants"); dao.addNew(rest); } @POST @Path("/getById") @Produces(MediaType.APPLICATION_JSON) public Restaurant getById(String id) { RestaurantDAO dao = (RestaurantDAO) ctx.getAttribute("restaurants"); return dao.getById(id); } @GET @Path("/getRestaurantForManager") @Produces(MediaType.APPLICATION_JSON) public Restaurant getForManager(){ RestaurantDAO dao = (RestaurantDAO) ctx.getAttribute("restaurants"); User user = (User) request.getSession().getAttribute("loginUser"); if(user.getRole() == Role.MANAGER) return dao.getRestaurantByManager(user.getUsername()); return null; } @GET @Path("/deleteRestaurant") @Produces(MediaType.TEXT_HTML) public String deleteRestaurant(@QueryParam("id") String id) { RestaurantDAO dao = (RestaurantDAO) ctx.getAttribute("restaurants"); dao.deleteRestaurant(id); return "/FoodDeliveryApp/administratorPage.html#/"; } @GET @Path("/getRestaurantName") public String getRestaurantName(@QueryParam("id") String id){ RestaurantDAO dao = (RestaurantDAO) ctx.getAttribute("restaurants"); Restaurant found = dao.getRestaurantByManager(id); if( found == null) return ""; else return found.getName(); } }
true