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
a9a347bed5ec8931057e96d51fff56473b29af92
Java
pansaipan/SkyOkHttp
/app/src/main/java/com/skygeoinfo/skyokhttp/request/GetRequest.java
UTF-8
617
2.203125
2
[]
no_license
package com.skygeoinfo.skyokhttp.request; import okhttp3.Request; import okhttp3.RequestBody; /** * 作 者:pansai * 创建日期:17/3/23 下午4:58 * * Get请求实现类 */ public class GetRequest extends BaseRequest<GetRequest> { public GetRequest(String url){ super(url); method = "GET"; } @Override public RequestBody buildRequestBody() { return null; } @Override public Request generateRequest(RequestBody requestBody) { Request.Builder builder = new Request.Builder(); return builder.get().url(url).tag(tag).build(); } }
true
5a3f0909888037b30b00fd4a90fa10997f350659
Java
jerrinot/probeRecord
/src/main/java/uk/co/rockstable/experiements/proberecord/Constants.java
UTF-8
216
1.765625
2
[]
no_license
package uk.co.rockstable.experiements.proberecord; public class Constants { public static final int NO_OF_SLOTS = 32 * 1024 * 1024; public static final int RECORD_SIZE_BYTES = 32; //must be power of two }
true
356afa3636a3e70f161e608bf07e1f022bf64bca
Java
apssouza22/java-microservice
/config-server/src/test/java/demo/OutOfContainerTest.java
UTF-8
1,993
2.21875
2
[ "MIT" ]
permissive
package demo; import com.apssouza.config.Application; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; /** * Out-of-container test for the config server. * Verifies that the server serves up configuration when asked. * Uses "native" profile to obtain properties from local file system rather than GitHub. * * @author ken krueger */ @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration @ActiveProfiles("native") // "native" means use local classpath location rather than GitHub. public class OutOfContainerTest { @Autowired WebApplicationContext spring; MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(spring).build(); } @Test public void propertyLoadTest() throws Exception { // To test if this config server is working, we will simulate a "testConfig" client // calling to get properties for its default profile. These configuration files // (application.yml and testConfig.yml) are on the classpath as the server is // running the 'native' profile: MvcResult result = mockMvc.perform(get("/eureka-server.properties")) .andExpect(status().isOk()) .andReturn() ; } }
true
532f90e7c785264ac9273e0ff9683a4af93afced
Java
rodriguezIsrael/DesingPatterns
/src/com/desingPatterns/structural/facade/CPU.java
UTF-8
278
2.6875
3
[]
no_license
package com.desingPatterns.structural.facade; public class CPU { public void processData() { System.out.println("Processing data...."); } public void turnOn() { System.out.println("Turn ON CPU"); } public void turnOff() { System.out.println("Turn OFF CPU"); } }
true
e6474abe0d9882a51b3a3d3662e04056eee32caf
Java
alexdeassis7/IntroProgramacionFebrero2020
/Clase5ArrayEjercicio1/src/com/utn/ejercicio1array/AppPrincipal.java
ISO-8859-1
1,670
3.78125
4
[]
no_license
package com.utn.ejercicio1array; import java.util.Scanner; public class AppPrincipal { // Calcular el promedio de 10 valores almacenados en un Vector. Determinar adems cuantos son // mayores que el promedio, imprimir el promedio, el nmero de datos mayores que el promedio // y una lista de valores mayores que el promedio . public static void main(String[] args) { /*definimos las variables de trabajo*/ float sumatoria = 0 , promedio = 0; float[] notas = new float[10]; int mayores = 0 ; Scanner teclado = new Scanner(System.in); /**solicitamos al usuario ingrese las notas * y las guardamos en cada indice del array (notas)*/ for (int i = 0; i < notas.length; i++) { System.out.println("ingrese la nota " + (i+1)); notas[i] = teclado.nextFloat(); sumatoria += notas[i]; } //Calculamos el promedio promedio = sumatoria / notas.length ; //contamos los valores mayores al promedio for (int i = 0; i < notas.length; i++) { if(notas[i] > promedio) { mayores ++; } } float [] listaDeMayores = new float[mayores]; int j = 0; System.out.println("PROMEDIO" +promedio); for (int i = 0; i < notas.length; i++) { if(notas[i] > promedio) { listaDeMayores[j] = notas[i]; j ++; } } //mostramos los datos procesados System.out.println("Promedio : " + promedio); System.out.println("Cantidad Mayores al promedio :" + mayores); System.out.println("valores mayores son :"); for (int i = 0; i < listaDeMayores.length; i++) { System.out.println(listaDeMayores[i]); } } }
true
da67d27ac37357c502585318dc7bf805e0588eac
Java
milek888/repotest
/src/main/java/springboot/Application.java
UTF-8
1,070
1.9375
2
[]
no_license
package springboot; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import java.util.logging.Logger; @SpringBootApplication @EnableWebMvc public class Application implements ApplicationListener<ContextRefreshedEvent> { //5555555555555555555555555 //666666666666666 //7777777777777777777777777 //888888888888888888888888888888 //999999999999999999 private static final Logger LOG = Logger.getLogger("Application.class"); @Value("${spring.profiles.active}") private String activeProfile; @Override public void onApplicationEvent(ContextRefreshedEvent event) { LOG.info("activeProfile: " + activeProfile); } public static void main(String[] args) { SpringApplication.run(Application.class); } }
true
605eaa243a18e5e5e35e207afe32e8269c2e6bf0
Java
duanjinpeng/MpSystem
/src/main/java/cn/edu/hist/dict/service/impl/SystemConfigServiceImpl.java
UTF-8
1,723
2.203125
2
[]
no_license
package cn.edu.hist.dict.service.impl; import java.util.List; import cn.edu.hist.dict.service.SystemConfigService; import cn.edu.hist.mapper.BasicinfoMapper; import cn.edu.hist.mapper.DictinfoMapper; import cn.edu.hist.model.Basicinfo; import cn.edu.hist.model.Dictinfo; import cn.edu.hist.model.DictinfoExample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemConfigServiceImpl implements SystemConfigService { @Autowired DictinfoMapper dictinfoMapper; @Autowired BasicinfoMapper basicinfoMapper; //根据数据字典typecode获取字典明细信息 @Override public List findDictinfoByType(String typecode) throws Exception { DictinfoExample dictinfoExample = new DictinfoExample(); DictinfoExample.Criteria criteria = dictinfoExample.createCriteria(); criteria.andTypecodeEqualTo(typecode); return dictinfoMapper.selectByExample(dictinfoExample); } //根据typeocde和dictcode获取单个字典明细 public Dictinfo findDictinfoByDictcode(String typecode,String dictcode) throws Exception{ DictinfoExample dictinfoExample = new DictinfoExample(); DictinfoExample.Criteria criteria = dictinfoExample.createCriteria(); criteria.andDictcodeEqualTo(dictcode); criteria.andTypecodeEqualTo(typecode); List<Dictinfo> list = dictinfoMapper.selectByExample(dictinfoExample); if(list!=null && list.size()==1){ return list.get(0); } return null; } /** * 根据id获取系统配置信息 */ @Override public Basicinfo findBasicinfoById(String id) throws Exception { return basicinfoMapper.selectByPrimaryKey(id); } }
true
a960ef198b138aef6667f975b81fd2f8a85386db
Java
2037118171l/xgdjweb
/src/main/java/com/xgdjweb/bean/Pictureupload.java
UTF-8
1,140
1.859375
2
[]
no_license
package com.xgdjweb.bean; public class Pictureupload { private Integer pid; private String picturetitle; private String picturepath; private String picturename; private String putton; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getPicturetitle() { return picturetitle; } public void setPicturetitle(String picturetitle) { this.picturetitle = picturetitle == null ? null : picturetitle.trim(); } public String getPicturepath() { return picturepath; } public void setPicturepath(String picturepath) { this.picturepath = picturepath == null ? null : picturepath.trim(); } public String getPicturename() { return picturename; } public void setPicturename(String picturename) { this.picturename = picturename == null ? null : picturename.trim(); } public String getPutton() { return putton; } public void setPutton(String putton) { this.putton = putton == null ? null : putton.trim(); } }
true
27f393af7876f30c24ef1c9fa7784fdbd407af17
Java
KarinaRomero/itsonSoft
/src/java/entity/CustomerOrder.java
UTF-8
5,310
2.125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author KarinaRomero */ @Entity @Table(name = "customer_order") @XmlRootElement @NamedQueries({ @NamedQuery(name = "CustomerOrder.findAll", query = "SELECT c FROM CustomerOrder c"), @NamedQuery(name = "CustomerOrder.findByIdcustomero", query = "SELECT c FROM CustomerOrder c WHERE c.idcustomero = :idcustomero"), @NamedQuery(name = "CustomerOrder.findByAmount", query = "SELECT c FROM CustomerOrder c WHERE c.amount = :amount"), @NamedQuery(name = "CustomerOrder.findByDateCreated", query = "SELECT c FROM CustomerOrder c WHERE c.dateCreated = :dateCreated"), @NamedQuery(name = "CustomerOrder.findByConfirmationNumber", query = "SELECT c FROM CustomerOrder c WHERE c.confirmationNumber = :confirmationNumber")}) public class CustomerOrder implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idcustomero") private Integer idcustomero; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Basic(optional = false) @NotNull @Column(name = "amount") private BigDecimal amount; @Basic(optional = false) @NotNull @Column(name = "date_created") @Temporal(TemporalType.TIMESTAMP) private Date dateCreated; @Basic(optional = false) @NotNull @Column(name = "confirmation_number") private int confirmationNumber; @JoinTable(name = "customer_order_has_product", joinColumns = { @JoinColumn(name = "customer_order_idcustomero", referencedColumnName = "idcustomero")}, inverseJoinColumns = { @JoinColumn(name = "product_idProduct", referencedColumnName = "idProduct")}) @ManyToMany private List<Product> productList; @JoinColumn(name = "customer_idcustomer", referencedColumnName = "idcustomer") @ManyToOne(optional = false) private Customer customerIdcustomer; public CustomerOrder() { } public CustomerOrder(Integer idcustomero) { this.idcustomero = idcustomero; } public CustomerOrder(Integer idcustomero, BigDecimal amount, Date dateCreated, int confirmationNumber) { this.idcustomero = idcustomero; this.amount = amount; this.dateCreated = dateCreated; this.confirmationNumber = confirmationNumber; } public Integer getIdcustomero() { return idcustomero; } public void setIdcustomero(Integer idcustomero) { this.idcustomero = idcustomero; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public int getConfirmationNumber() { return confirmationNumber; } public void setConfirmationNumber(int confirmationNumber) { this.confirmationNumber = confirmationNumber; } @XmlTransient public List<Product> getProductList() { return productList; } public void setProductList(List<Product> productList) { this.productList = productList; } public Customer getCustomerIdcustomer() { return customerIdcustomer; } public void setCustomerIdcustomer(Customer customerIdcustomer) { this.customerIdcustomer = customerIdcustomer; } @Override public int hashCode() { int hash = 0; hash += (idcustomero != null ? idcustomero.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CustomerOrder)) { return false; } CustomerOrder other = (CustomerOrder) object; if ((this.idcustomero == null && other.idcustomero != null) || (this.idcustomero != null && !this.idcustomero.equals(other.idcustomero))) { return false; } return true; } @Override public String toString() { return "entity.CustomerOrder[ idcustomero=" + idcustomero + " ]"; } }
true
23ec660783134b023122e50c0d0f7199e1b4d411
Java
floshton/CoreBC
/src/main/java/com/bconnect/common/jpa/util/SearchParameterBean.java
UTF-8
658
2.046875
2
[]
no_license
package com.bconnect.common.jpa.util; /** * * @author Jorge Rodriguez */ public class SearchParameterBean { private Object object; private String queryClause; private String parameterName; public SearchParameterBean(Object object, String queryClause) { this.object = object; this.queryClause = queryClause; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public String getQueryClause() { return queryClause; } public void setQueryClause(String queryClause) { this.queryClause = queryClause; } }
true
9be3a5e7afc750c486fe418ab97f8b6865ff5b1a
Java
tandpsolutions/SkableClient_2_0_1
/src/masterController/CameraMasterController.java
UTF-8
12,222
2
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package masterController; import com.google.gson.JsonObject; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.KeyStroke; import masterView.CameraMasterView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofitAPI.CameraAPI; import retrofitAPI.SupportAPI; import skable.SkableHome; import support.Library; public class CameraMasterController extends javax.swing.JDialog { public static final int RET_CANCEL = 0; public static final int RET_OK = 1; boolean formLoad = false; private Library lb = Library.getInstance(); private String camera_cd = ""; private CameraMasterView bmv = null; private CameraAPI cameraAPI; public CameraMasterController(java.awt.Frame parent, boolean modal, CameraMasterView cmv, String camera_cd, String camera_name) { super(parent, modal); initComponents(); // Close the dialog when Esc is pressed String cancelName = "cancel"; InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName); ActionMap actionMap = getRootPane().getActionMap(); actionMap.put(cancelName, new AbstractAction() { public void actionPerformed(ActionEvent e) { doClose(RET_CANCEL); } }); this.bmv = cmv; cameraAPI = lb.getRetrofit().create(CameraAPI.class); jtxtCameraName.setText(camera_name); this.camera_cd = camera_cd; jtxtCameraName.requestFocusInWindow(); } public int getReturnStatus() { return returnStatus; } private void validateVoucher() { if (lb.isBlank(jtxtCameraName)) { lb.showMessageDailog("Camera name can not be left blank"); jtxtCameraName.requestFocusInWindow(); return; } if (camera_cd.equalsIgnoreCase("")) { Call<JsonObject> call = lb.getRetrofit().create(SupportAPI.class).validateData("cameramst", "camera_cd", "camera_name", jtxtCameraName.getText(),SkableHome.db_name,SkableHome.selected_year); call.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<JsonObject> rspns) { if (rspns.isSuccessful()) { if (rspns.body().get("result").getAsInt() == 0) { lb.showMessageDailog("Camera already exist"); return; } else { saveVoucher(); } } else { lb.showMessageDailog(rspns.message()); } } @Override public void onFailure(Call<JsonObject> call, Throwable thrwbl) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); } else { Call<JsonObject> call = lb.getRetrofit().create(SupportAPI.class).ValidateDataEdit("cameramst", "camera_cd", "camera_name", jtxtCameraName.getText(), "camera_cd", camera_cd,SkableHome.db_name,SkableHome.selected_year); call.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<JsonObject> rspns) { if (rspns.isSuccessful()) { if (rspns.body().get("result").getAsInt() == 0) { lb.showMessageDailog("Camera already exist"); return; } else { saveVoucher(); } } else { lb.showMessageDailog(rspns.message()); } } @Override public void onFailure(Call<JsonObject> call, Throwable thrwbl) { } }); } } private void saveVoucher() { Call<JsonObject> call = cameraAPI.addUpdateCameraMaster(camera_cd, jtxtCameraName.getText(), SkableHome.user_id,SkableHome.selected_year,SkableHome.db_name,SkableHome.selected_year); lb.addGlassPane(this); call.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<JsonObject> rspns) { lb.removeGlassPane(CameraMasterController.this); if (rspns.isSuccessful()) { if (rspns.body().get("result").getAsInt() == 1) { lb.showMessageDailog(rspns.body().get("Cause").getAsString()); if (bmv != null) { bmv.addRow(rspns.body().get("camera_cd").getAsString(), jtxtCameraName.getText()); } CameraMasterController.this.dispose(); } else { lb.showMessageDailog(rspns.body().get("Cause").getAsString()); } } else { lb.showMessageDailog(rspns.message()); } } @Override public void onFailure(Call<JsonObject> call, Throwable thrwbl) { lb.removeGlassPane(CameraMasterController.this); } }); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { cancelButton = new javax.swing.JButton(); jbtnSave = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jtxtCameraName = new javax.swing.JTextField(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { closeDialog(evt); } }); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); jbtnSave.setText("Save"); jbtnSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnSaveActionPerformed(evt); } }); jbtnSave.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jbtnSaveKeyPressed(evt); } }); jLabel1.setText("Camera Name"); jtxtCameraName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jtxtCameraNameFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jtxtCameraNameFocusLost(evt); } }); jtxtCameraName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jtxtCameraNameKeyPressed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 192, Short.MAX_VALUE) .addComponent(jbtnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancelButton)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtxtCameraName))) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, jbtnSave}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtxtCameraName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(jbtnSave)) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jtxtCameraName}); pack(); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed doClose(RET_CANCEL); }//GEN-LAST:event_cancelButtonActionPerformed private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog doClose(RET_CANCEL); }//GEN-LAST:event_closeDialog private void jbtnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSaveActionPerformed validateVoucher(); }//GEN-LAST:event_jbtnSaveActionPerformed private void jbtnSaveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbtnSaveKeyPressed lb.enterClick(evt); }//GEN-LAST:event_jbtnSaveKeyPressed private void jtxtCameraNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtCameraNameFocusGained // TODO add your handling code here: lb.selectAll(evt); }//GEN-LAST:event_jtxtCameraNameFocusGained private void jtxtCameraNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtCameraNameFocusLost // TODO add your handling code here: lb.toUpper(evt); }//GEN-LAST:event_jtxtCameraNameFocusLost private void jtxtCameraNameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtxtCameraNameKeyPressed // TODO add your handling code here: lb.enterFocus(evt, jbtnSave); }//GEN-LAST:event_jtxtCameraNameKeyPressed private void doClose(int retStatus) { returnStatus = retStatus; setVisible(false); dispose(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JLabel jLabel1; private javax.swing.JButton jbtnSave; private javax.swing.JTextField jtxtCameraName; // End of variables declaration//GEN-END:variables private int returnStatus = RET_CANCEL; }
true
717cf3613a8e2b32665b348ab4ee139c3ee6e037
Java
danpal/OpenSAML
/src/main/java/org/opensaml/saml1/binding/encoding/.svn/text-base/HTTPPostEncoder.java.svn-base
UTF-8
6,270
1.992188
2
[ "Apache-2.0" ]
permissive
/* * Copyright [2007] [University Corporation for Advanced Internet Development, Inc.] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensaml.saml1.binding.encoding; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml1.core.ResponseAbstractType; import org.opensaml.ws.message.MessageContext; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.ws.transport.http.HTTPOutTransport; import org.opensaml.ws.transport.http.HTTPTransportUtils; import org.opensaml.xml.util.Base64; import org.opensaml.xml.util.XMLHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * SAML 1.X HTTP POST message encoder. */ public class HTTPPostEncoder extends BaseSAML1MessageEncoder { /** Class logger. */ private final Logger log = LoggerFactory.getLogger(HTTPPostEncoder.class); /** Velocity engine used to evaluate the template when performing POST encoding. */ private VelocityEngine velocityEngine; /** ID of the velocity template used when performing POST encoding. */ private String velocityTemplateId; /** * Constructor. * * @param engine velocity engine instance used to create POST body * @param templateId ID of the template used to create POST body */ public HTTPPostEncoder(VelocityEngine engine, String templateId) { super(); velocityEngine = engine; velocityTemplateId = templateId; } /** {@inheritDoc} */ public String getBindingURI() { return SAMLConstants.SAML1_POST_BINDING_URI; } /** {@inheritDoc} */ public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { return false; } /** {@inheritDoc} */ public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { return false; } /** {@inheritDoc} */ protected void doEncode(MessageContext messageContext) throws MessageEncodingException { if (!(messageContext instanceof SAMLMessageContext)) { log.error("Invalid message context type, this encoder only support SAMLMessageContext"); throw new MessageEncodingException( "Invalid message context type, this encoder only support SAMLMessageContext"); } if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); throw new MessageEncodingException( "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); } SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage(); if (outboundMessage == null) { throw new MessageEncodingException("No outbound SAML message contained in message context"); } String endpointURL = getEndpointURL(samlMsgCtx); if (samlMsgCtx.getOutboundSAMLMessage() instanceof ResponseAbstractType) { ((ResponseAbstractType) samlMsgCtx.getOutboundSAMLMessage()).setRecipient(endpointURL); } signMessage(samlMsgCtx); samlMsgCtx.setOutboundMessage(outboundMessage); postEncode(samlMsgCtx, endpointURL); } /** * Base64 and POST encodes the outbound message and writes it to the outbound transport. * * @param messageContext current message context * @param endpointURL endpoint URL to encode message to * * @throws MessageEncodingException thrown if there is a problem encoding the message */ protected void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException { log.debug("Invoking velocity template to create POST body"); try { VelocityContext context = new VelocityContext(); log.debug("Encoding action url of: {}", endpointURL); context.put("action", endpointURL); log.debug("Marshalling and Base64 encoding SAML message"); String messageXML = XMLHelper.nodeToString(marshallMessage(messageContext.getOutboundSAMLMessage())); String encodedMessage = Base64.encodeBytes(messageXML.getBytes(), Base64.DONT_BREAK_LINES); context.put("SAMLResponse", encodedMessage); if (messageContext.getRelayState() != null) { log.debug("Setting TARGET parameter to: {}", messageContext.getRelayState()); context.put("TARGET", messageContext.getRelayState()); } HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); HTTPTransportUtils.addNoCacheHeaders(outTransport); HTTPTransportUtils.setUTF8Encoding(outTransport); HTTPTransportUtils.setContentType(outTransport, "text/html"); OutputStream transportOutStream = outTransport.getOutgoingStream(); Writer out = new OutputStreamWriter(transportOutStream, "UTF-8"); velocityEngine.mergeTemplate(velocityTemplateId, "UTF-8", context, out); out.flush(); } catch (Exception e) { log.error("Error invoking velocity template", e); throw new MessageEncodingException("Error creating output document", e); } } }
true
198feab975b6b21509ed708918849250783f3ac7
Java
iNastik/JavaStage1
/src/main/java/training/classes/Main.java
UTF-8
2,148
3.203125
3
[]
no_license
package training.classes; public class Main { private static Patient[] patientList; public static void main(String[] args) { Main main = new Main(); main.setPatientList(); main.printPatientsByDiagnosis("Allergy"); System.out.println(); main.printPatientsByCardNumber(33240, 33270); } private void setPatientList() { patientList = new Patient[]{ new Patient(121, "Petrova", "Anna", "Nikolaevna", "Lenina 24", 297474936, 33412, "Avitaminosis"), new Patient(122, "Kiselev", "Igor", "Ivanovich", "Pirogova 76 - 12", 298463754, 33265, "Adenoma"), new Patient(123, "Silin", "Leonid", "Nikolaevich", "Pobedy 64 - 23", 337474445, 33245, "Allergy"), new Patient(124, "Ivanova", "Irina", "iosifovna", "Kirova 21 - 2", 291134584, 22545, "Arthritis"), new Patient(125, "Mironova", "Elena", "Ivanovna", "Esenina 129 - 35", 336647545, 33874, "Adenoma"), new Patient(126, "Nikolaev", "Dmitry", "Dmitrievich", "Lenina 38", 297074547, 33248, "Alcoholism"), new Patient(127, "Isaev", "Vasily", "Petrovich", "Geroev 19", 294456363, 33250, "Allergy"), new Patient(128, "Kirov", "Alexey", "Ivanovich", "Mira 46", 298904546, 33269, "Anemia"), new Patient(129, "Levin", "Kirill", "Eliseevich", "Gornaya 90 - 12", 291765345, 33278, "Artritis"), new Patient(130, "Horina", "Olga", "Petrovna", "Sadovaya 8", 296737373, 33598, "Allergy") }; } private void printPatientsByDiagnosis(String diagnosis) { for (Patient patient : patientList) { if (patient.getDiagnosis().equals(diagnosis)) { System.out.println(patient); } } } private void printPatientsByCardNumber(long medicalCardNumberMin, long medicalCardNumberMax) { for (Patient patient : patientList) { if (patient.getMedicalCardNumber() >= medicalCardNumberMin && patient.getMedicalCardNumber() <= medicalCardNumberMax) { System.out.println(patient); } } } }
true
147f3d31fad72f852bb9ec4f84cb60c6940a67c0
Java
hailinliu/Dexintong
/app/src/main/java/com/runtai/newdexintong/module/personalcenter/activity/OtherReplaceActivity.java
UTF-8
9,293
1.742188
2
[]
no_license
package com.runtai.newdexintong.module.personalcenter.activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.runtai.newdexintong.R; import com.runtai.newdexintong.comment.activity.BaseActivity; import com.runtai.newdexintong.comment.utils.LogUtil; import com.runtai.newdexintong.comment.utils.MyDateUtils; import com.runtai.newdexintong.comment.utils.RandomUtil; import com.runtai.newdexintong.comment.utils.SPUtils; import com.runtai.newdexintong.comment.utils.StringUtil; import com.runtai.newdexintong.comment.utils.ToastUtil; import com.runtai.newdexintong.comment.utils.des.Base64; import com.runtai.newdexintong.comment.utils.des.UTF8Util; import com.runtai.newdexintong.module.home.widget.DialogUtil; import com.runtai.newdexintong.module.home.widget.MyAlertDialog; import com.runtai.newdexintong.module.home.utils.AppConstant; import com.runtai.newdexintong.module.home.utils.GsonUtil; import com.runtai.newdexintong.module.personalcenter.adapter.OtherReplaceGoodsAdapter; import com.runtai.newdexintong.module.personalcenter.bean.OtherReplaceGoodsBean; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Request; /** * 申请其他替换对应的界面 */ public class OtherReplaceActivity extends BaseActivity { private ImageView iv_search3; private TextView tv_subtitle; private RelativeLayout head_back; private ListView lv_other_replace; private List<OtherReplaceGoodsBean.DataBean> mData; private EditText et_search2; private static HashMap<Integer, Boolean> isChecked; private OtherReplaceGoodsAdapter adapter; private TextView tv_no_data; private String QValue = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other_replace); showLoading(); httpData(); initView(); registerListener(); } private void httpData() { String url = AppConstant.BASEURL2 + "api/order/searchs"; String timeStamp = MyDateUtils.getCurrentMillisecond(); String randomNumberTen = RandomUtil.getRandomNumberTen(); String accessToken = SPUtils.getString(this, "accessToken", ""); Map<String, String> map = new HashMap<>(); map.clear(); map.put("Timestamp", timeStamp); map.put("Nonce", randomNumberTen); map.put("AppId", AppConstant.appid_value); String signValue = StringUtil.getSignValue(map); OkHttpUtils.post().url(url).addHeader(AppConstant.HEADER_NAME, AppConstant.HEADER_VERSION) .addHeader("Authorization", accessToken) .addParams("Sign", signValue) .addParams("Timestamp", timeStamp) .addParams("Nonce", randomNumberTen) .addParams("AppId", AppConstant.appid_value) .build().execute(new StringCallback() { @Override public void onResponse(String response) { try { byte[] decode = Base64.decode(response);//base64解码 String strJson = UTF8Util.getString(decode); JSONObject jsonObject = new JSONObject(strJson); int code = Integer.parseInt(jsonObject.getString("Code")); String msg = jsonObject.getString("Msg"); if (code == 200) { Gson gson = GsonUtil.buildGson(); OtherReplaceGoodsBean otherReplaceGoodsBean = gson.fromJson(strJson, OtherReplaceGoodsBean.class); if (mData == null) { mData = new ArrayList<OtherReplaceGoodsBean.DataBean>(); } mData.clear(); mData = otherReplaceGoodsBean.getData(); adapter = new OtherReplaceGoodsAdapter(OtherReplaceActivity.this, mData); lv_other_replace.setAdapter(adapter); } else if (code == 403) { DialogUtil.showDialog(OtherReplaceActivity.this, getResources().getString(R.string.need_login_again)); } else { ToastUtil.showToast(OtherReplaceActivity.this, msg, Toast.LENGTH_SHORT); } } catch (JSONException e) { e.printStackTrace(); } dismissLoading(); } @Override public void onError(Request request, Exception e) { LogUtil.e("search_result", e.toString()); dismissLoading(); } }); } private void initView() { setActivityTitle(); tv_no_data = (TextView) findViewById(R.id.tv_no_data); isChecked = new HashMap<>(); lv_other_replace = (ListView) findViewById(R.id.lv_other_replace); } private void registerListener() { head_back.setOnClickListener(this); tv_subtitle.setOnClickListener(this); lv_other_replace.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // isChecked.clear(); OtherReplaceGoodsBean.DataBean dataBean = mData.get(position); for (int i = 0; i < mData.size(); i++) { if (position == i) { isChecked.put(position, true); } else { isChecked.put(i, false); } } OtherReplaceGoodsAdapter.setIsChecked(isChecked); adapter.notifyDataSetChanged(); showMyDialog(dataBean); } }); } /** * 弹出提示框 */ private void showMyDialog(final OtherReplaceGoodsBean.DataBean bean) { new MyAlertDialog(OtherReplaceActivity.this).builder() .setTitle("您确定要调换为选中的商品吗?") .setPositiveButton("确定", new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.putExtra("unit", bean.getUnit()); intent.putExtra("specStr", String.valueOf(bean.getSpec())); intent.putExtra("goodsName", bean.getItemName()); intent.putExtra("goodsPrice", StringUtil.strToDouble_new(String.valueOf(bean.getOriginalPrice()))); intent.putExtra("stock", String.valueOf(bean.getStock())); intent.putExtra("itemId", String.valueOf(bean.getItemId())); setResult(100, intent); onBackPressed(); } }).setNegativeButton("取消", new View.OnClickListener() { @Override public void onClick(View v) { } }).show(); } /** * 设置界面标题栏 */ private void setActivityTitle() { head_back = (RelativeLayout) findViewById(R.id.head_back); ((TextView) findViewById(R.id.tv_title)).setVisibility(View.GONE); RelativeLayout rl_search_result = (RelativeLayout) findViewById(R.id.rl_search_result); iv_search3 = (ImageView) findViewById(R.id.iv_search3); rl_search_result.setVisibility(View.VISIBLE); et_search2 = (EditText) findViewById(R.id.et_search2); tv_subtitle = (TextView) findViewById(R.id.tv_subtitle); tv_subtitle.setVisibility(View.VISIBLE); tv_subtitle.setText("搜索"); } @Override public void onClick(View v) { super.onClick(v); switch (v.getId()) { case R.id.head_back: onBackPressed(); break; case R.id.tv_subtitle://点击搜索 if (checkSearchInfo()) { Intent intent = new Intent(this, OtherReplaceSearchResultActivity.class); intent.putExtra("goodsname", getSearchContent()); startActivityByIntent(intent); finish(); } break; } } private boolean checkSearchInfo() { String search_content = getSearchContent(); if (TextUtils.isEmpty(search_content)) { ToastUtil.showToast(this, "请输入要搜索的商品名称", Toast.LENGTH_SHORT); return false; } return true; } private String getSearchContent() { return et_search2.getText().toString().trim(); } }
true
584807b005dc1f260e5e356ca7b53c24c444061e
Java
Choukouna/Spring2020
/spring-boot-sample-aop-standalone/src/main/java/sample/aop/service/LauncherService.java
UTF-8
331
1.875
2
[]
no_license
package sample.aop.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import sample.aop.client.IRun; @Component public class LauncherService { @Autowired private IRun client; public void run(String... args) { this.client.run(); } }
true
16f56b692af234aa8a296ae826ff5e05601fed89
Java
adiraj297/EaglesvSharks-game
/src/Model/Piece/Shark4.java
UTF-8
425
2.703125
3
[]
no_license
package Model.Piece; import Model.Player; public class Shark4 extends Shark { private static final int ATTACK_POWER = 5; private static final int DEFENCE_POWER = 5; private static final int MOVE_POWER = 5; public Shark4(Player player) { super(player); this.attackPower = ATTACK_POWER; this.defencePower = DEFENCE_POWER; this.movePower = MOVE_POWER; } public String iconName() { return "shark4"; } }
true
83c0dfd5925191f67e52eca42932d03f9741a0ec
Java
rizwanalvi/AndroidCode
/DatabaseExample/app/src/main/java/com/example/databaseexample/DashboardActivity.java
UTF-8
2,315
2.328125
2
[]
no_license
package com.example.databaseexample; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class DashboardActivity extends AppCompatActivity { FirebaseAuth mAuth=null; private FirebaseDatabase database=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); mAuth= FirebaseAuth.getInstance(); database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("users"); myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. Customer value = dataSnapshot.child(mAuth.getCurrentUser().getUid()).getValue(Customer.class); Log.e( "onDataChange: ", value.getName().toString()); ((EditText) findViewById(R.id.txtData)).setText(value.getName().toString()); } @Override public void onCancelled(DatabaseError error) { // Failed to read value } }); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { mAuth.signOut(); Intent _intnet = new Intent(DashboardActivity.this,MainActivity.class); startActivity(_intnet); finish(); return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater _munu = getMenuInflater(); _munu.inflate(R.menu.menu,menu); return true; } }
true
c76a9f052c8624198e9c6e5df22f1e6ede5d75ca
Java
leanshi2018/b2c
/trunk/system/src/main/java/com/framework/loippi/service/impl/LogServiceImpl.java
UTF-8
631
1.898438
2
[]
no_license
package com.framework.loippi.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.framework.loippi.dao.LogDao; import com.framework.loippi.entity.Log; import com.framework.loippi.service.LogService; /** * Service - 日志 * * @author Mounate Yan。 * @version 1.0 */ @Service("logServiceImpl") public class LogServiceImpl extends GenericServiceImpl<Log, Long> implements LogService { @Autowired private LogDao logDao; @Autowired public void setGenericDao() { super.setGenericDao(logDao); } public void clear() { logDao.clear(); } }
true
d7ce18d0e3478663f4558530264f4ec548392886
Java
jiehao321/lk
/src/com/java/likou/数组/最长公共前缀.java
UTF-8
825
3.859375
4
[]
no_license
package com.java.likou.数组; /** * 编写一个函数来查找字符串数组中的最长公共前缀。 * * 如果不存在公共前缀,返回空字符串 ""。 * *   * * 示例 1: * * 输入:strs = ["flower","flow","flight"] * 输出:"fl" * 示例 2: * * 输入:strs = ["dog","racecar","car"] * 输出:"" * 解释:输入不存在公共前缀。 */ public class 最长公共前缀 { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; String res = strs[0]; for (int i = 1; i < strs.length; i++) { int j = 0; for (; j < res.length() && j < strs[i].length(); j++) if (res.charAt(j) != strs[i].charAt(j))break; res = res.substring(0, j); } return res; } }
true
38c025c689e9f07eab0edb433f4dc725229110a1
Java
BITS-GridWatch/BPGC-Android-app
/app/src/main/java/com/macbitsgoa/bitsgridwatch/OnboardingSliderAdapter.java
UTF-8
2,744
2.3125
2
[]
no_license
package com.macbitsgoa.bitsgridwatch; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; public class OnboardingSliderAdapter extends PagerAdapter { private Context context; private LayoutInflater layoutInflater; public OnboardingSliderAdapter(Context context) { this.context = context; } public String[] slide_titles = { "Welcome to UJALA!", "The Map", "The Settings" }; public String[] slide_descriptions = { "This is an initiative to detect and log power cuts in BITS Pilani, K K Birla Goa Campus. The app monitors your phone and gives you near real-time information about electricity around you.", "The marks on the map show you the areas with presence of power supply. Additionally, you can choose to view the data from past 5 minutes or past 1 hour by tapping on the floating action button at the bottom right.", "The settings page gives you further control over the app, along with options such as changing the theme, toggling the monitoring and viewing your profile." }; public int[] slide_icons = { R.drawable.ujala_logo, R.drawable.map_logo, R.drawable.settings_logo }; @Override public int getCount() { return slide_titles.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == (RelativeLayout) object; } @Override public Object instantiateItem(ViewGroup container, int position) { layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.slide_layout, container, false); TextView slide_title = view.findViewById(R.id.slide_title); TextView slide_desc = view.findViewById(R.id.slide_desc); ImageView slide_icon = view.findViewById(R.id.slide_icon); slide_title.setText(slide_titles[position]); slide_desc.setText(slide_descriptions[position]); slide_icon.setImageResource(slide_icons[position]); if (position == 0) slide_icon.setPadding(300, 50, 300, 0); else slide_icon.setPadding(380, 50, 380, 10); container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((RelativeLayout) object); } }
true
80727e06aa8089d722c30159c6640325cba9762c
Java
guangmomo/BaseCode
/app/src/main/java/com/xuliwen/basecode/javacode/concurrent/combat/test2/countdownlatch/Run.java
UTF-8
1,430
3.0625
3
[]
no_license
package com.xuliwen.basecode.javacode.concurrent.combat.test2.countdownlatch; import java.util.Map; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; /** * Created by xlw on 2017/6/25. */ public class Run { private ConcurrentHashMap<String ,Integer> concurrentHashMap=new ConcurrentHashMap<>(); private CountDownLatch countDownLatch=new CountDownLatch(3); public static void main(String[] args) { new Run().test(); } private void test(){ new Thread(){ @Override public void run() { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } int sum=0; for(Map.Entry<String ,Integer> entry:concurrentHashMap.entrySet()){ sum+=entry.getValue(); } System.out.println("结果为:"+sum); } }.start(); for(int i=0;i<3;i++){ new Thread(){ @Override public void run() { concurrentHashMap.put(Thread.currentThread().getName(),1); countDownLatch.countDown(); } }.start(); } } }
true
fa62f4be78845c8fcc9aaa41a2076b78b0e6ad9d
Java
HaranArbel/Compiler
/EX3/FOLDER_2_SRC/TYPES/TYPE.java
UTF-8
1,270
3.046875
3
[]
no_license
package TYPES; public abstract class TYPE { /******************************/ /* Every type has a name ... */ /******************************/ public String name; /*************/ /* isClass() */ /*************/ public boolean isClass(){ return false;} /*************/ /* isArray() */ /*************/ public boolean isArray(){ return false;} /*************/ /* isString() */ /*************/ public boolean isString() { return false;} /*************/ /* isInt() */ /*************/ public boolean isInt() { return false;} /****************/ /* isInstance() */ /****************/ //returns true if this is an instance of a type //for example: //on input "int" returns true iff this is the singleton instance of TYPE_INT //on input "Person" returns true iff this is the singleton instance of TYPE_CLASS with name "Person" public boolean isInstance(String name) { return !(this.name.equals(name)); } /****************/ /* isPrimitive() */ /****************/ //returns true if public boolean isPrimitive() { return false; } /*****************************************/ /* To distinct function from other types */ /*****************************************/ public boolean isFunction(){ return false; } }
true
023dd02418d22623c21c239191cc253d0c8cd968
Java
GodsJoy/LendaBook
/app/src/main/java/com/example/android/lendabook/Book.java
UTF-8
2,218
2.65625
3
[]
no_license
package com.example.android.lendabook; import android.os.Parcel; import android.os.Parcelable; /** * Created by ayomide on 11/10/18. * A book POJO */ public class Book implements Parcelable { private String name; private String group; private String imageUri; private String ownerId; private String ownerEmail; public Book(){} public Book(String name, String group, String imageUri, String ownerId, String ownerEmail) { this.name = name; this.group = group; this.imageUri = imageUri; this.ownerId = ownerId; this.ownerEmail = ownerEmail; } private Book(Parcel in){ this.name = in.readString(); this.group = in.readString(); this.imageUri = in.readString(); this.ownerId = in.readString(); this.ownerEmail = in.readString(); } public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() { public Book createFromParcel(Parcel in) { return new Book(in); } public Book[] newArray(int size) { return new Book[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(name); parcel.writeString(group); parcel.writeString(imageUri); parcel.writeString(ownerId); parcel.writeString(ownerEmail); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getImageUri() { return imageUri; } public void setImageUri(String imageUri) { this.imageUri = imageUri; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getOwnerEmail() { return ownerEmail; } public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } }
true
7bde66e78fb395fe1e667df818be177065b55ced
Java
cirola2000/SubtitlesIndexer
/src/main/java/status/mongodb/collections/SentenceDB.java
UTF-8
798
2.25
2
[]
no_license
package status.mongodb.collections; import org.bson.types.ObjectId; import status.mongodb.MongoSuperClass; public class SentenceDB extends MongoSuperClass { public static String COLLECTION_NAME = "Sentence"; public SentenceDB() { super(COLLECTION_NAME); } public SentenceDB(Object id) { super(COLLECTION_NAME); find(true, ID, new ObjectId(id.toString())); } public static String SENTENCE = "sentence"; public static String CAPTION_ID = "captionId"; public void setSentence(String sentence){ addField(SENTENCE, sentence); } public void setCaptionID(String captionID){ addField(CAPTION_ID, captionID); } public String getSentence(){ return getField(SENTENCE).toString(); } public String getCaptionID(){ return getField(CAPTION_ID).toString(); } }
true
85cf930005040902aac99fddd7bd322e3a7a2955
Java
SaadHussain813/unknown-caller-reject
/app/src/main/java/com/namitservices/ucr/BootCompletedReceiver.java
UTF-8
633
2.109375
2
[]
no_license
package com.namitservices.ucr; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by neil on 07/12/2015. */ public class BootCompletedReceiver extends BroadcastReceiver { final static String TAG = "BootCompletedReceiver"; @Override public void onReceive(Context context,Intent intent){ try{ context.startService(new Intent(context,BackGroundService.class)); Log.i(TAG,"Starting Service ConnectivityListener"); }catch(Exception e){ Log.e(TAG,e.toString()); } } }
true
99b0c12a0d5f3fd0a0a15d0546c832cb2ecf28c5
Java
huanghai2000/androidToJS_wavToMp3
/wisdomclassroom/src/main/java/com/kingsun/teacherclasspro/callback/MyHandlerCallBack.java
UTF-8
140
1.75
2
[]
no_license
package com.kingsun.teacherclasspro.callback; public interface MyHandlerCallBack { abstract void handleMessage(android.os.Message msg); }
true
451987f06a04841d3033f8a45da5d6e9113adb86
Java
DisruptionTheory/Eggscraper
/src/com/disruptiontheory/eggfetcher/QueryData.java
UTF-8
1,106
2.265625
2
[]
no_license
package com.disruptiontheory.eggfetcher; import org.json.simple.*; public class QueryData { @SuppressWarnings("unchecked") public static String NeweggQueryData(int brand, int page, int category, int subcat) { JSONObject obj = new JSONObject(); obj.put("IsUPCCodeSearch", false); obj.put("isGuideAdvanceSearch", false); obj.put("StoreDepaId", 1); obj.put("CategoryId", category); obj.put("SubCategoryId", subcat); obj.put("NodeId", -1); obj.put("BrandId", brand); obj.put("NValue", ""); obj.put("Keyword", ""); obj.put("Sort", "FEATURED"); obj.put("PageNumber", page); if(subcat > -1) { obj.put("IsSubCategorySearch", true); } else { obj.put("IsSubCategorySearch", false); } return obj.toJSONString(); } public static String SlimData(int brand) { return QueryData.NeweggQueryData(brand, 0, -1, -1); } public static String SlimData(int brand, int page) { return QueryData.NeweggQueryData(brand, page, -1, -1); } public static String SlimData(int brand, int page, int catId) { return QueryData.NeweggQueryData(brand, page, catId, -1); } }
true
114d88d2df6f71ac4a560368cd3c8f31b47f4e90
Java
unit7-0/com-unit7
/study/TranslationMethods/trunk/src/com/unit7/study/translationmethods/labs/test/Test.java
UTF-8
921
2.890625
3
[]
no_license
/** * file: Test.java * date: 16 дек. 2013 г. * * author: Zajcev V. */ package com.unit7.study.translationmethods.labs.test; import com.unit7.study.translationmethods.rgz.var7.processors.Tree; public class Test { /** * @param args */ public static void main(String[] args) { Test app = new Test(); String expr = "00(1+2)*0((1+2)*0(1+2)*((0+1)*1(1+2))*)*((0+1+2)*1222((1+2)*01))*"; Tree.setTerms("012"); Tree tree = Tree.parseTree(expr); app.printLeftToRight(tree, "", ""); } public void printLeftToRight(Tree tree, String spaces, String parent) { for (Tree tr: tree.getChilds()) { printLeftToRight(tr, spaces + "\t", tree.getName()); } System.out.println(spaces + "name: " + tree.getName() + " parent: " + parent + " node: " + tree.getNode() + " stub: " + tree.isStub() + " monolith: " + tree.isMonolith() + " onlyOne: " + tree.isOnlyOne()); } }
true
19be630533e9fba8f75fb38b9cae26779e98ec16
Java
sreeprasad/topcoder
/Marketing.java
UTF-8
1,433
3.140625
3
[]
no_license
public class Marketing { public static int [][] table; public static int [] visited; public static int RED =1; public static int BLACK =0; public static void main(String[] args) { //String [] s={"1 4","2","3","0",""}; //String [] s={"1","2","0"}; //String [] s={"1","2","3","0","0 5","1"}; String [] s={"","","","","","","","","","", "","","","","","","","","","", "","","","","","","","","",""}; make_graph (s); System.out.println(find_components(s)); } public static int find_components(String []s){ int N = s.length; int result=0; for(int i=0;i<N;i++){ if(visited[i]==-1){ if(!dfs(i,BLACK,N)){ return -1; } result ++; } } return 1<<result; } public static boolean dfs (int vertex, int color,int N){ visited[vertex]= color; for (int i=0;i<N;i++){ if(vertex!=i){ if(table[i][vertex]==1 && visited[i]!=-1 && visited[i]==color) return false; if (table[i][vertex]==1 && visited[i]==-1 && !dfs(i,1-color,N)) return false; } } return true; } public static void make_graph(String []s){ int N = s.length; table = new int [N][N]; for(int i=0;i<N;i++){ char [] array = s[i].toCharArray(); for(int j=0;j<array.length;j++){ if(array[j]!=' '){ table[i][Integer.parseInt(""+array[j])] =1; table[Integer.parseInt(""+array[j])][i] =1; } } } visited = new int[N]; for(int i=0;i<N;i++){ visited[i]=-1; } } }
true
53ffaa5d9fa2c2551f4760b6131e6c771ef1ac10
Java
kuno2582/java
/ch04-operation/src/IfEx01.java
UHC
489
3.390625
3
[]
no_license
/* ǹ, 񱳹, б⹮ - ־ ๮ ٸ Ͽ ٸ ϴ  - if, switch if - ѹ ϳ Ǵ -> б - boolean (true/false) */ public class IfEx01 { public static void main(String[] args) { int n = 4; if(n>5){ System.out.println("n 5 ũ."); } System.out.println("α׷ "); } }
true
f798abfb4fcd8146c1276f1068703551de30b156
Java
Mrhelilin/aap02
/src/main/java/com/briup/app02/dao/SchoolMapper.java
UTF-8
434
2.109375
2
[]
no_license
package com.briup.app02.dao; import java.util.List; import com.briup.app02.bean.School; public interface SchoolMapper { // 查询所有课程信息 List<School> findAll(); // 通过id查询课程信息 School findById(long id); // 保存课程信息 void save(School school); // 修改课程信息 void update(School school); //删除课程信息 void deleteById(long id); }
true
649c6838606500dca1af59173334cc8e270cd4ac
Java
ArunDrioder/RecyclerAddImages
/app/src/main/java/com/example/recycleraddimages/ImageRecyclerViewAdapter.java
UTF-8
1,904
2.40625
2
[]
no_license
package com.example.recycleraddimages; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.Glide; import java.io.File; import java.util.ArrayList; import java.util.List; public class ImageRecyclerViewAdapter extends RecyclerView.Adapter<ImageRecyclerViewAdapter.MyViewHolder> { private Context mContext; private List<String> picturesList; public ImageRecyclerViewAdapter(ArrayList<String> picturesList, Context context) { this.mContext = context; this.picturesList = picturesList; notifyDataSetChanged(); } @NonNull @Override public ImageRecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_adapter, parent,false); return new ImageRecyclerViewAdapter.MyViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull final ImageRecyclerViewAdapter.MyViewHolder holder, int position) { try { File file = new File(picturesList.get(position)); Glide.with(mContext).load(file).into(holder.picture); } catch (Exception e) { Log.i(ImageRecyclerViewAdapter.class.getSimpleName(),"Exception : "+e ); } } @Override public int getItemCount() { return picturesList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { private ImageView picture; public MyViewHolder(@NonNull View itemView) { super(itemView); picture = itemView.findViewById(R.id.picture); } } }
true
45923f57a69e38905e2fb32d93088c20e391d072
Java
xiusan/xiao
/src/main/java/com/xjl/partten/dataalgorithm/Base/ArrayCase/Test.java
UTF-8
326
2.203125
2
[]
no_license
package com.xjl.partten.dataalgorithm.Base.ArrayCase; /** * @Auther: [email protected] * @Date: 2020/7/31 21:40 * @Description: */ public class Test { public static void main(String[] args) { int[] ai = new int[4]; ai[0]=2147483647; System.out.println(ai.length); System.out.println(); } }
true
33ebbdd8ba11ada8452817fdcf7b84a842e567c8
Java
freelanceandroidstudios/NFL-2015-Schedule-Prediction
/src/com/football2015schedulematchups/app/ShareFragment.java
UTF-8
9,176
2.140625
2
[]
no_license
/** * */ package com.football2015schedulematchups.app; import java.util.Locale; import com.football2015schedulematchups.app.NavigationDrawerFragment.NavigationDrawerCallbacks; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; /** * @author Scott Auman * */ public class ShareFragment extends Fragment { private LinearLayout layout, homeLayout, visitorLayout; private TextView finalRecord, teamName, changeInWins, lastYearsRecord; View view; private ScrollView scrollViewlayout; private ImageView differenceImageView; SaveScreenshot saveScreenshot; TeamResults teamResults; ChangeType changeType; int team_pos; private Button shareButton; enum ChangeType { WINS, LOSSES, SAME } public enum GameType { HOME, AWAY } /** * */ public ShareFragment() { // TODO Auto-generated constructor stub } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.share_view, null, true); assignViewElements(); buildHomeGames(); buildVisitorGames(); getFinalRecord().setText(teamResults.getFinalRecord()); getTeamName().setText(teamResults.getTeamName()); getChangeInWins().setText(determineChangeInRecord()); getDifferenceImageView().setImageDrawable( getActivity().getResources().getDrawable(determineImageType())); getLastYearsRecord().setText( "2014 Record: " + teamResults.getLastYears()); setButtonClicker(); new Fonts().setFontHugMeTight(getTeamName()); new Fonts().setFontRobotoBlackItalics(getLastYearsRecord()); new Fonts().setPointsFont(getFinalRecord()); new Fonts().setPointsFont(getChangeInWins()); return view; } private Integer determineImageType() { switch (changeType) { case WINS: return R.drawable.green_arrow; case LOSSES: return R.drawable.red_arrow; case SAME: return R.drawable.equal_icon; default: return null; } } private String determineChangeInRecord() { String[] s = teamResults.getFinalRecord().split("-"); int winsF = Integer.parseInt(s[0]); int lossesF = Integer.parseInt(s[1]); int tieF; try { // see if there is a tie game!!! tieF = Integer.parseInt(s[2]); } catch (Exception ex) { ex.printStackTrace(); } String[] last = teamResults.getLastYears().split("-"); int winsL = Integer.parseInt(last[0]); int lossesL = Integer.parseInt(last[1]); int tieL = 0; try { // see if there is a tie game!!! tieL = Integer.parseInt(s[2]); } catch (Exception ex) { ex.printStackTrace(); } // find out which is changed! if (winsF > winsL) { // find diff changeType = ChangeType.WINS; if (tieL > 0) { return (((winsF - winsL) - (tieL * .5) + "")); } return (winsF - winsL + ""); } else if (winsL == winsF) { // same record changeType = ChangeType.SAME; return "No Change"; } else { // more losses changeType = ChangeType.LOSSES; // find diff if (tieL > 0) { return (((double) (lossesF - lossesL) - (double) (tieL * .50) + "")); } return (lossesF - lossesL + ""); } } /** * */ private void setButtonClicker() { getShareButton().setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // remove view so its not in the screenshot getShareButton().setVisibility(View.INVISIBLE); saveScreenshot.saveBitmap(takeScreenshot()); shareToApp(); getShareButton().setVisibility(View.VISIBLE); getActivity().getSupportFragmentManager().popBackStack(); } }); } /** * */ private void buildVisitorGames() { for (int i = 0; i < 8; i++) { getVisitorLayout() .addView( new ShareTableRow(getActivity(), teamResults .getVisitorResults().get(i).getName(), teamResults.getVisitorResults().get(i) .isWin(), GameType.AWAY), getVisitorLayout().getChildCount()); } } /** * */ private void buildHomeGames() { for (int i = 0; i < 8; i++) { getHomeLayout().addView( new ShareTableRow(getActivity(), teamResults .getHomeResults().get(i).getName(), teamResults .getHomeResults().get(i).isWin(), GameType.HOME), getHomeLayout().getChildCount()); } } /** * */ private void assignViewElements() { setHomeLayout((LinearLayout) view.findViewById(R.id.homeLayout)); setVisitorLayout((LinearLayout) view.findViewById(R.id.visitorLayout)); setFinalRecord((TextView) view.findViewById(R.id.finalRecordTextView)); setTeamName((TextView) view.findViewById(R.id.team_name_share_textview)); setLayout((LinearLayout) view.findViewById(R.id.shareLayout)); setChangeInWins((TextView) view.findViewById(R.id.winsChangeTextView)); setDifferenceImageView((ImageView) view .findViewById(R.id.changeIamgeView)); setShareButton((Button) view.findViewById(R.id.sharebutton)); setLastYearsRecord((TextView) view .findViewById(R.id.lastYearsRecordTextView)); setScrollViewlayout((ScrollView) view .findViewById(R.id.shareViewScrollView)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); saveScreenshot = new SaveScreenshot(getActivity()); teamResults = new TeamResults(); teamResults = getArguments().getParcelable(Keys.RESULTS); team_pos = getArguments().getInt(Keys.TEAM_POS); } public Bitmap takeScreenshot() { view.setDrawingCacheEnabled(true); return view.getDrawingCache(); } public void shareToApp() { String text = "https://play.google.com/store/apps/details?" + "id=com.football2015schedulematchups.app"; Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, text); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(saveScreenshot.getUriImage())); shareIntent.setType("image/*"); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(shareIntent, "Share " + teamResults.getTeamName() + " Record With...")); } /** * @return the layout */ public LinearLayout getLayout() { return layout; } /** * @return the homeLayout */ public LinearLayout getHomeLayout() { return homeLayout; } /** * @return the visitorLayout */ public LinearLayout getVisitorLayout() { return visitorLayout; } /** * @param layout * the layout to set */ public void setLayout(LinearLayout layout) { this.layout = layout; } /** * @param homeLayout * the homeLayout to set */ public void setHomeLayout(LinearLayout homeLayout) { this.homeLayout = homeLayout; } /** * @param visitorLayout * the visitorLayout to set */ public void setVisitorLayout(LinearLayout visitorLayout) { this.visitorLayout = visitorLayout; } /** * @return the finalRecord */ public TextView getFinalRecord() { return finalRecord; } /** * @param finalRecord * the finalRecord to set */ public void setFinalRecord(TextView finalRecord) { this.finalRecord = finalRecord; } /** * @return the teamName */ public TextView getTeamName() { return teamName; } /** * @param teamName * the teamName to set */ public void setTeamName(TextView teamName) { this.teamName = teamName; } /** * @return the shareButton */ public Button getShareButton() { return shareButton; } /** * @param shareButton * the shareButton to set */ public void setShareButton(Button shareButton) { this.shareButton = shareButton; } /** * @return the changeInWins */ public TextView getChangeInWins() { return changeInWins; } /** * @param changeInWins * the changeInWins to set */ public void setChangeInWins(TextView changeInWins) { this.changeInWins = changeInWins; } /** * @return the differenceImageView */ public ImageView getDifferenceImageView() { return differenceImageView; } /** * @param differenceImageView * the differenceImageView to set */ public void setDifferenceImageView(ImageView differenceImageView) { this.differenceImageView = differenceImageView; } /** * @return the lastYearsRecord */ public TextView getLastYearsRecord() { return lastYearsRecord; } /** * @param lastYearsRecord * the lastYearsRecord to set */ public void setLastYearsRecord(TextView lastYearsRecord) { this.lastYearsRecord = lastYearsRecord; } /** * @return the scrollViewlayout */ public ScrollView getScrollViewlayout() { return scrollViewlayout; } /** * @param scrollViewlayout * the scrollViewlayout to set */ public void setScrollViewlayout(ScrollView scrollViewlayout) { this.scrollViewlayout = scrollViewlayout; } }
true
28f5947ecf8e066a19be8fb82ebc0a4def669056
Java
caoguobin-git/JavaBase01
/java-programming/src/main/java/com/programming/chapter9/exercise/Exercise9_3.java
UTF-8
886
2.96875
3
[]
no_license
/*********************************************** * File Name: Exercise9_3 * Author: caoguobin * mail: [email protected] * Created Time: 21 06 2019 9:35 ***********************************************/ package com.programming.chapter9.exercise; import java.util.Date; public class Exercise9_3 { public static void main(String[] args) { Date date=new Date(1000); System.out.println(date.toString()); date.setTime(10000); System.out.println(date.toString()); date.setTime(100000); System.out.println(date.toString()); date.setTime(1000000); System.out.println(date.toString()); date.setTime(10000000); System.out.println(date.toString()); date.setTime(100000000); System.out.println(date.toString()); date.setTime(100000000000L); System.out.println(date.toString()); } }
true
85f24dd7c16313a53021c868d4649bd34912bc02
Java
armpatch/VideoJournal
/app/src/main/java/com/armpatch/android/videojournal/data/local/DatabaseSchema.java
UTF-8
645
2.09375
2
[]
no_license
package com.armpatch.android.videojournal.data.local; public class DatabaseSchema { public static final class RecordingTable { public static final String NAME = "recordings"; public static final class Cols { public static final String RECORDING_UUID = "recording_id"; public static final String RECORDING_TITLE = "recording_title"; public static final String DATE = "date"; public static final String NOTES = "notes"; public static final String VIDEO_PATH = "video_path"; public static final String THUMBNAIL_PATH = "thumbnail_path"; } } }
true
bf82e806ea1cfc78152534348fd734763fa16983
Java
StarBlossom99/PPS_Camp_Week2
/tweleve_six_HanSeongHWa_20210715.java
UTF-8
560
2.828125
3
[]
no_license
import java.util.Scanner; import java.math.BigInteger; public class tweleve_six_HanSeongHWa_20210715 { public static void main(String[] args) { Scanner kb = new Scanner(System.in); int num = 0; num = kb.nextInt(); BigInteger a1 = new BigInteger("1"); BigInteger a2 = new BigInteger("1"); BigInteger a3 = new BigInteger("2"); if(num<3) { System.out.println(a1); } else { for(int i = 0;i<num-2;i++) { a3 = a1.add(a2); a1 = a2; a2 = a3; } System.out.println(a3); } kb.close(); } }
true
60de92072ec4d59986f3268abb89789492d807d4
Java
RRoggia/helsinki-programming-with-java
/src/test/java/com/rroggia/oo/java/part1/exercise/week3/Exercise62Test.java
UTF-8
1,662
3.375
3
[]
no_license
package com.rroggia.oo.java.part1.exercise.week3; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import org.junit.Test; import com.rroggia.oo.java.part1.exercise.week3.Exercise62; public class Exercise62Test { @Test public void removeLast() { ArrayList<String> brothers = new ArrayList<String>(); brothers.add("Dick"); brothers.add("Henry"); brothers.add("Michael"); brothers.add("Bob"); int expectedSizeAfterRemoveLast = brothers.size() - 1; testImplementationOfRemoveLast(Exercise62.class, expectedSizeAfterRemoveLast, brothers); } public static void testImplementationOfRemoveLast(Class<?> implementationClass, int expectedResult, ArrayList<String> list) { try { Method instanceMethod = implementationClass.getMethod("removeLast", ArrayList.class); instanceMethod.invoke(null, list); assertEquals("The list has the same size. Did you forgot to remove ?", expectedResult, list.size()); assertFalse("The list still contain the last element, Did you removed the last one?", list.contains("Bob")); } catch (NoSuchMethodException e) { fail("Create the method removeLast, which removes the last item from the list."); } catch (ClassCastException | NullPointerException | IllegalAccessException | IllegalArgumentException e) { fail("Your method must follow: public static void removeLast(ArrayList<String> list)"); } catch (InvocationTargetException e) { fail(e.getTargetException().getMessage()); } } }
true
295a57296a37b4ce5b03cee5886b45d984eb2b6c
Java
thevpc/nuts
/core/nuts/src/main/java/net/thevpc/nuts/NWorkspaceStoredConfig.java
UTF-8
2,429
1.78125
2
[ "Apache-2.0" ]
permissive
/** * ==================================================================== * Nuts : Network Updatable Things Service * (universal package manager) * <br> * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for * maven (and other build managers) as it helps installing all package * dependencies at runtime. Nuts is not tied to java and is a good choice * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. * * <br> * <p> * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. * <br> * ==================================================================== */ package net.thevpc.nuts; import net.thevpc.nuts.env.NOsFamily; import java.util.Map; /** * Nuts read-only configuration * * @author thevpc * @app.category Config * @since 0.5.4 */ public interface NWorkspaceStoredConfig { String getName(); NStoreStrategy getStoreStrategy(); NStoreStrategy getRepositoryStoreStrategy(); NOsFamily getStoreLayout(); /** * all home locations key/value map where keys are in the form "location" * and values are absolute paths. * * @return home locations mapping */ Map<NStoreType, String> getStoreLocations(); /** * all home locations key/value map where keys are in the form * "osfamily:location" and values are absolute paths. * * @return home locations mapping */ Map<NHomeLocation, String> getHomeLocations(); String getStoreLocation(NStoreType folderType); String getHomeLocation(NHomeLocation homeLocation); NId getApiId(); NId getRuntimeId(); String getRuntimeDependencies(); String getBootRepositories(); String getJavaCommand(); String getJavaOptions(); boolean isSystem(); }
true
2adb70d412e128d1e2572aaa20d5a15d89b3d274
Java
saisnehad/HelloWorld
/src/com/mul/Mul.java
UTF-8
463
3.46875
3
[]
no_license
package com.mul; import java.util.Scanner; public class Mul { public static void main(String[] args) { int x = 0, y = 0; int w; System.out.println("enter x value: "); Scanner sc = new Scanner(System.in); x = sc.nextInt(); System.out.println(" x value: " + x); System.out.println("enter y value: "); y = sc.nextInt(); System.out.println("enter y value: " + y); w = x * y; sc.close(); System.out.println("output for mul: " + w); } }
true
5239fdce61c4051c2a2d72220708b29480c6ea78
Java
eschild314/Kettle2theMettle
/ultimate_goal_autonomous/Red.java
UTF-8
10,508
2.140625
2
[]
no_license
package org.firstinspires.ftc.teamcode.ultimate_goal_autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.hardware.Servo; import java.lang.annotation.Target; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector; import org.firstinspires.ftc.robotcore.external.tfod.Recognition; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import java.util.ArrayList; import java.util.List; @Autonomous(group ="ultimateGoal") public class Red extends LinearOpMode { // Servos Servo tilt0; Servo arm0; Servo claw0; // Power for motors while moving double flPower; double frPower; double blPower; double brPower; int footTime; int rotTime; // Drive motors private DcMotor BackRight; private DcMotor FrontRight; private DcMotor FrontLeft; private DcMotor BackLeft; // Vuforia setup private static final String TFOD_MODEL_ASSET = "UltimateGoal.tflite"; private static final String LABEL_FIRST_ELEMENT = "Quad"; private static final String LABEL_SECOND_ELEMENT = "Single"; private static final String VUFORIA_KEY = "KEY"; private VuforiaLocalizer vuforia; private TFObjectDetector tfod; int ringNum; @Override public void runOpMode() { frPower = 0.5; //0.6 (last year's values are commented out) flPower = 0.5; //0.5 brPower = 0.555; //0.5 blPower = 0.555; //0.52 footTime = 650; //385: changed to 650 in 2021 for 18 inches per instruction rotTime = 410; //356: changed to 410 for 2021 90-degree rotation // Initialize motors and servos tilt0 = hardwareMap.servo.get("tilt0"); arm0 = hardwareMap.servo.get("arm0"); claw0 = hardwareMap.servo.get("claw0"); tilt0.setPosition(0.5); arm0.setPosition(0); claw0.setPosition(1); FrontRight = hardwareMap.dcMotor.get("FrontRight"); FrontLeft = hardwareMap.dcMotor.get("FrontLeft"); BackLeft = hardwareMap.dcMotor.get("BackLeft"); BackRight = hardwareMap.dcMotor.get("BackRight"); FrontRight.setDirection(DcMotorSimple.Direction.REVERSE); BackLeft.setDirection(DcMotorSimple.Direction.FORWARD); BackRight.setDirection(DcMotorSimple.Direction.REVERSE); initVuforia(); initTfod(); ringNum = 0; if (tfod != null) { tfod.activate(); //tfod.setZoom(2.5, 1.78); } telemetry.addData(">", "Everything is initialized."); telemetry.update(); waitForStart(); move_left(); detectRings(); stop2(); telemetry.addData("ringNum", ringNum); telemetry.update(); move(); } private void move() { for(int i=0; i<7; i++) { move_left(); } tilt_left(); stop2(); tilt_reset(); brPower = 0.53; blPower = 0.53; if (ringNum == 0) { move_right(); move_right(); stop2(); rot_counterclock(); stop2(); rot_counterclock(); stop2(); arm_up(); claw_open(); stop2(); arm_reset(); claw_close(); move_right(); } else if (ringNum == 1) { move_right(); arm_up(); claw_open(); stop2(); arm_reset(); claw_close(); move_right(); move_right(); } else if (ringNum == 4) { move_right(); // move back to prevent rotating into the wall rot_counterclock(); stop2(); rot_counterclock(); stop2(); brPower = 0.555; blPower = 0.555; move_left(); brPower = 0.53; blPower = 0.53; arm_up(); claw_open(); stop2(); arm_reset(); claw_close(); move_right(); move_right(); move_right(); } } private void detectRings() { if (tfod != null) { // getUpdatedRecognitions() will return null if no new information is available since // the last time that call was made. List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); if (updatedRecognitions != null) { int i = 0; for (Recognition recognition : updatedRecognitions) { //telemetry.addData(String.format("label (%d)", i), recognition.getLabel()); if (recognition.getLabel().equals("Quad")) { ringNum = 4; } else if (recognition.getLabel().equals("Single")) { ringNum = 1; } else { ringNum = 0; } } } tfod.shutdown(); } } private void arm_reset() { arm0.setPosition(0); } private void arm_down() { arm0.setPosition(0.89); } private void arm_up() { arm0.setPosition(0.6); } private void claw_open() { claw0.setPosition(0.75); } private void claw_close() { claw0.setPosition(1); } private void tilt_right() { tilt0.setPosition(0.7); } private void tilt_left() { tilt0.setPosition(0.3); } private void tilt_reset() { tilt0.setPosition(0.5); } private void move_forward() { FrontRight.setDirection(DcMotorSimple.Direction.REVERSE); FrontLeft.setDirection(DcMotorSimple.Direction.FORWARD); BackLeft.setDirection(DcMotorSimple.Direction.FORWARD); BackRight.setDirection(DcMotorSimple.Direction.REVERSE); FrontRight.setPower(frPower); FrontLeft.setPower(flPower); BackLeft.setPower(blPower); BackRight.setPower(brPower); sleep(footTime); } private void move_backward() { FrontRight.setDirection(DcMotorSimple.Direction.FORWARD); FrontLeft.setDirection(DcMotorSimple.Direction.REVERSE); BackLeft.setDirection(DcMotorSimple.Direction.REVERSE); BackRight.setDirection(DcMotorSimple.Direction.FORWARD); FrontRight.setPower(frPower); FrontLeft.setPower(flPower); BackLeft.setPower(blPower); BackRight.setPower(brPower); sleep(footTime); } private void move_left() { FrontRight.setDirection(DcMotorSimple.Direction.REVERSE); FrontLeft.setDirection(DcMotorSimple.Direction.REVERSE); BackLeft.setDirection(DcMotorSimple.Direction.FORWARD); BackRight.setDirection(DcMotorSimple.Direction.FORWARD); FrontRight.setPower(frPower); FrontLeft.setPower(flPower); BackLeft.setPower(blPower); BackRight.setPower(brPower); sleep(footTime); } private void move_right() { FrontRight.setDirection(DcMotorSimple.Direction.FORWARD); FrontLeft.setDirection(DcMotorSimple.Direction.FORWARD); BackLeft.setDirection(DcMotorSimple.Direction.REVERSE); BackRight.setDirection(DcMotorSimple.Direction.REVERSE); FrontRight.setPower(frPower); FrontLeft.setPower(flPower); BackLeft.setPower(blPower); BackRight.setPower(brPower); sleep(footTime); } private void stop2() { FrontRight.setPower(0); FrontLeft.setPower(0); BackLeft.setPower(0); BackRight.setPower(0); sleep(footTime); } private void rot_clock() { FrontLeft.setDirection(DcMotorSimple.Direction.FORWARD); BackRight.setDirection(DcMotorSimple.Direction.FORWARD); BackLeft.setDirection(DcMotorSimple.Direction.FORWARD); FrontRight.setDirection(DcMotorSimple.Direction.FORWARD); FrontRight.setPower(frPower); FrontLeft.setPower(flPower); BackLeft.setPower(blPower); BackRight.setPower(brPower); sleep(rotTime); } private void rot_counterclock() { FrontLeft.setDirection(DcMotorSimple.Direction.REVERSE); BackRight.setDirection(DcMotorSimple.Direction.REVERSE); BackLeft.setDirection(DcMotorSimple.Direction.REVERSE); FrontRight.setDirection(DcMotorSimple.Direction.REVERSE); FrontRight.setPower(0.69); FrontLeft.setPower(0.69); BackLeft.setPower(0.6); BackRight.setPower(0.6); sleep(rotTime); } /** * Initialize the Vuforia localization engine. */ private void initVuforia() { /* * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine. */ VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); parameters.vuforiaLicenseKey = VUFORIA_KEY; parameters.cameraName = hardwareMap.get(WebcamName.class, "Megapixel Webcam"); // Instantiate the Vuforia engine vuforia = ClassFactory.getInstance().createVuforia(parameters); } /** * Initialize the TensorFlow Object Detection engine. */ private void initTfod() { int tfodMonitorViewId = hardwareMap.appContext.getResources().getIdentifier( "tfodMonitorViewId", "id", hardwareMap.appContext.getPackageName()); TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId); tfodParameters.minResultConfidence = 0.8f; tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia); tfod.loadModelFromAsset(TFOD_MODEL_ASSET, LABEL_FIRST_ELEMENT, LABEL_SECOND_ELEMENT); } }
true
c3fe20f66dadc5af5ca096b128e42aaf5eb2a57e
Java
eric-pham/shapes
/phase1/Game/app/src/main/java/com/group0578/hpgame/view/CreateUser.java
UTF-8
569
2.3125
2
[]
no_license
package com.group0578.hpgame.view; import com.group0578.hpgame.model.SQLiteHelper; /** * Methods responsible for communication between CreateUserPresenter and CreateUserActivity */ public interface CreateUser { /** * Methods implemented by CreateUserActivity */ interface View { } // Haven't decided if we need this yet interface Model { } /** * Methods implemented by CreateUserPresenter */ interface Presenter { void createAccount(SQLiteHelper sqlHelper, String username, String password); } }
true
1eb6bb952bc1b48138c29a6cdb212e698158bcca
Java
sjs2774/HelloMarket
/src/User/UserDAO.java
UTF-8
8,528
2.375
2
[]
no_license
package User; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.websocket.Session; public class UserDAO { public UserDAO() { } public int login(String user_email,String user_pwd) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String pass =null; String sql = "SELECT MD5(?)"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user_pwd); rs = pstmt.executeQuery(); if(rs.next()) { pass = rs.getString(1); } }catch(Exception e) { e.printStackTrace(); } System.out.println(pass); sql = "SELECT user_pwd FROM userlist WHERE user_email=?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user_email); rs = pstmt.executeQuery(); if(rs.next()) { if(rs.getString("user_pwd").equals(pass)) { return 1; } else return 0; } return -1; }catch(Exception e) { e.printStackTrace(); } return -2; } public UserDTO profile(String userId) { UserDTO userDTO = new UserDTO(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT user_prof,seller_level,user_ph from userlist where user_email = ?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, userId); rs = pstmt.executeQuery(); while(rs.next()) { userDTO.setUserProf(rs.getString("user_prof")); userDTO.setSellerLevel(rs.getInt("seller_level")); userDTO.setUserPh(rs.getInt("user_ph")); } }catch(Exception e) { e.printStackTrace(); } return userDTO; } public void changeProfile(String userId,String changeProf) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "UPDATE userlist set user_prof =? where user_email =?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, changeProf); pstmt.setString(2, userId); pstmt.executeUpdate(); }catch(Exception e) { e.printStackTrace(); } } public void changePic(String userNick) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "UPDATE userlist set user_pic=? where user_nick =?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, userNick); pstmt.executeUpdate(); }catch(Exception e) { e.printStackTrace(); } } public void changePhone(String userId,int changePhone) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "UPDATE userlist set user_ph =? where user_email =?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, changePhone); pstmt.setString(2, userId); pstmt.executeUpdate(); }catch(Exception e) { e.printStackTrace(); } } public String selectUserNick(String user_email) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String userNick; String sql = "SELECT user_nick FROM userlist WHERE user_email=?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user_email); rs = pstmt.executeQuery(); if(rs.next()) { userNick = rs.getString(1); return userNick; } }catch(Exception e) { e.printStackTrace(); } return "no"; } public int join(UserDTO user) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; UserDAO setUser_nick = new UserDAO(); String sql = "INSERT INTO userlist(user_email,user_pwd,user_nick) values(?,MD5(?),?)"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUserId()); pstmt.setString(2, user.getUserPass()); pstmt.setString(3, "default"); pstmt.executeUpdate(); setUser_nick.set_userNick(user); return 0; } catch(Exception e) { e.printStackTrace(); } return -1; } public void set_userNick(UserDTO user) { int user_idx = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String user_nick = ""; String sql = "select user_idx from userlist where user_email=?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUserId()); rs = pstmt.executeQuery(); while(rs.next()) { user_idx = rs.getInt(1); user_nick = "n"+100000+user_idx; user.setUserNick(user_nick); user.setUserIdx(user_idx); } }catch(Exception e) { e.printStackTrace(); } sql ="update userlist set user_nick=? where user_idx=?"; try { conn= Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUserNick()); pstmt.setInt(2, user.getUserIdx()); pstmt.executeUpdate(); }catch(Exception e) { e.printStackTrace(); } } public void changeUserNick(String userId,String changeNick) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "UPDATE userlist set user_nick = ? where user_email=?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, changeNick); pstmt.setString(2, userId); pstmt.executeUpdate(); }catch(Exception e) { e.printStackTrace(); } } public int user_coupon(String userId) { int couponIdx=0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "Select coupon_idx from userlist where user_email = ?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, userId); rs = pstmt.executeQuery(); while(rs.next()) { couponIdx = rs.getInt("coupon_idx"); } }catch(Exception e) { e.printStackTrace(); } return couponIdx; } public int getUser_level(String userNick) { int userLevel = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "Select seller_level from userlist where user_nick = ?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, userNick); rs = pstmt.executeQuery(); if(rs.next()) { userLevel = rs.getInt(1); } }catch(Exception e) { e.printStackTrace(); } return userLevel; } public int getUserIdx(String userNick) { int user_idx = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select user_idx from userlist where user_nick=?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, userNick); rs = pstmt.executeQuery(); while(rs.next()) { user_idx = rs.getInt(1); } }catch(Exception e) { e.printStackTrace(); } return user_idx; } public UserDTO getUserInfo(int userIdx) { UserDTO userDTO = new UserDTO(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select user_nick,user_prof,seller_star,seller_level,user_following,user_follower from userlist where user_idx=?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userIdx); rs = pstmt.executeQuery(); while(rs.next()) { userDTO.setUserNick(rs.getString("user_nick")); userDTO.setUserProf(rs.getString("user_prof")); userDTO.setSellerStar(rs.getInt("seller_star")); userDTO.setSellerLevel(rs.getInt("seller_level")); userDTO.setUserFollowing(rs.getInt("user_following")); userDTO.setUserFollower(rs.getInt("user_follower")); } }catch(Exception e) { e.printStackTrace(); } return userDTO; } public int deleteUser(String user) { int rows = 0; Connection conn = null; PreparedStatement pstmt = null; String sql = "DELETE FROM userlist WHERE user_email=?"; try { conn = Dbconn.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user); rows = pstmt.executeUpdate(); if (rows != 0) { System.out.println("성공"); return 1; // 성공 }else { System.out.println("실패"); } }catch(Exception e) { e.printStackTrace(); }finally { Dbconn.close(conn, pstmt); } return -2; } }
true
ea4e1b5a53056aca9df43ad26346d77db8936909
Java
semmiverian/androidSkripsi
/app/src/main/java/com/skripsi/semmi/restget3/Interface/DeleteProdukInterface.java
UTF-8
436
1.953125
2
[]
no_license
package com.skripsi.semmi.restget3.Interface; import com.skripsi.semmi.restget3.Model.DeleteData; import retrofit.Callback; import retrofit.http.Multipart; import retrofit.http.POST; import retrofit.http.Part; /** * Created by semmi on 17/12/2015. */ public interface DeleteProdukInterface { @Multipart @POST("/deleteProduk.php") void deleteProduk(@Part("produkId") String produkId , Callback<DeleteData> callback); }
true
ab491a599428687075eba6129511f2ec77b1cce9
Java
wso2/wso2-rampart
/modules/rampart-core/src/main/java/org/apache/rampart/policy/RampartPolicyBuilder.java
UTF-8
15,263
1.75
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rampart.policy; import org.apache.axis2.policy.model.MTOMAssertion; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.neethi.Assertion; import org.apache.rampart.policy.model.RampartConfig; import org.apache.ws.secpolicy.WSSPolicyException; import org.apache.ws.secpolicy.model.AsymmetricBinding; import org.apache.ws.secpolicy.model.Binding; import org.apache.ws.secpolicy.model.ContentEncryptedElements; import org.apache.ws.secpolicy.model.EncryptionToken; import org.apache.ws.secpolicy.model.Header; import org.apache.ws.secpolicy.model.InitiatorToken; import org.apache.ws.secpolicy.model.ProtectionToken; import org.apache.ws.secpolicy.model.RecipientToken; import org.apache.ws.secpolicy.model.RequiredElements; import org.apache.ws.secpolicy.model.SignatureToken; import org.apache.ws.secpolicy.model.SignedEncryptedElements; import org.apache.ws.secpolicy.model.SignedEncryptedParts; import org.apache.ws.secpolicy.model.SupportingToken; import org.apache.ws.secpolicy.model.SymmetricAsymmetricBindingBase; import org.apache.ws.secpolicy.model.SymmetricBinding; import org.apache.ws.secpolicy.model.TokenWrapper; import org.apache.ws.secpolicy.model.TransportBinding; import org.apache.ws.secpolicy.model.TransportToken; import org.apache.ws.secpolicy.model.Trust10; import org.apache.ws.secpolicy.model.Wss10; import org.apache.ws.secpolicy.model.Wss11; import java.util.Iterator; import java.util.List; public class RampartPolicyBuilder { private static final Log log = LogFactory.getLog(RampartPolicyBuilder.class); /** * Compile the parsed security data into one Policy data block. * * This methods loops over all top level Policy Engine data elements, * extracts the parsed parameters and sets them into a single data block. * During this processing the method prepares the parameters in a format * that is ready for processing by the WSS4J functions. * * <p/> * * The WSS4J policy enabled handler takes this data block to control the * setup of the security header. * * @param topLevelAssertions * The iterator of the top level policy assertions * @return The compile Poilcy data block. * @throws WSSPolicyException */ public static RampartPolicyData build(List topLevelAssertions) throws WSSPolicyException { RampartPolicyData rpd = new RampartPolicyData(); for (Iterator iter = topLevelAssertions.iterator(); iter.hasNext();) { Assertion assertion = (Assertion) iter.next(); if (assertion instanceof Binding) { setWebServiceSecurityPolicyNS(assertion, rpd); if (assertion instanceof SymmetricBinding) { processSymmetricPolicyBinding((SymmetricBinding) assertion, rpd); } else if(assertion instanceof AsymmetricBinding) { processAsymmetricPolicyBinding((AsymmetricBinding) assertion, rpd); } else { processTransportBinding((TransportBinding) assertion, rpd); } /* * Don't change the order of Wss11 / Wss10 instance checks * because Wss11 extends Wss10 - thus first check Wss11. */ } else if (assertion instanceof Wss11) { processWSS11((Wss11) assertion, rpd); } else if (assertion instanceof Wss10) { processWSS10((Wss10) assertion, rpd); } else if (assertion instanceof SignedEncryptedElements) { processSignedEncryptedElements((SignedEncryptedElements) assertion, rpd); } else if (assertion instanceof SignedEncryptedParts) { processSignedEncryptedParts((SignedEncryptedParts) assertion, rpd); } else if ( assertion instanceof RequiredElements) { processRequiredElements((RequiredElements)assertion, rpd); } else if (assertion instanceof ContentEncryptedElements) { processContentEncryptedElements((ContentEncryptedElements) assertion, rpd); }else if (assertion instanceof SupportingToken) { //Set policy version. Cos a supporting token can appear along without a binding setWebServiceSecurityPolicyNS(assertion, rpd); processSupportingTokens((SupportingToken) assertion, rpd); } else if (assertion instanceof Trust10) { processTrust10((Trust10)assertion, rpd); } else if (assertion instanceof RampartConfig) { processRampartConfig((RampartConfig)assertion, rpd); } else if (assertion instanceof MTOMAssertion){ processMTOMSerialization((MTOMAssertion)assertion, rpd); } else { if (log.isDebugEnabled()) { log.debug("Unknown top level PED found: " + assertion.getClass().getName()); } } } return rpd; } /** * Sets web service security policy version. The policy version is extracted from an assertion. * But if namespace is already set this method will just return. * @param assertion The assertion to get policy namespace. */ private static void setWebServiceSecurityPolicyNS(Assertion assertion, RampartPolicyData policyData) { if (policyData.getWebServiceSecurityPolicyNS() == null) { policyData.setWebServiceSecurityPolicyNS(assertion.getName().getNamespaceURI()); } } /** * @param binding * @param rpd */ private static void processTransportBinding(TransportBinding binding, RampartPolicyData rpd) { binding(binding, rpd); rpd.setTransportBinding(true); rpd.setTokenProtection(binding.isTokenProtection()); TransportToken transportToken = binding.getTransportToken(); if ( transportToken != null ) { rpd.setTransportToken(transportToken.getTransportToken()); } } /** * Add TRust10 assertion info into rampart policy data * @param trust10 * @param rpd */ private static void processTrust10(Trust10 trust10, RampartPolicyData rpd) { rpd.setTrust10(trust10); } /** * Add the rampart configuration information into rampart policy data. * @param config * @param rpd */ private static void processRampartConfig(RampartConfig config, RampartPolicyData rpd) { rpd.setRampartConfig(config); } /** * Evaluate the symmetric policy binding data. * * @param symmBinding * The binding data * @param rpd * The WSS4J data to initialize * @throws WSSPolicyException */ private static void processSymmetricPolicyBinding( SymmetricBinding symmBinding, RampartPolicyData rpd) throws WSSPolicyException { rpd.setSymmetricBinding(true); binding(symmBinding, rpd); symmAsymmBinding(symmBinding, rpd); symmetricBinding(symmBinding, rpd); } private static void processWSS10(Wss10 wss10, RampartPolicyData rpd) { rpd.setWss10(wss10); } /** * Evaluate the asymmetric policy binding data. * * @param binding * The binding data * @param rpd * The WSS4J data to initialize * @throws WSSPolicyException */ private static void processAsymmetricPolicyBinding( AsymmetricBinding binding, RampartPolicyData rpd) throws WSSPolicyException { rpd.setAsymmetricBinding(true); binding(binding, rpd); symmAsymmBinding(binding, rpd); asymmetricBinding(binding, rpd); } private static void processWSS11(Wss11 wss11, RampartPolicyData rpd) { rpd.setSignatureConfirmation(wss11.isRequireSignatureConfirmation()); rpd.setWss11(wss11); } /** * Populate elements to sign and/or encrypt with the message tokens. * * @param see * The data describing the elements (XPath) * @param rpd * The WSS4J data to initialize */ private static void processSignedEncryptedElements( SignedEncryptedElements see, RampartPolicyData rpd) { Iterator it = see.getXPathExpressions().iterator(); if (see.isSignedElemets()) { while (it.hasNext()) { rpd.setSignedElements((String) it.next()); } } else { while (it.hasNext()) { rpd.setEncryptedElements((String) it.next()); } } rpd.addDeclaredNamespaces(see.getDeclaredNamespaces()); } /** * Populate parts to sign and/or encrypt with the message tokens. * * @param sep * The data describing the parts * @param rpd * The WSS4J data to initialize */ private static void processSignedEncryptedParts(SignedEncryptedParts sep, RampartPolicyData rpd) { Iterator it = sep.getHeaders().iterator(); if (sep.isSignedParts()) { rpd.setSignBody(sep.isBody()); rpd.setSignAttachments(sep.isAttachments()); rpd.setSignAllHeaders(sep.isSignAllHeaders()); rpd.setSignBodyOptional(sep.isOptional()); rpd.setSignAttachmentsOptional(sep.isOptional()); while (it.hasNext()) { Header header = (Header) it.next(); rpd.addSignedPart(header.getNamespace(), header.getName()); } } else { rpd.setEncryptBody(sep.isBody()); rpd.setEncryptAttachments(sep.isAttachments()); rpd.setEncryptBodyOptional(sep.isOptional()); rpd.setEncryptAttachmentsOptional(sep.isOptional()); while (it.hasNext()) { Header header = (Header) it.next(); rpd.setEncryptedParts(header.getNamespace(), header.getName(),"Header"); } } } private static void processContentEncryptedElements(ContentEncryptedElements cee, RampartPolicyData rpd) { Iterator it = cee.getXPathExpressions().iterator(); while (it.hasNext()) { rpd.setContentEncryptedElements((String) it.next()); } rpd.addDeclaredNamespaces(cee.getDeclaredNamespaces()); } private static void processRequiredElements(RequiredElements req, RampartPolicyData rpd) { Iterator it = req.getXPathExpressions().iterator(); while (it.hasNext()) { rpd.setRequiredElements((String) it.next()); } rpd.addDeclaredNamespaces(req.getDeclaredNamespaces()); } /** * Evaluate policy data that is common to all bindings. * * @param binding * The common binding data * @param rpd * The WSS4J data to initialize */ private static void binding(Binding binding, RampartPolicyData rpd) { rpd.setLayout(binding.getLayout().getValue()); rpd.setIncludeTimestamp(binding.isIncludeTimestamp()); rpd.setIncludeTimestampOptional(binding.isIncludeTimestampOptional()); rpd.setAlgorithmSuite(binding.getAlgorithmSuite()); } /** * Evaluate policy data that is common to symmetric and asymmetric bindings. * * @param binding * The symmetric/asymmetric binding data * @param rpd * The WSS4J data to initialize */ private static void symmAsymmBinding( SymmetricAsymmetricBindingBase binding, RampartPolicyData rpd) { rpd.setEntireHeadersAndBodySignatures(binding .isEntireHeadersAndBodySignatures()); rpd.setProtectionOrder(binding.getProtectionOrder()); rpd.setSignatureProtection(binding.isSignatureProtection()); rpd.setTokenProtection(binding.isTokenProtection()); rpd.setAlgorithmSuite(binding.getAlgorithmSuite()); } /** * Evaluate policy data that is specific to symmetric binding. * * @param binding * The symmetric binding data * @param rpd * The WSS4J data to initialize */ private static void symmetricBinding(SymmetricBinding binding, RampartPolicyData rpd) throws WSSPolicyException { Assertion token = binding.getProtectionToken(); if (token != null) { rpd.setProtectionToken(((ProtectionToken)token).getProtectionToken()); } else { Assertion encrToken = binding.getEncryptionToken(); Assertion sigToken = binding.getSignatureToken(); if (token == null && sigToken == null) { throw new WSSPolicyException("Symmetric binding should have a Protection token or" + " both Signature and Encryption tokens defined"); } rpd.setEncryptionToken( ((EncryptionToken) encrToken).getEncryptionToken()); rpd.setSignatureToken(((SignatureToken) sigToken).getSignatureToken()); } } /** * Evaluate policy data that is specific to asymmetric binding. * * @param binding * The asymmetric binding data * @param rpd * The WSS4J data to initialize */ private static void asymmetricBinding(AsymmetricBinding binding, RampartPolicyData rpd) throws WSSPolicyException { TokenWrapper tokWrapper = binding.getRecipientToken(); TokenWrapper tokWrapper1 = binding.getInitiatorToken(); if (tokWrapper == null || tokWrapper1 == null) { throw new WSSPolicyException("Asymmetric binding should have both Initiator and " + "Recipient tokens defined"); } rpd.setRecipientToken(((RecipientToken) tokWrapper).getReceipientToken()); rpd.setInitiatorToken(((InitiatorToken) tokWrapper1).getInitiatorToken()); } private static void processSupportingTokens(SupportingToken token, RampartPolicyData rpd) throws WSSPolicyException { rpd.setSupportingTokens(token); } private static void processMTOMSerialization(MTOMAssertion mtomAssertion, RampartPolicyData rpd) { rpd.setMTOMAssertion(mtomAssertion); } }
true
0e0a71b57b0614a44a822a0eb7841749e27aae7c
Java
xsl2000/schie
/schie/schie-framework/src/main/java/org/schic/modules/sys/dao/OnlineSessionFactory.java
UTF-8
1,869
2.109375
2
[]
no_license
package org.schic.modules.sys.dao; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.SessionContext; import org.apache.shiro.session.mgt.SessionFactory; import org.apache.shiro.web.session.mgt.WebSessionContext; import org.schic.common.utils.IpUtils; import org.schic.common.utils.ServletUtils; import org.schic.common.utils.StringUtils; import org.schic.modules.monitor.entity.OnlineSession; import org.schic.modules.sys.entity.SysUserOnline; import org.springframework.stereotype.Service; import eu.bitwalker.useragentutils.UserAgent; /** * * @Description: 自定义sessionFactory会话 * @author Caiwb * @date 2019年5月6日 上午10:37:26 */ @Service public class OnlineSessionFactory implements SessionFactory { public Session createSession(SysUserOnline userOnline) { OnlineSession onlineSession = userOnline.getSession(); if (StringUtils.isNotNull(onlineSession) && onlineSession.getId() == null) { onlineSession.setId(userOnline.getId()); } return userOnline.getSession(); } @Override public Session createSession(SessionContext initData) { OnlineSession session = new OnlineSession(); if (initData instanceof WebSessionContext) { WebSessionContext sessionContext = (WebSessionContext) initData; HttpServletRequest request = (HttpServletRequest) sessionContext .getServletRequest(); if (request != null) { UserAgent userAgent = UserAgent.parseUserAgentString( ServletUtils.getRequest().getHeader("User-Agent")); // 获取客户端操作系统 String os = userAgent.getOperatingSystem().getName(); // 获取客户端浏览器 String browser = userAgent.getBrowser().getName(); session.setHost(IpUtils.getIpAddr(request)); session.setBrowser(browser); session.setOs(os); } } return session; } }
true
0057b69c6d59dbc40d364406f9b1ba8f7bf71c07
Java
inunez/HR-Services-DB
/src/java/entities/UniformPK.java
UTF-8
3,462
2.390625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Ismael */ @Embeddable public class UniformPK implements Serializable { @Basic(optional = false) @NotNull @Size(min = 1, max = 10) @Column(name = "id_number") private String idNumber; @Basic(optional = false) @NotNull @Size(min = 1, max = 1) @Column(name = "status") private String status; @Basic(optional = false) @NotNull @Column(name = "date_sent") @Temporal(TemporalType.DATE) private Date dateSent; @Basic(optional = false) @NotNull @Column(name = "index_sent") private Integer index; public UniformPK() { } public UniformPK(String idNumber, String status, Date dateSent, Integer index) { this.idNumber = idNumber; this.status = status; this.dateSent = dateSent; this.index = index; } public String getIdNumber() { return idNumber; } public void setIdNumber(String idNumber) { this.idNumber = idNumber; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getDateSent() { return dateSent; } public void setDateSent(Date dateSent) { this.dateSent = dateSent; } public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } @Override public int hashCode() { int hash = 0; hash += (idNumber != null ? idNumber.hashCode() : 0); hash += (status != null ? status.hashCode() : 0); hash += (dateSent != null ? dateSent.hashCode() : 0); hash += (index != null ? index.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof UniformPK)) { return false; } UniformPK other = (UniformPK) object; if ((this.idNumber == null && other.idNumber != null) || (this.idNumber != null && !this.idNumber.equals(other.idNumber))) { return false; } if ((this.status == null && other.status != null) || (this.status != null && !this.status.equals(other.status))) { return false; } if ((this.dateSent == null && other.dateSent != null) || (this.dateSent != null && !this.dateSent.equals(other.dateSent))) { return false; } if (this.index != other.index) { return false; } return true; } @Override public String toString() { return "entities.UniformPK[ idNumber=" + idNumber + ", status=" + status + ", dateSent=" + dateSent + ", index=" + index + " ]"; } }
true
53fef84f498f3cf0a4211331f23ac2cfb2828fee
Java
LinThirteen/study_Java_basic
/Study_Java/day10/src/day10/io_file_API使用规则3.java
UTF-8
625
3.234375
3
[]
no_license
package day10; import java.io.File; import java.io.IOException; public class io_file_API使用规则3 { public static void main(String[] args) throws IOException { File src = new File("D:/eclipse/Study_Java/day10/12458.png"); //返回一个文件的长度,文件夹则为0 System.out.println("长度"+src.length()); //创建文件 createNewFile(),不存在则创建,存在则创建不成功 File src1 = new File("D:/eclipse/Study_Java/day10/io.txt"); boolean flag = src1.createNewFile(); System.out.println(flag); flag = src1.delete(); //删除文件 System.out.println(flag); } }
true
da7d9d2c6514d3dbf9a05c3165bda0e8600b02f6
Java
jalalzia1/infinity
/src/com/floreantpos/util/datamigrate/Elements.java
UTF-8
4,952
1.789063
2
[ "Apache-2.0" ]
permissive
/** * ************************************************************************ * * The contents of this file are subject to the MRPL 1.2 * * (the "License"), being the Mozilla Public License * * Version 1.1 with a permitted attribution clause; you may not use this * * file except in compliance with the License. You may obtain a copy of * * the License at http://www.floreantpos.org/license.html * * Software distributed under the License is distributed on an "AS IS" * * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * * License for the specific language governing rights and limitations * * under the License. * * The Original Code is Infinity POS. * * The Initial Developer of the Original Code is OROCUBE LLC * * All portions are Copyright (C) 2015 OROCUBE LLC * * All Rights Reserved. * ************************************************************************ */ package com.floreantpos.util.datamigrate; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import com.floreantpos.model.MenuCategory; import com.floreantpos.model.MenuGroup; import com.floreantpos.model.MenuItem; import com.floreantpos.model.MenuItemModifierGroup; import com.floreantpos.model.MenuModifier; import com.floreantpos.model.MenuModifierGroup; import com.floreantpos.model.Tax; @XmlRootElement(name = "elements") public class Elements { // public final static Class[] classes = new Class[] { User.class, Tax.class, MenuCategory.class, MenuGroup.class, MenuModifier.class, // MenuModifierGroup.class, MenuItem.class, MenuItemShift.class, Restaurant.class, UserType.class, UserPermission.class, Shift.class }; List<Tax> taxes; List<MenuCategory> menuCategories; List<MenuGroup> menuGroups; List<MenuModifier> menuModifiers; List<MenuItemModifierGroup> menuItemModifierGroups; List<MenuModifierGroup> menuModifierGroups; List<MenuItem> menuItems; //List<User> users; // List<MenuItemShift> menuItemShifts; // List<Restaurant> restaurants; // List<UserType> userTypes; // List<UserPermission> userPermissions; // List<Shift> shifts; public List<MenuCategory> getMenuCategories() { return menuCategories; } public void setMenuCategories(List<MenuCategory> menuCategories) { this.menuCategories = menuCategories; } public List<MenuGroup> getMenuGroups() { return menuGroups; } public void setMenuGroups(List<MenuGroup> menuGroups) { this.menuGroups = menuGroups; if (menuGroups == null) { return; } for (MenuGroup menuGroup : menuGroups) { MenuCategory parent = menuGroup.getParent(); if(parent != null) { parent.setMenuGroups(null); } } } public List<MenuModifier> getMenuModifiers() { return menuModifiers; } public void setMenuModifiers(List<MenuModifier> menuModifiers) { this.menuModifiers = menuModifiers; if (menuModifiers == null) return; for (MenuModifier menuModifier : menuModifiers) { MenuModifierGroup modifierGroup = menuModifier.getModifierGroup(); if(modifierGroup != null) { modifierGroup.setModifiers(null); } } } public List<MenuModifierGroup> getMenuModifierGroups() { return menuModifierGroups; } public void setMenuModifierGroups(List<MenuModifierGroup> menuModifierGroups) { this.menuModifierGroups = menuModifierGroups; } public List<MenuItem> getMenuItems() { return menuItems; } public void setMenuItems(List<MenuItem> menuItems) { this.menuItems = menuItems; } // public List<User> getUsers() { // return users; // } // // public void setUsers(List<User> users) { // this.users = users; // } // public List<Tax> getTaxes() { return taxes; } public void setTaxes(List<Tax> taxes) { this.taxes = taxes; } public List<MenuItemModifierGroup> getMenuItemModifierGroups() { return menuItemModifierGroups; } public void setMenuItemModifierGroups(List<MenuItemModifierGroup> menuItemModifierGroups) { this.menuItemModifierGroups = menuItemModifierGroups; } // public List<MenuItemShift> getMenuItemShifts() { // return menuItemShifts; // } // // public void setMenuItemShifts(List<MenuItemShift> menuItemShifts) { // this.menuItemShifts = menuItemShifts; // } // // public List<Restaurant> getRestaurants() { // return restaurants; // } // // public void setRestaurants(List<Restaurant> restaurants) { // this.restaurants = restaurants; // } // // public List<UserType> getUserTypes() { // return userTypes; // } // // public void setUserTypes(List<UserType> userTypes) { // this.userTypes = userTypes; // } // // public List<UserPermission> getUserPermissions() { // return userPermissions; // } // // public void setUserPermissions(List<UserPermission> userPermissions) { // this.userPermissions = userPermissions; // } // // public List<Shift> getShifts() { // return shifts; // } // // public void setShifts(List<Shift> shifts) { // this.shifts = shifts; // } }
true
6da5267ef80dfb68cdf16ccbbbe17093c881776d
Java
cdelfattore/FoodStoreModel
/FoodStoreModel/src/foodstore/model/Employee.java
UTF-8
1,944
2.390625
2
[]
no_license
package foodstore.model; import java.io.Serializable; import java.util.Date; public class Employee implements Serializable { private static final long serialVersionUID = 1L; private String firstName; private String lastName; private Date startDate; private Date endDate; private Date dateOfBirth; private int storeId; private String position; private String department; private int socialSecNum; private int employeeId; public Employee(){ } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public int getStoreId() { return storeId; } public void setStoreId(int storeId) { this.storeId = storeId; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public int getSocialSecNum() { return socialSecNum; } public void setSocialSecNum(int socialSecNum) { this.socialSecNum = socialSecNum; } public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } }
true
b76b0f7337ef334358243d816ac0ea4369f21b27
Java
yysoft/yy-auth
/auth-dashboard/src/main/java/net/caiban/auth/dashboard/service/staff/FeedbackService.java
UTF-8
639
1.898438
2
[ "MIT" ]
permissive
/** * Copyright 2011 ASTO. * All right reserved. * Created on 2011-5-19 */ package net.caiban.auth.dashboard.service.staff; import net.caiban.auth.dashboard.domain.staff.Feedback; import net.caiban.auth.dashboard.dto.PageDto; /** * @author mays ([email protected]) * * created on 2011-5-19 */ public interface FeedbackService { public Integer feedback(Feedback feedback); public PageDto<Feedback> pageFeedback(Integer status, PageDto<Feedback> page); public Integer dealSuccess(Integer id); public Integer dealNothing(Integer id); public Integer dealImpossible(Integer id); public Integer deleteFeedback(Integer id); }
true
d2fdff593f932ca4ebb390466b1d6f9cb15166a1
Java
LiesLee/CarlsbergPorject
/CarlsbergClient/src/main/java/com/carlsberg/app/module/my/persenter/MyPresenter.java
UTF-8
3,146
2.03125
2
[]
no_license
package com.carlsberg.app.module.my.persenter; import com.carlsberg.app.application.CarlsbergAppcation; import com.carlsberg.app.bean.common.User; import com.carlsberg.app.common.Constant; import com.carlsberg.app.http.protocol.CommonProtocol; import com.carlsberg.app.module.my.view.LoginView; import com.common.base.presenter.BasePresenterImpl; import com.common.callback.RequestCallback; import com.common.http.HttpSubscibe; import rx.android.schedulers.AndroidSchedulers; /** * Created by LiesLee on 2017/3/2. */ public class MyPresenter extends BasePresenterImpl<LoginView> { public MyPresenter(LoginView view) { super(view); } public void userInfo(){ HttpSubscibe.subscibe(CarlsbergAppcation.getInstance(), AndroidSchedulers.mainThread(), CommonProtocol.userInfo(), null, mView, new RequestCallback<User>() { @Override public void beforeRequest() { mView.showProgress(Constant.PROGRESS_TYPE_LIST); } @Override public void requestError(int code, String msg) { if(code == 0){ mView.hideProgress(Constant.PROGRESS_TYPE_LIST); mView.toast("网络失败异常,请稍后再试"); }else{ mView.toast(msg); } } @Override public void requestComplete() { mView.hideProgress(Constant.PROGRESS_TYPE_LIST); } @Override public void requestSuccess(User data) { if(data!=null){ mView.loginSucceed(data); } } }); } public void logout(){ HttpSubscibe.subscibe(CarlsbergAppcation.getInstance(), AndroidSchedulers.mainThread(), CommonProtocol.logout(), null, mView, new RequestCallback<String>() { @Override public void beforeRequest() { mView.showProgress(Constant.PROGRESS_TYPE_LIST); } @Override public void requestError(int code, String msg) { if(code == 0){ mView.hideProgress(Constant.PROGRESS_TYPE_LIST); mView.toast("网络失败异常,请稍后再试"); }else{ mView.toast(msg); } } @Override public void requestComplete() { mView.hideProgress(Constant.PROGRESS_TYPE_LIST); } @Override public void requestSuccess(String data) { if(data!=null){ mView.loginSucceed(null); } } }); } }
true
0c41c01f13d46c6318466366a8e90d48e31ae712
Java
Arturs85/ViaBotsJade
/src/sample/DistributionWTime.java
UTF-8
322
2.078125
2
[]
no_license
package sample; public class DistributionWTime { int[] tasksDistribution; int timeStart; int timeEnd; DistributionWTime(int[] tasksDistribution, int timeStart, int timeEnd) { this.tasksDistribution = tasksDistribution; this.timeStart = timeStart; this.timeEnd = timeEnd; } }
true
7acee1b94e998f2e061c3bbeb44d6921613f56f8
Java
LighteningSkype/ITrainRoute
/src/altynai/com/model/GStation.java
UTF-8
514
2.40625
2
[]
no_license
package altynai.com.model; public class GStation { private String name; private GArrival arrival; private GDeparture departure; public String getName() { return name; } public void setName(String name) { this.name = name; } public GArrival getArrival() { return arrival; } public void setArrival(GArrival arrival) { this.arrival = arrival; } public GDeparture getDeparture() { return departure; } public void setDeparture(GDeparture departure) { this.departure = departure; } }
true
77016064cb31ca730f8f571516274bda13a8e7fa
Java
missbe/acm-algorithm
/蓝桥杯竞赛/20161203校内预选赛/E.java
UTF-8
943
3.34375
3
[]
no_license
/* 题目描述 求三个数的最大公约数。 输入 每行输入三个正整数(满足100,000,000<N<1,000,000,000)。 输出 对应每个输入,输出最大公约数。 样例输入 120040650 160400250 20400750 179407728 237422727 338339574 样例输出 450 487521 */ //CODE import java.util.Scanner; public class five { public static void main(String[] args) { System.out.println(gcd(324, gcd(243,135))); int A,B,C; Scanner scanner=new Scanner(System.in); while(scanner.hasNext()){ A=scanner.nextInt(); B=scanner.nextInt(); C=scanner.nextInt(); ////求A和B的最大公约数后再与C求最大公约数 System.out.println(gcd(C, gcd(A,B))); } } ////最大公约数 public static int gcd(int a,int b){ if(0==b) return a; return gcd(b, a%b); } ///120040650 160400250 20400750 ///179407728 237422727 338339574 //120040650 120040651 120040652 ///1000000000 1000000002 1000000005 }
true
1342d806b08173ff85c59883493dcfaf2e39f3bd
Java
Chthonis/AndroidPowerMonitor
/app/src/main/java/com/molaro/androidpowermonitor/UI/GraphList.java
UTF-8
6,660
2.28125
2
[]
no_license
package com.molaro.androidpowermonitor.UI; import android.app.Fragment; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.Viewport; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import com.molaro.androidpowermonitor.R; import java.util.ArrayList; /* * Class GraphList * ------------------------ * Extends Fragment * * abstract class used to create a consistent usage * of a specific layout that is used many times * * formatted as a graph with a clickable ListView under it * that shows/hides related graphical data. * */ abstract class GraphList extends Fragment{ private final Handler handler = new Handler(); private Runnable timer; protected ArrayAdapter<String> listViewAdapter; protected ListView listView; protected GraphView graph; protected ArrayList<String> allDetails; protected ArrayList<LineGraphSeries<DataPoint>> allSeries; protected ArrayList<Boolean> graphOn; protected int lastX = 0; protected Context context; //public LineGraphSeries<DataPoint> series; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); allDetails = new ArrayList<String>(); allSeries = new ArrayList<LineGraphSeries<DataPoint>>(); graphOn = new ArrayList<Boolean>(); context = getActivity().getApplicationContext(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.activity_graph_list, container, false); graph = (GraphView) view.findViewById(R.id.graph); Viewport viewport = graph.getViewport(); viewport.setYAxisBoundsManual(true); viewport.setMinY(0.0); viewport.setXAxisBoundsManual(true); viewport.setMinX(0.0); viewport.setMaxX(200); viewport.setScrollable(true); pageActivity(); listView = (ListView)view.findViewById(R.id.info_list); listViewAdapter = new ArrayAdapter<String> (getActivity(), android.R.layout.simple_list_item_1, allDetails); listView.setAdapter(listViewAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int hexColor = getColor(position); int newPosition = position - listView.getFirstVisiblePosition(); if(graphOn.get(position)) { graph.removeSeries(allSeries.get(position)); graphOn.set(position, false); listView.getChildAt(newPosition).setBackgroundColor(Color.TRANSPARENT); } else { graph.addSeries(allSeries.get(position)); graphOn.set(position, true); listView.getChildAt(newPosition).setBackgroundColor(hexColor); } } }); return view; } @Override public void onResume() { super.onResume(); timer = new Runnable() { @Override public void run() { runActivity(); listViewAdapter.notifyDataSetChanged(); handler.postDelayed(this, 1000); } }; handler.postDelayed(timer, 1000); } @Override public void onPause() { handler.removeCallbacks(timer); super.onPause(); } public void initializeGraph(int size){ for(int i = 0; i <= size; i++){ LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(); int hexColor = getColor(i); series.setColor(hexColor); allSeries.add(series); graphOn.add(false); } } /* * Function * ------------------------ * Description: * * * @params * * * @returns * * */ public int getColor(int n){ int hexColor; switch (n) { case 0: hexColor = Color.BLUE; break; case 1: hexColor = Color.GREEN; break; case 2: hexColor = Color.RED; break; case 3: hexColor = Color.YELLOW; break; case 4: hexColor = Color.CYAN; break; case 5: hexColor = Color.MAGENTA; break; case 6: hexColor = Color.DKGRAY; break; case 7: hexColor = Color.LTGRAY; break; case 8: hexColor = Color.GRAY; break; case 9: hexColor = Color.WHITE; break; default: hexColor = Color.BLACK; break; } return hexColor; } /* * Function * ------------------------ * Description: * * * @params * * * @returns * * */ public double bytesToKilobytes(long b){ double ret = (double)b; ret /= 1000.0; ret = Math.round(ret * 1000.0) / 1000.0; return ret; } /* * Function * ------------------------ * Description: * * * @params * * * @returns * * */ public String getDataDirection(int n){ String ret; switch(n){ case(0): ret = "Download"; break; case(1): ret = "Upload"; break; default: ret = "_"; break; } return ret; } /* * Function * ------------------------ * Description: * * * @params * * * @returns * * */ public abstract void pageActivity(); /* * Function * ------------------------ * Description: * * * @params * * * @returns * * */ public abstract void runActivity(); }
true
9b7366be6b44f62e8ed2daf4e734b443bae0d59a
Java
ganumule777/AndroidWorkspaceNew
/BookDoctorsTime/src/com/techroot/bookdoctorstime/DoctorsDetailsProfileActivity.java
UTF-8
8,273
1.96875
2
[]
no_license
package com.techroot.bookdoctorstime; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.RequestParams; import com.techroot.bookdoctorstime.AppointmentActivity.GetDocByDocIdDetails; import com.techroot.bookdoctorstime.constants.LeverageConstants; import com.techroot.bookdoctorstime.doctorManagement.model.Doctor; import com.techroot.bookdoctorstime.doctorManagement.service.DoctorService; import com.techroot.bookdoctorstime.exception.LeverageExceptions; import com.techroot.bookdoctorstime.exception.LeverageNonLethalException; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import android.os.Build; public class DoctorsDetailsProfileActivity extends ActionBarActivity { private String strDocId; private ArrayList<Doctor> serverDoctorsDetails; DoctorService objDoctorService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_doctors_details_profile); strDocId=getIntent().getExtras().getString("docId"); serverDoctorsDetails=new ArrayList<Doctor>(); // WebServer Request URL String serverURL = LeverageConstants.URL+"getDocDetailsPrfl/"+strDocId; // Use AsyncTask execute Method To Prevent ANR Problem new GetDocProfileDetails().execute(serverURL); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.doctors_details_profile, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater .inflate(R.layout.fragment_doctors_details_profile, container, false); return rootView; } } /********************************************************************************* ********************************************************************************** ** Copyright (C) 2014 Techroot Pvt. Ltd. Pune INDIA ** Author : Ganesh Mule ** Created on : 09-12-2014 ** Dept: Android Based Mobile App Development ** Class: GetDocProfileDetails ** Description: This is inner class used to call suitable http method from server and get its result * Here we call method to get category details from server *********************************************************************************** ***********************************************************************************/ public class GetDocProfileDetails extends AsyncTask<String, Void, Void> { RequestParams params = new RequestParams(); private final HttpClient Client = new DefaultHttpClient(); private String Content; String result; private String Error = null; private ProgressDialog Dialog = new ProgressDialog(DoctorsDetailsProfileActivity.this); protected void onPreExecute() { // NOTE: You can call UI Element here. // Start Progress Dialog (Message) Dialog.setMessage("Please wait.."); Dialog.show(); Dialog.setIndeterminate(false); Dialog.setCancelable(false); params.add("strDocId", strDocId); } @Override protected Void doInBackground(String... arg0) { /************ Make Post Call To Web Server ***********/ // HttpGet request = new HttpGet(arg0[0]); HttpClient httpClient; httpClient = new DefaultHttpClient(); HttpResponse response; try { HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(arg0[0]); response= httpClient.execute(httpGet, localContext); HttpEntity entity = response.getEntity(); InputStream inputStream = null; inputStream= entity.getContent(); if(inputStream != null) result = convertStreamToString(inputStream); serverDoctorsDetails.clear(); if(!("error").equals(result.trim())) { // Converting gson to List of given elemnts Gson gson = new Gson(); ArrayList<Doctor> li=gson.fromJson(result, new TypeToken<List<Doctor>>(){}.getType()); serverDoctorsDetails=li; } Content=result; } catch (Exception e) { Content=result; System.out.println(e.getMessage()); } return null; } protected void onPostExecute(Void unused) { // NOTE: You can call UI Element here. // Close progress dialog Dialog.dismiss(); try { if(!(null==Content)) { if (!("error").equals(Content.trim())) { if(!serverDoctorsDetails.isEmpty()) { populateDocDetails(serverDoctorsDetails.get(0)); } } else { // Show Response Json On Screen (activity) throw new LeverageNonLethalException(LeverageExceptions.ERROR_CONNECTING_DATABASE,"Problem to coonecting to the server. Please try again"); } } else { throw new LeverageNonLethalException(LeverageExceptions.ERROR_CONNECTING_DATABASE,"Problem to coonecting to the server. Please try again"); } } catch (LeverageNonLethalException e) { // TODO Auto-generated catch block e.printStackTrace(); finish(); Toast.makeText(DoctorsDetailsProfileActivity.this,e.getExceptionMsg(), Toast.LENGTH_SHORT).show(); } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); } catch (IOException e) { } Log.i("*************Response*************** :: ", sb.toString()); return sb.toString(); } } /******************************************************************************* ** Function Name : populateDocDetails ** Created By : Ganesh Mule ** Description : This function is used to populate doc details ** Creation Date : 13/11/2014 ** Arguments : View v ** Return Type : void * @throws LeverageNonLethalException *******************************************************************************/ public void populateDocDetails(Doctor doctorListItem) { try { TextView tvDocName=(TextView)findViewById(R.id.tvDocNameDetails); TextView tvDocProfile=(TextView)findViewById(R.id.tvProfile); tvDocName.setText(doctorListItem.getDocFirstName()+" "+doctorListItem.getDocLastName()); if(null==doctorListItem.getDocDetailsProfile()) { tvDocProfile.setText("Profile details not present."); } else { tvDocProfile.setText(doctorListItem.getDocDetailsProfile()); } } catch(Exception e) { e.printStackTrace(); } } }
true
b19ee2de67f435188089fd3128bdd848010c3800
Java
elkhassoumichaimae/EL-KHASSOUMI-chaimae
/ELKHASSOUMI_chaimae/src/main/java/com/web/Serve2.java
UTF-8
1,441
2.3125
2
[ "MIT" ]
permissive
package com.web; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dao.UserDao; import com.model.User; /** * Servlet implementation class Serve2 */ @WebServlet("/Serve2") public class Serve2 extends HttpServlet { private static final long serialVersionUID = 1L; UserDao em; /** * @see HttpServlet#HttpServlet() */ public Serve2() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub em=new UserDao(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String log=request.getParameter("log"); String pass=request.getParameter("pass"); User u = em.authentification(log, pass); if(u!=null) { HttpSession ses = request.getSession(true); ses.setAttribute("user", u); response.sendRedirect("index2"); }else response.sendRedirect("index.jsp"); } }
true
70e86c9b92c11f8e2578db0839b4e3a30f99b713
Java
Jakedufe/LeetCode
/src/leetcode/editor/cn/mainThread/P733FloodFill.java
UTF-8
2,798
3.453125
3
[]
no_license
//有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。 // // 给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。 // // 为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方 //向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。 // // 最后返回经过上色渲染后的图像。 // // 示例 1: // // //输入: //image = [[1,1,1],[1,1,0],[1,0,1]] //sr = 1, sc = 1, newColor = 2 //输出: [[2,2,2],[2,2,0],[2,0,1]] //解析: //在图像的正中间,(坐标(sr,sc)=(1,1)), //在路径上所有符合条件的像素点的颜色都被更改成2。 //注意,右下角的像素没有更改为2, //因为它不是在上下左右四个方向上与初始点相连的像素点。 // // // 注意: // // // image 和 image[0] 的长度在范围 [1, 50] 内。 // 给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。 // image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。 // // Related Topics 深度优先搜索 // 👍 138 👎 0 package leetcode.editor.cn.mainThread; import org.junit.Test; //Java:图像渲染 //2020-09-24 16:42:18 public class P733FloodFill { @Test public void testResult() { //TO TEST Solution solution = new P733FloodFill().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int oldColor = image[sr][sc]; if (oldColor == newColor) return image; dfs(image, sr, sc, newColor, oldColor); return image; } private void dfs(int[][] image, int sr, int sc, int newColor, int oldColor) { image[sr][sc] = newColor; int[][] moves = new int[][]{{1, 0}, {-1, 0}, {0, -1}, {0, 1}}; for (int[] move : moves) { int r = sr + move[0]; int c = sc + move[1]; if (inArea(image, r, c) && image[r][c] == oldColor) { dfs(image, r, c, newColor, oldColor); } } } private boolean inArea(int[][] image, int r, int c) { return r >= 0 && r < image.length && c >= 0 && c < image[0].length; } } //leetcode submit region end(Prohibit modification and deletion) }
true
2bcf4bab828073fd6025dc2a8deb174fe30601cb
Java
sweetcczhang/smart4j
/src/main/java/zcc/smart4j/framework/util/ArrayUtil.java
UTF-8
353
2.28125
2
[]
no_license
package zcc.smart4j.framework.util; import org.apache.commons.lang3.ArrayUtils; /** * Created by 张城城 on 2018/3/30. */ public final class ArrayUtil { public static boolean isEmpty(Object[] array){ return ArrayUtils.isEmpty(array); } public static boolean isNotEmpty(Object[] array){ return !isEmpty(array); } }
true
be421eabfb021a2fb775bf1ce823590d87e9534e
Java
vatplanner/raw-data-archiver
/server/src/main/java/org/vatplanner/archiver/local/FetchedFileType.java
UTF-8
872
2.5
2
[ "MIT" ]
permissive
package org.vatplanner.archiver.local; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Identifies file types related to fetched data. */ public enum FetchedFileType { RAW_VATSIM_DATA_FILE(".*vatsim-data\\.(txt|json)$"), META_DATA(".*meta\\.json$"); private final Pattern fileNamePattern; private FetchedFileType(String fileNamePattern) { this.fileNamePattern = Pattern.compile(fileNamePattern); } public static FetchedFileType byFileName(String fileName) { for (FetchedFileType type : FetchedFileType.values()) { if (type.matchesFileName(fileName)) { return type; } } return null; } private boolean matchesFileName(String fileName) { Matcher matcher = fileNamePattern.matcher(fileName); return matcher.matches(); } }
true
f3fb1179b470303e01c3e4457563687a32b576de
Java
xuxiaowei007/carousel
/carousel-ds/src/test/java/org/lpw/carousel/discovery/QueryTest.java
UTF-8
5,549
2.1875
2
[ "Apache-2.0" ]
permissive
package org.lpw.carousel.discovery; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.junit.Assert; import org.junit.Test; import org.lpw.tephra.test.SchedulerAspect; import javax.inject.Inject; /** * @author lpw */ public class QueryTest extends TestSupport { @Inject private SchedulerAspect schedulerAspect; @Test public void query() { trustfulIp("/discovery/query"); schedulerAspect.pause(); for (int i = 0; i < 100; i++) create("key " + (i % 20), i); mockHelper.reset(); mockHelper.getRequest().addParameter("pageSize", "2"); mockHelper.getRequest().addParameter("pageNum", "1"); mockHelper.mock("/discovery/query"); JSONObject object = mockHelper.getResponse().asJson(); Assert.assertEquals(0, object.getIntValue("code")); JSONObject data = object.getJSONObject("data"); Assert.assertEquals(100, data.getIntValue("count")); Assert.assertEquals(2, data.getIntValue("size")); Assert.assertEquals(1, data.getIntValue("number")); JSONArray list = data.getJSONArray("list"); Assert.assertEquals(2, list.size()); for (int i = 0; i < list.size(); i++) { JSONObject discovery = list.getJSONObject(i); Assert.assertEquals("key " + i, discovery.getString("key")); Assert.assertEquals("service " + i, discovery.getString("service")); Assert.assertEquals("validate " + i, discovery.getString("validate")); Assert.assertEquals("success " + i, discovery.getString("success")); Assert.assertEquals(i, discovery.getIntValue("state")); } mockHelper.reset(); mockHelper.getRequest().addParameter("key", "ey 1"); mockHelper.getRequest().addParameter("pageSize", "2"); mockHelper.getRequest().addParameter("pageNum", "1"); mockHelper.mock("/discovery/query"); object = mockHelper.getResponse().asJson(); Assert.assertEquals(0, object.getIntValue("code")); data = object.getJSONObject("data"); Assert.assertEquals(55, data.getIntValue("count")); Assert.assertEquals(2, data.getIntValue("size")); Assert.assertEquals(1, data.getIntValue("number")); list = data.getJSONArray("list"); Assert.assertEquals(2, list.size()); int[] ns = new int[]{1, 10}; for (int i = 0; i < ns.length; i++) { JSONObject discovery = list.getJSONObject(i); Assert.assertEquals("key " + ns[i], discovery.getString("key")); Assert.assertEquals("service " + ns[i], discovery.getString("service")); Assert.assertEquals("validate " + ns[i], discovery.getString("validate")); Assert.assertEquals("success " + ns[i], discovery.getString("success")); Assert.assertEquals(1 - i, discovery.getIntValue("state")); } mockHelper.reset(); mockHelper.getRequest().addParameter("service", "ce 3"); mockHelper.getRequest().addParameter("pageSize", "2"); mockHelper.getRequest().addParameter("pageNum", "1"); mockHelper.mock("/discovery/query"); object = mockHelper.getResponse().asJson(); Assert.assertEquals(0, object.getIntValue("code")); data = object.getJSONObject("data"); Assert.assertEquals(11, data.getIntValue("count")); Assert.assertEquals(2, data.getIntValue("size")); Assert.assertEquals(1, data.getIntValue("number")); list = data.getJSONArray("list"); Assert.assertEquals(2, list.size()); ns = new int[]{3, 30}; for (int i = 0; i < ns.length; i++) { JSONObject discovery = list.getJSONObject(i); Assert.assertEquals("key " + (ns[i] % 20), discovery.getString("key")); Assert.assertEquals("service " + ns[i], discovery.getString("service")); Assert.assertEquals("validate " + ns[i], discovery.getString("validate")); Assert.assertEquals("success " + ns[i], discovery.getString("success")); Assert.assertEquals(ns[i] % 2, discovery.getIntValue("state")); } mockHelper.reset(); mockHelper.getRequest().addParameter("key", "ey 1"); mockHelper.getRequest().addParameter("service", "ce 3"); mockHelper.getRequest().addParameter("pageSize", "2"); mockHelper.getRequest().addParameter("pageNum", "1"); mockHelper.mock("/discovery/query"); object = mockHelper.getResponse().asJson(); Assert.assertEquals(0, object.getIntValue("code")); data = object.getJSONObject("data"); Assert.assertEquals(10, data.getIntValue("count")); Assert.assertEquals(2, data.getIntValue("size")); Assert.assertEquals(1, data.getIntValue("number")); list = data.getJSONArray("list"); Assert.assertEquals(2, list.size()); ns = new int[]{30, 31}; for (int i = 0; i < ns.length; i++) { JSONObject discovery = list.getJSONObject(i); Assert.assertEquals("key " + (ns[i] % 20), discovery.getString("key")); Assert.assertEquals("service " + ns[i], discovery.getString("service")); Assert.assertEquals("validate " + ns[i], discovery.getString("validate")); Assert.assertEquals("success " + ns[i], discovery.getString("success")); Assert.assertEquals(ns[i] % 2, discovery.getIntValue("state")); } schedulerAspect.press(); } }
true
08f4572c6d28b5eb4b74dd4fc6c8141e159a9098
Java
thaerrm/Bridge-Pattern
/src/main/java/Colors/Blue.java
UTF-8
242
2.8125
3
[]
no_license
package Colors; import Interfaces.Color; public class Blue implements Color { // used when choosing the color BLUE to assign to all existing shapes public void chooseColor() { System.out.println("BLUE"); } }
true
5cf00348d1005bdf7a18b65482fb3ecdf8801aa2
Java
seeing-eye/UnforgetIt
/app/src/main/java/org/jasey/unforgetit/repository/TaskRepositoryImpl.java
UTF-8
5,082
2.375
2
[ "Apache-2.0" ]
permissive
package org.jasey.unforgetit.repository; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.util.Log; import org.jasey.unforgetit.entity.Task; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.persistence.Id; public class TaskRepositoryImpl extends TaskRepository { static TaskRepositoryImpl getInstance(Context context) { return new TaskRepositoryImpl(context); } private DataBaseHelper helper; private TaskRepositoryImpl(Context context) { helper = DataBaseHelper.getInstance(context); } @Override public boolean addNew(Task task) { long stopwatch = System.currentTimeMillis(); try { if (task.getId() != null) { return false; } ContentValues values = fillContentValues(task); long id = helper .getWritableDatabase() .insert(Task.TABLE_NAME, null, values); if (id != -1) { Field[] fields = task.getClass().getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(Id.class)) { f.setAccessible(true); f.set(task, id); break; } } return true; } else { return false; } } catch (Exception e) { Log.e(this.getClass().getName(), ADD + ERROR_MESSAGE, e); return false; } finally { Log.d(this.getClass().getName(), String.format(ADD + STOPWATCH, System.currentTimeMillis() - stopwatch)); } } @Override public boolean remove(Task task) { long stopwatch = System.currentTimeMillis(); try { return helper .getWritableDatabase() .delete(Task.TABLE_NAME, Task.ID + " = ? ", new String[]{String.valueOf(task.getId())}) != 0; } catch (Exception e) { Log.e(this.getClass().getName(), REMOVE + ERROR_MESSAGE, e); return false; } finally { Log.d(this.getClass().getName(), String.format(REMOVE + STOPWATCH, System.currentTimeMillis() - stopwatch)); } } @Override public boolean update(Task task) { long stopwatch = System.currentTimeMillis(); try { ContentValues values = fillContentValues(task); return helper .getWritableDatabase() .update(Task.TABLE_NAME, values, null, null) != -1; } catch (Exception e) { Log.e(this.getClass().getName(), UPDATE + ERROR_MESSAGE, e); return false; } finally { Log.d(this.getClass().getName(), String.format(UPDATE + STOPWATCH, System.currentTimeMillis() - stopwatch)); } } @NonNull private ContentValues fillContentValues(Task task) { ContentValues values = new ContentValues(); values.put(Task.TASK_TITLE_COLUMN, task.getTitle()); values.put(Task.TASK_DATE_COLUMN, task.getDate().getTime()); values.put(Task.TASK_PRIORITY_COLUMN, task.getPriorityLevel()); values.put(Task.TASK_DONE_COLUMN, task.isDone()); values.put(Task.TASK_ALARM_ADVANCE_TIME_COLUMN, task.getAlarmAdvanceTime()); return values; } @Override public List<Task> getAll() { List<Task> tasks = new ArrayList<>(); long stopwatch = System.currentTimeMillis(); try { Cursor cursor = helper .getReadableDatabase() .query(Task.TABLE_NAME, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Long id = cursor.getLong(cursor.getColumnIndex(Task.ID)); String title = cursor.getString(cursor.getColumnIndex(Task.TASK_TITLE_COLUMN)); Date date = new Date(cursor.getLong(cursor.getColumnIndex(Task.TASK_DATE_COLUMN))); int priority = cursor.getInt(cursor.getColumnIndex(Task.TASK_PRIORITY_COLUMN)); boolean done = cursor.getInt(cursor.getColumnIndex(Task.TASK_DONE_COLUMN)) == 1; int alarmAdvanceTime = cursor.getInt(cursor.getColumnIndex(Task.TASK_ALARM_ADVANCE_TIME_COLUMN)); tasks.add(Task.buildTask(id, title, date, priority, done, alarmAdvanceTime)); } while (cursor.moveToNext()); } cursor.close(); return tasks; } catch (Exception e) { Log.e(this.getClass().getName(), GET_ALL + ERROR_MESSAGE, e); return Collections.emptyList(); } finally { Log.d(this.getClass().getName(), String.format(GET_ALL + STOPWATCH, System.currentTimeMillis() - stopwatch)); } } }
true
bda58e2bc812a0e752b70b7aae2ba1f5fcc9abed
Java
twopisoft/tweetmoodtut
/src/main/java/com/twopi/tutorial/utils/LanguageMapper.java
UTF-8
788
2.8125
3
[]
no_license
package com.twopi.tutorial.utils; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * This class provides a method to convert from ISO-639-1 languages designation (returned by Twitter) to * ISO-639-2 one which is needed by IDOL Sentiment Analysis API. * @author arshad01 * */ public class LanguageMapper { private static Map<String, String> LANG_MAP = new HashMap<String,String>(); static { String[] languages = Locale.getISOLanguages(); for (String lang : languages) { Locale loc = new Locale(lang); LANG_MAP.put(loc.getISO3Language(), lang); } } public static String map(String inputLanguage) { return LANG_MAP.getOrDefault(inputLanguage, "eng"); } }
true
268a0b0068ed6db5bb21a772c9d0be2120be8725
Java
levantuy/identity-samples-spring-boot
/src/main/java/org/wso2/identity/sample/oidc/controller/IndexController.java
UTF-8
5,268
2
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.identity.sample.oidc.controller; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import com.nimbusds.openid.connect.sdk.claims.UserInfo; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * Handles the redirection after successful authentication from Identity Server */ @Controller public class IndexController { private final Logger LOGGER = Logger.getLogger(IndexController.class.getName()); private String userName; private DefaultOidcUser user; private final OAuth2AuthorizedClientService authorizedClientService; public IndexController(OAuth2AuthorizedClientService authorizedClientService) { this.authorizedClientService = authorizedClientService; } /** * Redirects to this method once the user successfully authenticated and this method will redirect to index page. * * @param model Model. * @param authentication Authentication. * @return Index page. */ @GetMapping("/") public String currentUserName(Model model, Authentication authentication) { user = (DefaultOidcUser) authentication.getPrincipal(); if (user != null) { userName = user.getName(); } model.addAttribute("userName", userName); getTokenDetails(model, authentication); return "index"; } @GetMapping("/login/oauth2/code/wso2") public String callback(@RequestParam Map<String, String> allParams) { // SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(new UserInfo(yourHash, allParams.get, expirationDate))); return "callback"; } /** * Handles the redirection to /userinfo endpoint and get the user information from authentication object. This * method will display the id-token and user information in the UI. * * @param authentication Authentication * @param model Model. * @return userinfo html page. */ @GetMapping("/userinfo") public String getUser(Authentication authentication, Model model) { model.addAttribute("userName", userName); model.addAttribute("idtoken", user.getClaims()); LOGGER.log(Level.INFO, "UserName : " + userName); LOGGER.log(Level.INFO, "User Attributes: " + user.getClaims()); return "userinfo"; } private void getTokenDetails(Model model, Authentication authentication) { OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication; String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId(); OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(clientRegistrationId, oauthToken.getName()); if (client != null && client.getAccessToken() != null) { String accessToken = client.getAccessToken().getTokenValue(); Set<String> scope = client.getAccessToken().getScopes(); String tokenType = client.getAccessToken().getTokenType().getValue(); String accessTokenExp = client.getAccessToken().getExpiresAt().toString(); LOGGER.log(Level.INFO, "Access token : " + accessToken); LOGGER.log(Level.INFO, "Token type : " + tokenType); LOGGER.log(Level.INFO, "Scope : " + scope); LOGGER.log(Level.INFO, "Access token Exp : " + accessTokenExp); model.addAttribute("accessToken", accessToken); model.addAttribute("tokenType", tokenType); model.addAttribute("accessTokenExp", accessTokenExp); model.addAttribute("scope", scope); } if (client != null && client.getRefreshToken() != null) { String refreshToken = client.getRefreshToken().getTokenValue(); LOGGER.log(Level.INFO, "Refresh token: " + refreshToken); model.addAttribute("refreshToken", refreshToken); } } }
true
0466f8b4be2d023852dcf60c35bec6bf9c68944a
Java
IcedGarion/erweb-work-finder
/HOME/garepubbliche/web/src/main/java/it/erweb/web/beans/BandiView.java
UTF-8
1,711
2.265625
2
[]
no_license
package it.erweb.web.beans; import java.io.Serializable; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.event.ActionEvent; import it.erweb.web.data.Bando; import it.erweb.web.services.BandiService; /** * View Bean handling any frontend operation on a Bando */ @ManagedBean @SessionScoped public class BandiView implements Serializable { public static final long serialVersionUID = -926624460350620171L; @ManagedProperty("#{bandiService}") private BandiService bandiService; private List<Bando> userBans; private String filter = "new"; /** * Creates the list of current logged-in user's Bans that needs to be notified; * By default, only the last bans are loaded */ public void init() { userBans = bandiService.createUserBans(filter); } /** * Re-creates the list of current user's bans, after filter form submit * AJAX * * @param actionEvent */ public void init(ActionEvent actionEvent) { init(); } public void setBandiService(BandiService banServ) { this.bandiService = banServ; } public BandiService getBandiService() { return this.bandiService; } public void setuserBans(List<Bando> bList) { this.userBans = bList; } public void setFilter(String filter) { this.filter = filter; } public String getFilter() { return this.filter; } /** * Returns to the view the whole list of current user's bans, created in PostConstruct * * @return A list of bans */ public List<Bando> getuserBans() { //aggiorna la lista (causa magari cambio utente logout) init(); return this.userBans; } }
true
48517b69850cf42e80d570c37fb7d3d21b461329
Java
gmadekunle/Primes
/PrimeGenerator/PrimeGen/src/test/java/com/dare/adekunle/primegen/generators/PrimeGeneratorTest.java
UTF-8
2,295
2.953125
3
[]
no_license
/** * */ package com.dare.adekunle.primegen.generators; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class PrimeGeneratorTest { @ParameterizedTest @MethodSource("paramStream") public void testFastGeneratorGetPrimes(Integer[][] params) { FastPrimeGenerator fastPrimeGenerator = new FastPrimeGenerator(); Integer[] args = params[0]; List<Integer> expectedResult = Arrays.asList(params[1]); List<Integer> actualResult = fastPrimeGenerator.getPrimes(args[0], args[1]); assertEquals(expectedResult, actualResult); } @ParameterizedTest @MethodSource("paramStream") public void testModerateGeneratorGetPrimes(Integer[][] params) { ModeratePrimeGenerator moderatePrimeGenerator = new ModeratePrimeGenerator(); Integer[] args = params[0]; List<Integer> expectedResult = Arrays.asList(params[1]); List<Integer> actualResult = moderatePrimeGenerator.getPrimes(args[0], args[1]); assertEquals(expectedResult, actualResult); } @ParameterizedTest @MethodSource("paramStream") public void testSlowGeneratorGetPrimes(Integer[][] params) { SlowPrimeGenerator slowPrimeGenerator = new SlowPrimeGenerator(); Integer[] args = params[0]; List<Integer> expectedResult = Arrays.asList(params[1]); List<Integer> actualResult = slowPrimeGenerator.getPrimes(args[0], args[1]); assertEquals(expectedResult, actualResult); } public static Stream<Arguments> paramStream() { return Stream.of(Arguments.arguments((Object) new Integer[][]{ { -4, 1 }, {} }), /* min and max below 2, no primes */ Arguments.arguments((Object) new Integer[][]{ { 50, 10 }, {} }), /* max > min, no primes */ Arguments.arguments((Object)new Integer[][]{ { 0, 2 }, { 2 } }), /* min = 0, max = 2, one prime */ Arguments.arguments((Object)new Integer[][]{ { 1, 10 }, { 2, 3, 5, 7 } }), /* min = 1, max = 10, 4 primes */ Arguments.arguments((Object) new Integer[][]{ { 20, 40 }, { 23, 29, 31, 37 } })); /* min = 20, max = 40, four primes */ } }
true
505c6172db279fa7c4040cc29e514e9eae4321b7
Java
goodboy95/seekerhutAPP
/seekerhutApp/src/main/java/com/example/duoyi/testapp1/MainActivity.java
UTF-8
2,643
2.3125
2
[]
no_license
package com.example.duoyi.testapp1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button)findViewById(R.id.button3); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { URL url = new URL("http://www.seekerhut.com/homeapi/login"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); Map<String, String> loginMap = new HashMap<>(); loginMap.put("username", "duwei"); loginMap.put("password", "123456"); byte[] postInfo = PostParamConverter(loginMap); byte[] gotInfo = new byte[1000]; con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", String.valueOf(postInfo.length)); OutputStream os = con.getOutputStream(); os.write(postInfo); InputStream is = con.getInputStream(); is.read(gotInfo); System.out.print(gotInfo); } catch (Exception e) { System.out.println(e); } } }); } private byte[] PostParamConverter(Map<String, String> params) throws Exception { byte[] encodeBytes = null; StringBuilder sb = new StringBuilder(); if (params == null) { return encodeBytes; } for (Map.Entry<String, String> ent : params.entrySet()) { sb.append(URLEncoder.encode(ent.getKey(), "UTF-8")); if (!TextUtils.isEmpty(ent.getValue())) { sb.append(URLEncoder.encode(ent.getValue(), "UTF-8")); } else { sb.append(URLEncoder.encode("", "UTF-8")); } sb.append("&"); } encodeBytes = sb.toString().getBytes(); return encodeBytes; } }
true
15ffa4c55097d59b5b9784002773e3fc445368a0
Java
tokeepsmile/java-se
/src/main/java/com/wangwei/design/pattern/responsibility/Handler.java
UTF-8
728
3.59375
4
[]
no_license
package com.wangwei.design.pattern.responsibility; /** * @Author wangwei * @Date 2020/4/27 9:06 下午 * @Version 1.0 * 在职责链模式中,多个处理器(也就是刚刚定义中说的“接收对象”)依次处理同一个请求。一个请求先经过 A 处理器处理, * 然后再把请求传递给 B 处理器,B 处理器处理完后再传递给 C 处理器,以此类推,形成一个链条。 * 链条上的每个处理器各自承担各自的处理职责,所以叫作职责链模式。 */ public abstract class Handler { protected Handler successor = null; public void setSuccessor(Handler successor) { this.successor = successor; } public abstract void handle(); }
true
6557bd18ed32799cb694b98b1e1aa8d546d04066
Java
dshah2012/GlobalConnect
/src/com/ge/tps/enums/Gender.java
UTF-8
133
1.789063
2
[]
no_license
/** * */ package com.ge.tps.enums; /** * @author anil * @since 26-Feb-2016 * @version */ public enum Gender { MALE,FEMALE; }
true
96e5d660431bd35c4607bdd88996234c4b814cee
Java
shenshuangxi/rocketmq
/rocketmq-common/src/main/java/com/sundy/rocketmq/common/protocol/body/KVTable.java
UTF-8
356
1.5
2
[]
no_license
package com.sundy.rocketmq.common.protocol.body; import java.util.HashMap; import lombok.Getter; import lombok.Setter; import com.sundy.rocketmq.remoting.protocol.RemotingSerializable; @Getter @Setter public class KVTable extends RemotingSerializable { private HashMap<String, String> table = new HashMap<String, String>(); }
true
6c35d52e479861887b1fed633d7155a5a877a485
Java
MaoLeYuu/asset-1
/src/main/java/me/maxct/asset/util/StringUtil.java
UTF-8
529
2.40625
2
[]
no_license
package me.maxct.asset.util; import java.security.SecureRandom; /** * @author imaxct * 2019-03-25 18:28 */ public class StringUtil { private static final long TOP_LIMIT = 0x19A100L; private static final long LOWER_LIMIT = 0xB640L; private static final SecureRandom RANDOM = new SecureRandom(); public static String random4BitStr() { long number = Math.abs(RANDOM.nextLong()) % (TOP_LIMIT - LOWER_LIMIT) + LOWER_LIMIT; return Long.toUnsignedString(number, 36); } }
true
4a495c1ad659a35b238591b603726bcc87894aed
Java
f3226912/paycenter
/paycenter-api/src/main/java/cn/gdeng/paycenter/api/server/order/OrderbaseInfoHessianService.java
UTF-8
1,117
1.710938
2
[]
no_license
package cn.gdeng.paycenter.api.server.order; import java.util.List; import java.util.Map; import cn.gdeng.paycenter.api.BizException; import cn.gdeng.paycenter.dto.pos.OrderBaseinfoHessianDto; import cn.gdeng.paycenter.dto.pos.WangPosOrderListRequestDto; import cn.gdeng.paycenter.dto.pos.WangPosResultDto; public interface OrderbaseInfoHessianService { OrderBaseinfoHessianDto getByOrderNo(String orderNo) throws BizException; List<Map<String, String>> getUnpaidOrderList(Map<String, Object> map) throws Exception; String getProductName(String orderNo) throws BizException; /** * 分页获取尾款信息 * @return * @throws BizException */ WangPosResultDto getFinalOrder4Page(WangPosOrderListRequestDto dto) throws BizException; public String updateOrderForCheckBill(Map<String, Object> params) throws Exception; public String addOrderForCheckBill(Map<String, Object> params) throws Exception; public String addPaySerialnumberForCheckBill(Map<String, Object> params) throws Exception; public String dealAdvanceAndPayment(List<OrderAdvanceAndPaymentDTO> list) throws Exception; }
true
6e33be74b556cb107ce09786fdfbd3efd595e307
Java
Manikyavalli9/SpringBoot
/src/main/java/com/example/springPractice1/Practice.java
UTF-8
1,234
2.96875
3
[]
no_license
package com.example.springPractice1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component //it will make it as bean // @Scope(value = "prototype") //it wont create default value i.e. no singleton public class Practice { private int pid; private String pname; @Autowired //it will connect practice class obj to laptop class object private Laptop laptop; public Laptop getLaptop() { return laptop; } public void setLaptop(Laptop laptop) { this.laptop = laptop; } public Practice() { System.out.println("object is created........"); } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } private String tech; public String getTech() { return tech; } public void setTech(String tech) { this.tech = tech; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public void show(){ System.out.println("show me"); laptop.compiler(); } }
true
dc4f01da113a4c60e55e9bb21752274b87ed8a2a
Java
zhangjiahe-web/10.1-10.8
/XueYuan/src/main/java/com/kgc/zhang/service/studentinfoService.java
UTF-8
361
1.8125
2
[]
no_license
package com.kgc.zhang.service; import com.kgc.zhang.entity.studentinfo; import com.kgc.zhang.entity.studentinfoExample; import java.util.List; public interface studentinfoService { List<studentinfo> selectByExample(studentinfoExample example); studentinfo selectByPrimaryKey(Integer sid); int updateByPrimaryKeySelective(studentinfo record); }
true
13cd2e317dd4e99b7a7077d1320a78d9095bce7a
Java
SucreLighT/SpringBootProjects
/SpringBoot-HelloWorld/src/main/java/cn/sucrelt/springboothelloworld/controller/HelloWorldController.java
UTF-8
985
2.21875
2
[]
no_license
package cn.sucrelt.springboothelloworld.controller; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @description: * @author: sucre * @date: 2020/12/13 * @time: 17:24 */ @RestController @RequestMapping("test") @ConfigurationProperties(prefix = "helloworld") public class HelloWorldController { // @Value("${helloworld.username}") private String username; // @Value("${helloworld.info}") private String info; @RequestMapping("hello") public String sayHello() { return username + ":" + info; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } }
true
5da003429d45604b8b0b1c8f9b71e34196d8230f
Java
DarinLyn/leetcode
/src/main/java/com/darin/leetcode/code/DP/HouseRobber.java
UTF-8
1,817
3.859375
4
[]
no_license
package com.darin.leetcode.code.DP; /** * 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, * 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 * * 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 * * 示例 1: * * 输入: [1,2,3,1] * 输出: 4 * 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 *   偷窃到的最高金额 = 1 + 3 = 4 。 * 示例 2: * * 输入: [2,7,9,3,1] * 输出: 12 * 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 *   偷窃到的最高金额 = 2 + 9 + 1 = 12 。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/house-robber */ public class HouseRobber { public static void main(String[] args) { // int[] nums = {1,2,3,1}; // int[] nums = {2,7,9,3,1}; int[] nums = {1,3,1,3,100}; System.out.println(new HouseRobber().rob(nums)); } /** * 第i位的最大值等于第i-2的最大值+第i位的值 或者 第i-1位的最大值 * dp[i] = max(dp[i-2]+nums[i] + dp[i-1]) * * @param nums * @return */ public int rob(int[] nums) { if(nums.length == 0) return 0; if(nums.length == 1) return nums[0]; int ans1 = nums[0]; int ans2 = Math.max(nums[0], nums[1]); for(int i = 2; i < nums.length; i++){ int cur = Math.max(ans1 + nums[i], ans2); ans1 = ans2; ans2 = cur; } return ans2; } }
true
4a4ca1b7417ed54297b606001346f80cc8aa087a
Java
talmeym/regurgitator-core-yml
/src/main/java/com/emarte/regurgitator/core/YmlLoader.java
UTF-8
334
1.515625
2
[ "MIT" ]
permissive
/* * Copyright (C) 2017 Miles Talmey. * Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ package com.emarte.regurgitator.core; import java.util.Set; public interface YmlLoader<TYPE> extends Loader<Yaml, TYPE> { TYPE load(Yaml yaml, Set<Object> allIds) throws RegurgitatorException; }
true
0721e96d1ccdc95d6e5dade9cf567d77f1651285
Java
sebastianacevedoc/NewPingeso
/sml4/sml4-ejb/src/main/java/ejb/FormularioDigitadorLocal.java
UTF-8
772
1.90625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejb; import entity.Formulario; import entity.Usuario; import java.util.Date; import javax.ejb.Local; /** * * @author sebastian */ @Local public interface FormularioDigitadorLocal { public String crearFormulario(String rut, String ruc, String rit, int nue, int nParte, String delito, String direccionSS, String lugar, String unidadPolicial, Date fecha, String observacion, String descripcion, Usuario digitador); public String crearTraslado(Formulario formulario, Usuario usuarioInicia, String usuarioRecibeRut, Date fechaT, String observaciones, String motivo); }
true
0f29bbd2b669c8c7f37d2317006cde08c0141f96
Java
gandeng/ThinkAndroidDemo
/app/src/main/java/activity/ThinkAndroidSimpleDwonLoadActivtiy.java
UTF-8
3,257
2.359375
2
[]
no_license
package activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.ta.annotation.TAInjectView; import com.ta.util.cache.TAExternalOverFroyoUtils; import com.ta.util.http.AsyncHttpClient; import com.ta.util.http.FileHttpResponseHandler; import com.thinkandroiddemo.ganjian.thinkandroiddemo.R; /** * Created by ganjian on 2016/8/22. */ public class ThinkAndroidSimpleDwonLoadActivtiy extends ThinkAndroidBaseActivity { final static String DOWNLOAD_DIR="download"; @TAInjectView(id = R.id.start) Button startbuton; @TAInjectView(id = R.id.stop) Button stopbutton; @TAInjectView(id = R.id.textview) TextView textView; @TAInjectView(id = R.id.prograssbar) ProgressBar progressBar; @Override protected void onAfterOnCreate(Bundle savedInstanceState) { super.onAfterOnCreate(savedInstanceState); setTitle(R.string.thinkandroid_simple_download_title); setContentView(R.layout.simple_download); } @Override protected void onAfterSetContentView() { super.onAfterSetContentView(); final AsyncHttpClient asyncHttpClient=new AsyncHttpClient(); final FileHttpResponseHandler fileHttpResponseHandler=new FileHttpResponseHandler( TAExternalOverFroyoUtils.getDiskCacheDir(ThinkAndroidSimpleDwonLoadActivtiy.this,DOWNLOAD_DIR).getAbsolutePath()) { @Override public void onProgress(long totalSize, long currentSize, long speed) { super.onProgress(totalSize, currentSize, speed); long downloadPercent=currentSize*100/totalSize; progressBar.setVisibility(View.VISIBLE); progressBar.setProgress(100*progressBar.getProgress()); textView.setText(downloadPercent+":"+speed+"kbs"); } @Override public void onFailure(Throwable error, byte[] binaryData) { super.onFailure(error, binaryData); textView.setText("x下载失败"); } @Override public void onSuccess(byte[] binaryData) { super.onSuccess(binaryData); textView.setText("下载成功"); } }; View.OnClickListener onClickListener=new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.start: startDownload(); break; case R.id.stop: stopDownload(); } } private void startDownload() { fileHttpResponseHandler.setInterrupt(false); asyncHttpClient.download("http://static.qiyi.com/ext/common/iQIYI/QIYImedia_4_01.exe",fileHttpResponseHandler); } private void stopDownload(){ fileHttpResponseHandler.setInterrupt(true);//设置暂停 } }; startbuton.setOnClickListener(onClickListener); stopbutton.setOnClickListener(onClickListener); } }
true
acf76106008e468b6e5418db234f53a2e18d166f
Java
zeeberry/cmp211
/SavingsAccount.java
UTF-8
1,622
3.8125
4
[]
no_license
package project5; /** * <p>Title: SavingsAccount Class</p> * * <p>Description: It able to create a SavingsAccount * object. It's a subclass of Account. It contains * a withdrawal and deposit method. </p> * * @author Zainab Ebrahimi * */ public class SavingsAccount extends Account { /** * SavingAccount default constructor-- * calls the default constructor in * the parent class by using super(). */ public SavingsAccount() { super(); } /** * SavingsAccount parameterized constructor-- * initializes instance variables in the parent class * by calling super(); * @param balance containing balance amount to initialize * the account. * @param accountN containing the account number. */ public SavingsAccount(double balance, int accountN, Customer c) { super(balance, accountN, c); } /** * withdrawal method-- * accepts the amount to withdraw and * decreases the balance amount. If the * balance is equal to zero withdraw will * not be able to process. */ public double withdrawal(double Wamount){ double theBalance = this.getBalance(); if(theBalance == 0){ return 0; }else{ if(theBalance < Wamount){ this.setBalance(0); }else{ this.setBalance(theBalance - Wamount); } return theBalance -(theBalance - Wamount); } } /** * deposit method-- * accepts the amount to deposit and * increases the balance. * @param containing the amount to * deposit. */ public void deposit(double Damount){ this.setBalance(this.getBalance()+Damount); } }
true
d348c7977d85275e6680932b411d328a4e11b6ad
Java
Herrius/Android-Studio-fragment
/app/src/main/java/com/example/datosusuariosupe/ConsultarUsuario.java
UTF-8
1,735
2.1875
2
[]
no_license
package com.example.datosusuariosupe; import androidx.appcompat.app.AppCompatActivity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import entidades.conexionSqlHelper; import utils.utils; public class ConsultarUsuario extends AppCompatActivity implements View.OnClickListener { EditText edtId, edtNom, edttel; Button btnbuscar; conexionSqlHelper conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_consultar_usuario); edtId=findViewById(R.id.edtCUid); edtNom=findViewById(R.id.edtCUnombre); edttel=findViewById(R.id.edtCUTel); btnbuscar=findViewById(R.id.btnconsulUsuario); btnbuscar.setOnClickListener(this); conn=new conexionSqlHelper(this, "bd_usuarios",null,1); } @Override public void onClick(View view) { consultar(); } private void consultar(){ SQLiteDatabase db=conn.getReadableDatabase(); String[] parametros={edtId.getText().toString()}; String[] campos={utils.CAMPO_NOMBRE,utils.CAMPO_TELEFONO}; try { Cursor cursor=db.query(utils.TABLA_USUARIO,campos,utils.CAMPO_ID+"=?",parametros,null,null,null); cursor.moveToFirst(); edtNom.setText(cursor.getString(0)); edttel.setText(cursor.getString(1)); cursor.close(); }catch (Exception e){ Toast.makeText(this,"El registro buscado no existe",Toast.LENGTH_SHORT).show(); }; } }
true
da17533da13287f4873525d8b49e4262ecc31c29
Java
JefferyCJ/Jef_tmc_poi
/src/main/java/com/tumi/data/poi/utils/CategoryUtils.java
UTF-8
1,463
2.515625
3
[]
no_license
package com.tumi.data.poi.utils; import com.googlecode.easyec.sika.WorkData; import org.apache.commons.lang.StringUtils; import java.util.List; import java.util.Set; import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; /** * @author jefferychan */ public class CategoryUtils { public static void fill(List<WorkData> list, Set<String> baseCategories, String col, boolean isCheck) { WorkData data = WorkDataUtils.getData2String(list, col); if (data != null) { List<String> categories = WorkDataUtils.getData2ListString(data); if (isNotEmpty(categories)) { for (int i = 0; i < categories.size(); i++) { String val = categories.get(i); boolean b = baseCategories.stream() .anyMatch(cate -> StringUtils.equalsIgnoreCase(val, cate)); if (!b) { if (!isCheck) { categories.remove(i--); } else { WorkDataUtils.appendErrorLabel(list, "column 【" + col + "】 can't check: [" + val + "]"); } } } data.setValue(StringUtils.join(categories, ",")); } else { String lable = "not found any categories"; WorkDataUtils.appendErrorLabel(list, lable); } } } }
true
cde8f77523456ac3fe5da55a45ed0161e983ece4
Java
Asmitha07/positive
/revnum.java
UTF-8
347
2.75
3
[]
no_license
import java.io.*; import java.util.*; class revnum { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); int r=0; int i; while(a>0) { i=a%10; r=r*10+i; a=a/10; } System.out.println(r); } }
true
3369d9fe229775da34dddce0b98bb802d79f9d93
Java
Tynx11/AndroidLab
/HomeWorkRecycler/app/src/main/java/com/example/tony/homeworkrecycler/model/Event.java
UTF-8
2,084
2.625
3
[]
no_license
package com.example.tony.homeworkrecycler.model; import android.os.Parcel; import android.os.Parcelable; import java.util.Date; /** * Created by Tony on 25.09.2017. */ public class Event implements Parcelable { private String eventDescription; private String name; private int photoId; protected Event(Parcel in) { eventDescription = in.readString(); name = in.readString(); photoId = in.readInt(); id = in.readInt(); } public static final Creator<Event> CREATOR = new Creator<Event>() { @Override public Event createFromParcel(Parcel in) { return new Event(in); } @Override public Event[] newArray(int size) { return new Event[size]; } }; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } private Date date; public Event(int id, int photoId, String eventDescription, String name, Date date) { this.eventDescription = eventDescription; this.name = name; this.photoId = photoId; this.id = id; this.date = date; } public String getEventDescription() { return eventDescription; } public void setEventDescription(String eventDescription) { this.eventDescription = eventDescription; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPhotoId() { return photoId; } public void setPhotoId(int photoId) { this.photoId = photoId; } public int getId() { return id; } public void setId(int id) { this.id = id; } private int id; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(eventDescription); dest.writeString(name); dest.writeInt(photoId); dest.writeInt(id); } }
true
e19044adb02668eae03f6d6180ce618f5bc7a4ea
Java
yixayixa/School-Projects
/ActiveMQPublisher.java
UTF-8
9,654
2.421875
2
[]
no_license
package middleware; import org.apache.activemq.ActiveMQConnectionFactory; import engine.StatsCollector; import engine.StoppingCriteria; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import java.util.Hashtable; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; /** This class is a server that can generate requests for option payout and send them to a client. After the client send back result, the * server adds the result to a stats collector and keep tracking for the stopping criteria. The server sends 100 requests each time as a * batch, and keep sending unless the stopping criteria is met. * The results and requests destinations must correspond to those of the server class to ensure the communication between the two classes. */ public class ActiveMQPublisher { protected int MAX_DELTA_PERCENT = 1; protected Map<String, Double> LAST_PRICES = new Hashtable<String, Double>(); protected static int count = 10; protected static int total; protected static String brokerURL = "tcp://localhost:61616"; protected static ConnectionFactory factory; protected Connection connection; protected Session session; protected MessageProducer producer; private StoppingCriteria _criteria; private int _numSimulation; private String ticker; public ActiveMQPublisher(String ticker) throws JMSException { factory = new ActiveMQConnectionFactory(brokerURL); connection = factory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(null); this.ticker=ticker; } public void close() throws JMSException { if (connection != null) { connection.close(); } } public static void main(String[] args) throws Exception { //Pop up the choices of European and Asian options System.out.println("Please choose an option style: "+"Type European or Asian"); //The user need to enter one type of option to run Scanner scan=new Scanner(System.in); String optionType=scan.nextLine(); ActiveMQPublisher publisher = new ActiveMQPublisher("Results");//change the destination if necessary publisher.run(optionType); scan.close(); } //This class calls multiple methods to complete the simulation process //Input: Option type, either 'European' or 'Asian' public void run(String optionType) throws Exception{ //Create queue for requests Destination queue_1=session.createQueue("Requests");//change the destination if necessary //Create queue for results Destination queue_2 = session.createQueue(ticker); MessageConsumer messageConsumer =session.createConsumer(queue_2); //Stats collector StatsCollector sc_1=new StatsCollector(); //Keep tracking of the request id TreeMap<Integer,Integer> idSet=new TreeMap<Integer,Integer>(); //Warm up the simulation by 100 batches (10000 simulations) and return current id for further id generating int id=this.warmUp(sc_1, optionType, queue_1, messageConsumer, idSet); //Generate stopping criteria this._criteria=new StoppingCriteria(0.98,sc_1.getSD(),0.1); this._criteria.calculateNum(); this._numSimulation=this._criteria.getNumSimulation(); //Run the simulation process, stop when meet the stopping criteria this.runSimulation(id, queue_1, messageConsumer, optionType, sc_1, idSet); } //Warm up the simulation by 100 batches (10000 simulations in total) //Input: stats collector, optionType, destination, message consumer //Return: Current id public int warmUp(StatsCollector sc, String optionType, Destination queue_1, MessageConsumer messageConsumer, TreeMap<Integer,Integer> idSet) throws Exception { // A flag that checks if the client is running and send result boolean received=false; //Initiate the first id as 0 int id=0; //Count number of batches sent int count=0; while(count<100) { //Sent request in first loop or when the client is running and responding if ((count==0) || (received)) { for(int i=0; i<100; i++) { TextMessage msg = session.createTextMessage(optionType+","+id+",252,152.35,0.01,0.0001,1"); producer.send(queue_1,msg); //put the new id as a new key in the id set for later checking idSet.put(id, 1); //update the id for next message id++; } count++; } //wait for results from the client Thread.sleep(500); //Listen to results sent from client messageConsumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { if (message instanceof TextMessage){ try{ //Store message in a string String result=((TextMessage) message).getText(); //token the string for information String[] tok=result.split(","); int resultId=Integer.parseInt(tok[1]); double payout=Double.parseDouble(tok[2]); //add the data is the message was sent by this server if(idSet.containsKey(resultId)) { sc.addData(payout); } } catch (JMSException e ){ e.printStackTrace(); } } } }); //as long as there is data in the stats collector, the client is working, set flag true if(sc.getData().size()!=0) { received=true; System.out.println("The running estimated payout for number "+count+ " batch of warm up is currently: "+sc.getAverage()); } } System.out.println("Warm up is done!"); System.out.println("=========================================================================================="); //return the last id for further id generating return(id); } //Run additional simulations beside the warm up //Input: current id, destination, message consumer, option type, stats collector, id set public void runSimulation(int id, Destination queue_1, MessageConsumer messageConsumer, String optionType, StatsCollector sc_1, TreeMap<Integer, Integer> idSet) throws Exception { // A flag that checks if the client is running and send result boolean received=false; //Count for the number of simulations had ran int count_2=0; //Check if the number of simulation needed is greater than 10000, if it is, further simulations are needed if(this._numSimulation>10000) { System.out.println("More simulations besides warm up simulations are needed!"); System.out.println("=========================================================================================="); //Count for the number of batches sent int count_batch=0; //check if another batch is needed while (count_2<this._numSimulation-100){ if ((count_2==0) || (received)) { for(int i=0; i<100; i++) { TextMessage msg = session.createTextMessage(optionType+","+id+",252,152.35,0.01,0.0001,1"); producer.send(queue_1,msg); idSet.put(id, 1); id++; count_2++; } count_batch++; } //Wait for responses from the client Thread.sleep(500); messageConsumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { if (message instanceof TextMessage){ try{ String result=((TextMessage) message).getText(); String[] tok=result.split(","); int resultId=Integer.parseInt(tok[1]); double payout=Double.parseDouble(tok[2]); //Check if the message was sent by this server if(idSet.containsKey(resultId)) { sc_1.addData(payout); } } catch (JMSException e ){ e.printStackTrace(); } } } }); if(sc_1.getData().size()!=0) { received=true; System.out.println("The running estimated payout for number "+count_batch+ " batch AFTER warm up is currently: "+sc_1.getAverage()); } //update the stopping criteria after one batch was simulated this._criteria=new StoppingCriteria(0.98,sc_1.getSD(),0.1); this._criteria.calculateNum(); //update the number of simulation needed this._numSimulation=this._criteria.getNumSimulation(); } } else { this._numSimulation=10000; } connection.close(); System.out.println("=========================================================================================="); System.out.println("Total number of simulation is: "+this._numSimulation); System.out.println("=========================================================================================="); System.out.println("The final estimated payout for the option is: "+sc_1.getAverage()); } }
true
ac63b9d3f4d72793046394ae7c07d478b609bde4
Java
tranggoro/Tugas
/BangunDatar.java
UTF-8
836
2.9375
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 javaapplication1; /** * * @author trian */ import java.util.Scanner; public class BangunDatar { public static void main(String[] args) { int s; double luas; Scanner input = new Scanner (System.in); System.out.println("=================================="); System.out.println(" MENGHITUNG LUAS PERSEGI "); System.out.println("=================================="); System.out.println(""); s =input.nextInt(); luas = s*s; System.out.println("luas persegi adalah : "+luas+"cm2"); } }
true
26cf6886c882d45f98b4bb6f22f31a75380d87d7
Java
SamuelDerous/JVakantie
/src/be/zenodotus/data/Totalen.java
UTF-8
1,505
2.421875
2
[]
no_license
package be.zenodotus.data; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.content.Context; import be.zenodotus.databank.Verlof; import be.zenodotus.databank.VerlofDao; import be.zenodotus.databank.Verlofsoort; import be.zenodotus.databank.VerlofsoortDao; public class Totalen { private Context context; private VerlofsoortDao verlofsoortDao; private VerlofDao verlofDao; private ArrayList<Verlofsoort> verlofsoorten; private ArrayList<Verlof> verloven; private List<Rekenen> berekeningen; private int jaar; private Calendar cal; public Totalen(Context context, int jaar) { this.context = context; this.jaar = jaar; berekeningen = new ArrayList<Rekenen>(); } public void getSoorten() { verlofsoortDao = new VerlofsoortDao(context); verlofsoortDao.open(); verlofsoorten = verlofsoortDao.getAlleSoortenPerJaar(jaar); verlofsoortDao.close(); } public List<Rekenen> berekenUren() { getSoorten(); verlofDao = new VerlofDao(context); verlofDao.open(); Rekenen berekening; for(int i = 0; i < verlofsoorten.size(); i++) { verloven = verlofDao.getAlleVerlovenPerJaarPerSoort(jaar, verlofsoorten.get(i).getSoort()); berekening = new Rekenen(verlofsoorten.get(i).getUren(), verlofsoorten.get(i).getSoort()); for(int j = 0; j < verloven.size(); j++) { berekening.aftrekken(verloven.get(j).getUrental()); } berekeningen.add(berekening); } verlofDao.close(); return berekeningen; } }
true
40eeb8d85bd16014f6633fa28d4705403b0a7f89
Java
BanisBT/2021-03-18-ParkingAppJAVA
/src/main/java/org/example/tomasBarauskas/model/parking/parkingCity/ParkingKlaipeda.java
UTF-8
826
2.546875
3
[]
no_license
package org.example.tomasBarauskas.model.parking.parkingCity; import org.example.tomasBarauskas.model.parking.ParkingZone; public class ParkingKlaipeda implements ParkingCity{ private static final ParkingZone NO_ZONE = ParkingZone.NO_ZONE; private static final ParkingZone RED_ZONE = ParkingZone.KLAIPEDA_RED_ZONE; private static final ParkingZone GREEN_ZONE = ParkingZone.KLAIPEDA_GREEN_ZONE; private static final String NAME = "Klaipeda"; public ParkingKlaipeda() { } @Override public ParkingZone getBlueZone() { return NO_ZONE; } @Override public ParkingZone getRedZone() { return RED_ZONE; } @Override public ParkingZone getGreenZone() { return GREEN_ZONE; } @Override public String getName() { return NAME; } }
true
3b13c137d747d7fd58dedf2052b590f854b2fdee
Java
miarevalo10/ReporteReddit
/reddit-decompilada/com/instabug/library/core/InitialScreenshotHelper.java
UTF-8
2,531
1.953125
2
[]
no_license
package com.instabug.library.core; import android.graphics.Bitmap; import android.net.Uri; import com.instabug.library.screenshot.C0753a; import com.instabug.library.screenshot.C0753a.C0752a; import com.instabug.library.tracking.InstabugInternalTrackingDelegate; import com.instabug.library.util.BitmapUtils; import com.instabug.library.util.BitmapUtils.C0771a; import com.instabug.library.util.InstabugSDKLogger; public class InitialScreenshotHelper { public interface InitialScreenshotCapturingListener { void onScreenshotCapturedSuccessfully(Uri uri); void onScreenshotCapturingFailed(Throwable th); } public static void captureScreenshot(final InitialScreenshotCapturingListener initialScreenshotCapturingListener) { C0753a.m8313a(InstabugInternalTrackingDelegate.getInstance().getTargetActivity(), new C0752a() { class C13541 implements C0771a { final /* synthetic */ C13551 f15460a; C13541(C13551 c13551) { this.f15460a = c13551; } public final void mo2581a(Uri uri) { initialScreenshotCapturingListener.onScreenshotCapturedSuccessfully(uri); } public final void mo2582a(Throwable th) { StringBuilder stringBuilder = new StringBuilder("initial screenshot capturing got error: "); stringBuilder.append(th.getMessage()); stringBuilder.append(", time in MS: "); stringBuilder.append(System.currentTimeMillis()); InstabugSDKLogger.m8358e(this, stringBuilder.toString(), th); initialScreenshotCapturingListener.onScreenshotCapturingFailed(th); } } public final void mo2583a(Bitmap bitmap) { BitmapUtils.saveBitmap(bitmap, InstabugInternalTrackingDelegate.getInstance().getTargetActivity(), new C13541(this)); } public final void mo2584a(Throwable th) { StringBuilder stringBuilder = new StringBuilder("initial screenshot capturing got error: "); stringBuilder.append(th.getMessage()); stringBuilder.append(", time in MS: "); stringBuilder.append(System.currentTimeMillis()); InstabugSDKLogger.m8358e(this, stringBuilder.toString(), th); initialScreenshotCapturingListener.onScreenshotCapturingFailed(th); } }); } }
true
eca1fea8d2be2549c97678be6fcad1ca7ba4fc18
Java
KarloKnezevic/EDAF
/src/hr/fer/zemris/edaf/fitness/bbob/IUtil.java
UTF-8
2,359
2.703125
3
[]
no_license
package hr.fer.zemris.edaf.fitness.bbob; /** * Util interface. Defined in benchmarkshelper.h. * * @author Karlo Knezevic, [email protected] * */ public interface IUtil { /** * Round element to higher. * * @param a * @return rounded */ double round(double a); /** * Smaller element. * * @param a * @param b * @return Minor element */ double fmin(double a, double b); /** * Higher element. * * @param a * @param b * @return Higher element */ double fmax(double a, double b); /** * Generates N uniform numbers with starting seed * * @param r * @param N * @param inseed */ void unif(double[] r, int N, int inseed); /** * Samples N standard normally distributed numbers being the same for a * given seed. * * @param g * @param N * @param seed */ void gauss(double[] g, int N, int seed); /** * ? * * @param seed * @param _DIM */ void computeXopt(int seed, int _DIM); /** * ? * * @param f */ void monotoneTFosc(double[] f); /** * ? * * @param B * @param vector * @param m * @param n * @return ? */ double[][] reshape(double[][] B, double[] vector, int m, int n); /** * ? * * @param B * @param seed * @param _DIM */ void computeRotation(double[][] B, int seed, int _DIM); /** * Adaptation of myrand * * @return generated unif random number */ double myrand(); /** * Adaptation of myrand * * @return generated gauss random number */ double randn(); /** * ? * * @param Ftrue * @param beta * @return ? */ double FGauss(double Ftrue, double beta); /** * ? * * @param Ftrue * @param alpha * @param beta * @return ? */ double FUniform(double Ftrue, double alpha, double beta); /** * ? * * @param Ftrue * @param alpha * @param p * @return ? */ double FCauchy(double Ftrue, double alpha, double p); /** * Not used. * * @param a * @param b * @return */ int compare_doubles(int a, int b); /** * Util initialization. */ void initUtil(); /** * Util terminating. */ void finiUtil(); double computeFopt(int _funcId, int _trialId); /** * Set the seed for the noise. If the seeds are larger than 1e9 they are set * back to 1 in randn and myrand. * * @param _seed * @param _seedn */ void setNoiseSeed(int _seed, int _seedn); }
true
c15478edda656b9f6a569ef795387cec9a9225ae
Java
qianjinpeixun/RestSample
/RestSample/src/main/java/com/qianjin/java/sss/java2s/a1101/ass21/Connect4Board.java
UTF-8
8,516
3.15625
3
[]
no_license
package com.qianjin.java.sss.java2s.a1101.ass21; public class Connect4Board extends Board { private static final int rows = 6; private static final int cols = 7; private final int winCount = 4; private String winnerType; private Chip winChip; public Connect4Board() { super(rows, cols); } public boolean add(int col, String colour) { Chip chip = new Chip(colour); for (int i = rows - 1; i >= 0; i--) { if (isEmpty(i, col)) { return super.add(i, col, chip); } } return false; } public String winType() { return winnerType; } public boolean winner() { if (hasRowWin()) { winnerType = "horizontal"; return true; } if (hasColWin()) { winnerType = "vertical"; return true; } if (hasDigWin()) { winnerType = "diagonal"; return true; } if (hasDig2Win()) { winnerType = "diagonal2"; return true; } return false; } private boolean hasColWin() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (getBoard()[i][j] != null) { boolean colWin = colHasFour(i, j); if (colWin) { winChip = getBoard()[i][j]; return true; } } } } return false; } private boolean hasRowWin() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (getBoard()[i][j] != null) { boolean rowWin = rowHasFour(i, j); // System.out.println("rowWin="+rowWin+",i="+i+",j="+j); if (rowWin) { winChip = getBoard()[i][j]; return true; } } } } return false; } private boolean hasDigWin() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (getBoard()[i][j] != null) { boolean diaWin = diaHasFour(i, j); // System.out.println("rowWin="+rowWin+",i="+i+",j="+j); if (diaWin) { winChip = getBoard()[i][j]; return true; } } } } return false; } private boolean hasDig2Win() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (getBoard()[i][j] != null) { boolean diaWin = dia2HasFour(i, j); // System.out.println("rowWin="+rowWin+",i="+i+",j="+j); if (diaWin) { winChip = getBoard()[i][j]; return true; } } } } return false; } private boolean dia2HasFour(int row, int col) { boolean four = false; int colCount = 0; if (getBoard()[row][col] == null) return false; if (row < rows - 1 && col >0) for (int i = row + 1, j = col - 1; i < rows && j>0; i++, j--) { if (getBoard()[i][j] == null) { break; } if (getBoard()[row][col].equals(getBoard()[i][j])) { colCount++; } else { break; } } if (row > 0 && col <cols-1) for (int i = row - 1, j = col + 1; i > 0 && j <cols; i--, j++) { if (getBoard()[i][j] == null) { break; } if (getBoard()[row][col].equals(getBoard()[i][j])) { colCount++; } else { break; } } if (colCount >= (winCount - 1)) { four = true; } return four; } private boolean diaHasFour(int row, int col) { boolean four = false; int colCount = 0; if (getBoard()[row][col] == null) return false; if (row < rows - 1 && col < cols - 1) for (int i = row + 1, j = col + 1; i < rows && j < cols; i++, j++) { if (getBoard()[i][j] == null) { break; } if (getBoard()[row][col].equals(getBoard()[i][j])) { colCount++; } else { break; } } if (row > 0 && col > 0) for (int i = row - 1, j = col - 1; i > 0 && j > 0; i--, j--) { if (getBoard()[i][j] == null) { break; } if (getBoard()[row][col].equals(getBoard()[i][j])) { colCount++; } else { break; } } if (colCount >= (winCount - 1)) { four = true; } return four; } private boolean colHasFour(int row, int col) { boolean four = false; int colCount = 0; if (getBoard()[row][col] == null) return false; if (col < cols - 1) { for (int i = col + 1; i < cols; i++) { if (getBoard()[row][i] == null) { break; } if (getBoard()[row][col].equals(getBoard()[row][i])) { colCount++; } else { break; } } } if (col > 0) { for (int i = col - 1; i > 0; i--) { if (getBoard()[row][i] == null) { break; } if (getBoard()[row][col].equals(getBoard()[row][i])) { colCount++; } else { break; } } } // System.out.println("rowCount="+rowCount); if (colCount >= (winCount - 1)) { four = true; } return four; } private boolean rowHasFour(int row, int col) { boolean four = false; int rowCount = 0; if (getBoard()[row][col] == null) return false; rowCount = 0; if (row < rows - 1) { for (int i = row + 1; i < rows; i++) { if (getBoard()[i][col] == null) { break; } if (getBoard()[row][col].equals(getBoard()[i][col])) { rowCount++; } else { break; } } } if (row > 0) { for (int i = row - 1; i > 0; i--) { if (getBoard()[i][col] == null) { break; } if (getBoard()[row][col].equals(getBoard()[i][col])) { rowCount++; } else { break; } } } // System.out.println("rowCount="+rowCount); if (rowCount >= (winCount - 1)) { four = true; } return four; } public String toString() { System.out.println(); for (int i = 0; i < rows + 1; i++) { for (int j = 0; j < cols + 1; j++) { if (i == 0 && j == 0) { System.out.print(" "); continue; } if (i == 0) { if (j > 0) { System.out.print(j + " "); } if (j == 8) { System.out.println(); } } else { if (j > 0) { if (!isEmpty(i - 1, j - 1)) { System.out.print(getBoard()[i - 1][j - 1] + " "); } else { System.out.print(" "); } } } if (j == 0) { System.out.print(i + " "); } } System.out.println(); } return ""; } }
true
8c7b76ab6b1ac620da23becd0b5130faa6fc1587
Java
TAdragon1/p2p
/CloseSocketTask.java
UTF-8
755
2.9375
3
[]
no_license
import java.net.Socket; import java.util.TimerTask; public class CloseSocketTask extends TimerTask { private Socket connectionSocket; private Object heartbeatObject; public CloseSocketTask(Socket connectionSocket, Object heartbeatObject){ this.connectionSocket = connectionSocket; this.heartbeatObject = heartbeatObject; } @Override public void run() { try { if (!connectionSocket.isClosed()) { connectionSocket.close(); Printer.print("Heartbeat timeout: Closing socket"); synchronized (heartbeatObject) { heartbeatObject.notify(); } } } catch (Exception e){ } } }
true
83a89ebe0504585e15738856ff700fb7f8461f76
Java
Marimonbert/FastMeal
/FastMeal/FastMeal/app/src/main/java/com/example/fastmeal/cardapio/ResponseCardapio/CardapioResponse.java
UTF-8
1,301
2
2
[]
no_license
package com.example.fastmeal.cardapio.ResponseCardapio; import com.squareup.moshi.Json; public class CardapioResponse { @Json(name = "id_categoria") private String idCategoria; @Json(name = "nome") private String nome = "maria"; @Json(name = "descricao") private String descricao = "linda"; @Json(name = "valor") private String valor; @Json(name = "foto") private String foto; @Json(name = "id") private String id; public CardapioResponse( String id, String nome, String descricao, String valor, String foto, String idCategoria) { this.idCategoria = idCategoria; this.nome = nome; this.descricao = descricao; this.valor = valor; this.foto = foto; this.id = id; } public String getIdCategoria() { return idCategoria; } public String getId() { return id; } public String getNome() { return nome; } public String getDescricao() { return descricao; } public String getValor() { return valor; } public String getFoto() { return foto; } }
true
a5af73e215675f1db12a7098438cffb8fa633637
Java
Jerry7379/PIE
/src/main/java/com/sjcl/zrsy/domain/dto/LogisticsOperation.java
UTF-8
2,176
2.421875
2
[]
no_license
package com.sjcl.zrsy.domain.dto; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.Digits; //运输数据 public class LogisticsOperation { @Length(min = 7,max = 7,message = "车牌号长度为7") private String carId; @Digits(integer = 99,fraction = 99,message = "温度格式错误") private double temperature; @Digits(integer = 99,fraction = 99,message = "湿度格式错误") private double humidity; private String location; private String transportTime; @Digits(integer = 99,fraction = 99,message = "CO2格式错误") private double co2; @Length(min = 13,max = 13,message = "猪ID长度为13") private String id; public LogisticsOperation(String carId, double temperature, double humidity, String location, String transportTime, double co2, String id) { this.carId = carId; this.temperature = temperature; this.humidity = humidity; this.location = location; this.transportTime = transportTime; this.co2 = co2; this.id = id; } public LogisticsOperation() { } public String getCarId() { return carId; } public void setCarId(String carId) { this.carId = carId; } public double getTemperature() { return temperature; } public void setTemperature(double temperature) { this.temperature = temperature; } public double getHumidity() { return humidity; } public void setHumidity(double humidity) { this.humidity = humidity; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getTransportTime() { return transportTime; } public void setTransportTime(String transportTime) { this.transportTime = transportTime; } public double getCo2() { return co2; } public void setCo2(double co2) { this.co2 = co2; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
true
ed2bd7e0f418a5eafaf937fba54fe589eabd6387
Java
dungviettran89/s34j
/s34j-test/src/test/java/us/cuatoi/s34j/sbs/test/TestConfigurator.java
UTF-8
6,093
1.734375
2
[ "Apache-2.0" ]
permissive
package us.cuatoi.s34j.sbs.test; import com.github.sardine.Sardine; import com.github.sardine.SardineFactory; import com.google.gson.Gson; import io.minio.MinioClient; import io.minio.errors.*; import org.apache.commons.vfs2.VFS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; import org.xmlpull.v1.XmlPullParserException; import us.cuatoi.s34j.sbs.core.operation.AvailabilityUpdater; import us.cuatoi.s34j.sbs.core.store.imap.ImapConfiguration; import us.cuatoi.s34j.sbs.core.store.model.ConfigurationModel; import us.cuatoi.s34j.sbs.core.store.model.ConfigurationRepository; import us.cuatoi.s34j.sbs.core.store.nio.NioConfiguration; import us.cuatoi.s34j.sbs.core.store.sardine.SardineConfiguration; import us.cuatoi.s34j.test.TestHelper; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import static com.upplication.s3fs.AmazonS3Factory.*; import static java.nio.file.Files.createTempDirectory; import static org.apache.commons.lang3.StringUtils.isNotBlank; @Service public class TestConfigurator { private static final Logger logger = LoggerFactory.getLogger(TestConfigurator.class); @Autowired private AvailabilityUpdater availabilityUpdater; @Autowired private ConfigurationRepository configurationRepository; @Value("${test.sardine.url:}") private String webDavUrl; @Value("${test.sardine.user:}") private String webDavUser; @Value("${test.sardine.password:}") private String webDavPassword; @Value("${test.imap.url:}") private String imapUrl; @Value("${test.imap.user:}") private String imapUser; @Value("${test.imap.email:}") private String imapEmail; @Value("${test.imap.password:}") private String imapPassword; private Path tempDirectory; @PostConstruct void start() throws IOException, InvalidPortException, InvalidEndpointException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, ErrorResponseException, NoResponseException, InvalidBucketNameException, XmlPullParserException, InternalException, RegionConflictException { logger.info("start()"); tempDirectory = createTempDirectory("sbs-test-"); logger.info("stop() Created tempDirectory " + tempDirectory); String nioTempFolder = tempDirectory.toUri().toString(); Files.createDirectory(tempDirectory.resolve("nio-1")); createStore("nio-1", "nio", nioTempFolder + "nio-1/"); Files.createDirectory(tempDirectory.resolve("nio-2")); createStore("nio-2", "nio", nioTempFolder + "nio-2/"); createStore("vfs-1", "vfs", "ram://vfs-1/"); VFS.getManager().resolveFile(URI.create("ram://vfs-1/")).createFolder(); createStore("vfs-2", "vfs", "tmp://vfs-2/"); VFS.getManager().resolveFile(URI.create("tmp://vfs-2/")).createFolder(); createStore("vfs-3", "vfs", "ram://vfs-3/"); VFS.getManager().resolveFile(URI.create("ram://vfs-3/")).createFolder(); if (isNotBlank(webDavUrl)) { String url = webDavUrl + "/sardine-1/"; Sardine sardine = SardineFactory.begin(webDavUser, webDavPassword); if (!sardine.exists(url)) { sardine.createDirectory(url); } createStore("sardine", "sardine", url, new SardineConfiguration().setUser(webDavUser).setPassword(webDavPassword)); //Test minio s3 store String minioKey = TestHelper.DEFAULT_KEY; String minioSecret = TestHelper.DEFAULT_SECRET; String minioHost = "play.minio.io:9000"; String minioBucket = "sbs-test"; MinioClient client = new MinioClient("https://" + minioHost, minioKey, minioSecret); if (!client.bucketExists(minioBucket)) { logger.info("start() Created bucket " + minioBucket); client.makeBucket(minioBucket); } NioConfiguration config = new NioConfiguration(); config.put(ACCESS_KEY, minioKey); config.put(SECRET_KEY, minioSecret); config.put(SIGNER_OVERRIDE, "AWSS3V4SignerType"); config.put(PATH_STYLE_ACCESS, "true"); config.put("totalBytes", String.valueOf(1024L * 1024 * 1024)); createStore("nio-s3-1", "nio", "s3://" + minioHost + "/" + minioBucket + "/test/", config); } if (isNotBlank(imapUrl)) { ImapConfiguration imapConfiguration = new ImapConfiguration(); imapConfiguration.setEmail(imapEmail); imapConfiguration.setFolder("test"); imapConfiguration.setUser(imapUser); imapConfiguration.setPassword(imapPassword); imapConfiguration.setTotalBytes(512L * 1024 * 1024 * 1024); createStore("imap-1", "imap", imapUrl, imapConfiguration); } availabilityUpdater.updateAll(); } private void createStore(String name, String type, String uri) { createStore(name, type, uri, null); } private void createStore(String name, String type, String uri, Object config) { ConfigurationModel store = new ConfigurationModel(); store.setName(name); store.setType(type); store.setUri(uri); store.setJson(new Gson().toJson(config)); configurationRepository.save(store); logger.info("createStore() name=" + name); logger.info("createStore() uri=" + store.getUri()); } @PreDestroy void stop() { configurationRepository.deleteAll(); logger.info("stop() Delete tempDirectory " + tempDirectory); FileSystemUtils.deleteRecursively(tempDirectory.toFile()); } }
true
fc98586d6ebcc41fa6715a718156b42f02f04cf1
Java
jose2007kj/LearningAndroid
/jose2007kj/src/main/java/com/example/jose2007kj/learningandroid/jose2007kj/NamesFragment.java
UTF-8
4,932
2.15625
2
[]
no_license
package com.example.jose2007kj.learningandroid.jose2007kj; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class NamesFragment extends Fragment { // test.put("id:",1); /**private Map<Integer, String> r_data = new HashMap<Integer, String>() {{ put(R.drawable.mercilo, "Mercilo plays for Brazil"); put(R.drawable.messi, "Messi plays for Argentina"); put(R.drawable.ronaldho, "Ronaldo plays for Portugal"); put(R.drawable.neymar, "Neymar plays for brazil"); put(R.drawable.baichung, "Bhutia played for India"); put(R.drawable.vijayan, "IM Vijayan played for India"); put(R.drawable.sunil, "Chetari played for India"); put(R.drawable.zidane, "Zidane played for France"); put(R.drawable.zidane, "Zidane played for France"); }};**/ private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; public NamesFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { GlobalVariables players = ((GlobalVariables)getActivity().getApplicationContext()); View view = inflater.inflate(R.layout.names_fragment, container, false); mRecyclerView = view.findViewById(R.id.recycler_view); mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLayoutManager); JSONArray recycler_array=new JSONArray(); /** JSONObject marcelo=new JSONObject(); JSONObject ronoldo=new JSONObject(); JSONObject zidane =new JSONObject(); JSONObject vijanyan=new JSONObject(); JSONObject bhutia=new JSONObject(); JSONObject chetari =new JSONObject(); try { marcelo.put("id", "https://en.wikipedia.org/wiki/Marcelo_(footballer,_born_1988)"); marcelo.put("image", R.drawable.mercilo); marcelo.put("desc", "Mercilo plays for Brazil"); }catch(JSONException e) { // TODO Auto-generated catch block Log.d("","e"+e); e.printStackTrace(); } recycler_array.put(marcelo); try { ronoldo.put("id", "https://it.wikipedia.org/wiki/Cristiano_Ronaldo"); ronoldo.put("image", R.drawable.ronaldho); ronoldo.put("desc", "Ronaldho plays for portughese"); }catch(JSONException e) { // TODO Auto-generated catch block Log.d("","e"+e); e.printStackTrace(); } recycler_array.put(ronoldo); try { zidane.put("id", "https://en.wikipedia.org/wiki/Zinedine_Zidane"); zidane.put("image", R.drawable.zidane); zidane.put("desc", "Zidane plays for France"); }catch(JSONException e) { // TODO Auto-generated catch block Log.d("","e"+e); e.printStackTrace(); } recycler_array.put(zidane); try { vijanyan.put("id", "https://en.wikipedia.org/wiki/I._M._Vijayan"); vijanyan.put("image", R.drawable.vijayan); vijanyan.put("desc", "vijayan played for India"); }catch(JSONException e) { // TODO Auto-generated catch block Log.d("","e"+e); e.printStackTrace(); } recycler_array.put(vijanyan); try { chetari.put("id", "https://en.wikipedia.org/wiki/Sunil_Chhetri"); chetari.put("image", R.drawable.sunil); chetari.put("desc", "Chettari plays for India"); }catch(JSONException e) { // TODO Auto-generated catch block Log.d("","e"+e); e.printStackTrace(); } recycler_array.put(chetari); try { bhutia.put("id", "https://en.wikipedia.org/wiki/Bhaichung_Bhutia"); bhutia.put("image", R.drawable.baichung); bhutia.put("desc", "bhutia played for India"); }catch(JSONException e) { // TODO Auto-generated catch block Log.d("","e"+e); e.printStackTrace(); } recycler_array.put(bhutia);**/ recycler_array = players.get_players_info(); mAdapter = new GridAdapter(recycler_array); mRecyclerView.setAdapter(mAdapter); return view; } }
true
6a0e69209d432cf633095858c08c588e5b5d7eb5
Java
epiphany27/iPoli-android
/app/src/main/java/io/ipoli/android/quest/data/QuestReminder.java
UTF-8
1,727
2.375
2
[ "MIT" ]
permissive
package io.ipoli.android.quest.data; import io.ipoli.android.reminder.data.Reminder; /** * Created by Venelin Valkov <[email protected]> * on 12/24/16. */ public class QuestReminder { private Long minutesFromStart; private String questId; private String questName; private Long start; private Integer notificationId; private String message; public QuestReminder() { } public QuestReminder(Quest quest, Reminder reminder) { setQuestName(quest.getName()); setQuestId(quest.getId()); setMinutesFromStart(reminder.getMinutesFromStart()); setNotificationId(reminder.getNotificationId()); setStart(reminder.getStart()); setMessage(reminder.getMessage()); } public Long getMinutesFromStart() { return minutesFromStart; } public void setMinutesFromStart(Long minutesFromStart) { this.minutesFromStart = minutesFromStart; } public String getQuestId() { return questId; } public void setQuestId(String questId) { this.questId = questId; } public String getQuestName() { return questName; } public void setQuestName(String questName) { this.questName = questName; } public Long getStart() { return start; } public void setStart(Long startTime) { this.start = startTime; } public Integer getNotificationId() { return notificationId; } public void setNotificationId(Integer notificationId) { this.notificationId = notificationId; } public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } }
true
cc0f0e01a96c8e05555fed3316443d5b5c4afc0d
Java
bellmit/Intkr_SAAS_BEIDEN
/com/intkr/saas/dao/ad/impl/AdvertisementPositionDAOImpl.java
UTF-8
716
1.867188
2
[ "Apache-2.0" ]
permissive
package com.intkr.saas.dao.ad.impl; import com.intkr.saas.dao.BaseDAOImpl; import org.springframework.stereotype.Repository; import com.intkr.saas.dao.ad.AdvertisementPositionDAO; import com.intkr.saas.domain.dbo.ad.AdvertisementPositionDO; /** * 广告位 * * @table advertisement_position * * @author Beiden * @date 2020-11-04 09:37:22 * @version 1.0 */ @Repository("AdvertisementPositionDAO") public class AdvertisementPositionDAOImpl extends BaseDAOImpl<AdvertisementPositionDO> implements AdvertisementPositionDAO { public String getNameSpace() { return "advertisementPosition"; } private String dataSourceName = "cms"; public String getDataSourceName() { return dataSourceName; } }
true