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
13268ddb8f9ff1ef3004c72b6a2be84b928f678a
Java
Praxiology/springCloudLearn
/user-server/src/main/java/com/step/springcloud/user/HytrixSchedual.java
UTF-8
273
1.960938
2
[]
no_license
package com.step.springcloud.user; import org.springframework.stereotype.Component; @Component public class HytrixSchedual implements FeginHi { @Override public String sayHiFromClientOne(String name) { return name + "sorry ! 请求备用接口"; } }
true
d61adedb955d3bd5ad3d3956b8d401ba29f22405
Java
senka97/payment-concentrator
/pcc-service/src/main/java/team16/pccservice/model/PaymentRequest.java
UTF-8
964
2.25
2
[]
no_license
package team16.pccservice.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import team16.pccservice.enums.Status; import javax.persistence.*; import java.time.LocalDateTime; @NoArgsConstructor @AllArgsConstructor @Getter @Setter @Entity public class PaymentRequest { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private Long acquirerOrderID; // id oredr-a kreiranog u banci prodavca - Acquirer private LocalDateTime acquirerTimestamp; private Long issuerOrderID; // id oredr-a kreirane u banci kupca - Issuer private LocalDateTime issuerTimestamp; private Long merchantOrderId; @Column private Long paymentId; @ManyToOne private Bank acquirerBank; @ManyToOne private Bank issuerBank; private LocalDateTime createTime; @Column @Enumerated(EnumType.STRING) private Status status; }
true
37c410188ebbbc8a23460edceb0ca2ea9a296a39
Java
Darshan-C-S/Darshan-C-S
/assignment 2/project 1/src/Darshan/class3/calculate.java
UTF-8
448
3.15625
3
[]
no_license
package Darshan.class3; class cal{ public void add (int n ,int m){ System.out.println(n+m); } public static void multiply (int n ,int m){ System.out.println(n*m); } public void sub (int n , int m){ System.out.println(n-m); } } public class calculate { public static void main(String[] args) { cal c = new cal(); c.add(2,4); c.multiply(3,5); c.sub(8,2); } }
true
439d1f0458d4bbc674ad05b479fcd4ecbf828bb1
Java
vierri1/ya.money.test
/src/main/java/ya/money/test/exception/ErrorResponse.java
UTF-8
496
2.078125
2
[]
no_license
package ya.money.test.exception; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Структура общего ответа об ошибке */ @Data @AllArgsConstructor @NoArgsConstructor public class ErrorResponse { private String errorMessage; private String details; private String path; public ErrorResponse(String errorMessage, String path) { this.errorMessage = errorMessage; this.path = path; } }
true
43005a0edefcde076781f0da03dd939e3b1296ac
Java
Azamat753/MasterClassAndroid1
/app/src/main/java/com/lawlett/masterclassandroid1/ui/recycler_fragmen/IUpdateDataListener.java
UTF-8
122
1.585938
2
[]
no_license
package com.lawlett.masterclassandroid1.ui.recycler_fragmen; public interface IUpdateDataListener { void update(); }
true
5dd1512fc069b538092de0e3b8f04407245e699b
Java
ksksks2222/pl-workspace
/plfx/plfx-jp/plfx-jp-yxgjclient/src/main/java/plfx/yxgjclient/pojo/param/QueryAirRulesResult.java
UTF-8
363
1.726563
2
[]
no_license
package plfx.yxgjclient.pojo.param; /** * 出票规则返回参数列表 * @author guotx * 2015-07-06 */ public class QueryAirRulesResult { /** * 出票规则 */ private String resultData; public String getResultData() { return resultData; } public void setResultData(String resultData) { this.resultData = resultData; } }
true
bd53832b5d2a78c94688dc6acb85e3878af2371e
Java
vreyes23/javaParser
/target/generated-sources/antlr4/BlockSimpleGenerator.java
UTF-8
2,124
2.6875
3
[]
no_license
import java.util.ArrayList; import java.util.List; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; public class BlockSimpleGenerator implements BlockCreator { public BlockSimpleGenerator(){} @override public AST createTree(AST tree){ return tree; } public BlockNode generateExpandedCFG(AST ast) { StringBuilder builder = new StringBuilder(); int tokenType = -1; String tokenContent = ""; BlockNode expandedCFG = new BlockNode ("0", "", null); //AST ast = this; List<AST> firstStack = new ArrayList<>(); firstStack.add(ast); List<List<AST>> childListStack = new ArrayList<>(); childListStack.add(firstStack); while (!childListStack.isEmpty()) { List<AST> childStack = childListStack .get(childListStack.size() - 1); if (childStack.isEmpty()) { childListStack.remove(childListStack.size() - 1); } else { ast = childStack.remove(0); String caption; if (ast.getPayload() instanceof Token) { Token token = (Token) ast.getPayload(); caption = String.format("TOKEN[type: %s, text: %s]", token.getType(), token.getText().replace("\n", "\\n")); tokenType = token.getType(); tokenContent = token.getText(); expandedCFG.getTail().setExit1(new BlockNode(""+tokenType, tokenContent, null)); } else { caption = String.valueOf(ast.getPayload()); } String indent = ""; for (int i = 0; i < childListStack.size() - 1; i++) { indent += (childListStack.get(i).size() > 0) ? "| " : " "; } //this is what appends to builder builder.append(indent) .append(childStack.isEmpty() ? "'- " : "|- ") .append(caption).append("\n"); if (ast.children.size() > 0) { List<AST> children = new ArrayList<>(); for (int i = 0; i < ast.children.size(); i++) { children.add(ast.children.get(i)); } childListStack.add(children); } } } //return builder.toString(); return expandedCFG; } }
true
3c172185143ae3745e741fa2a78f4db54c01573e
Java
whc1998/SourceCodeTest
/hotfix/src/main/java/com/example/whc/hotfix/FixUtil/FixDexUtils.java
UTF-8
4,253
2.640625
3
[]
no_license
package com.example.whc.hotfix.FixUtil; import android.content.Context; import android.util.Log; import android.widget.Toast; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.HashSet; import dalvik.system.DexClassLoader; import dalvik.system.PathClassLoader; /** * Created by WSY on 2018/4/9. */ public class FixDexUtils { private static HashSet<File> loadedDex = new HashSet<>(); static { loadedDex.clear(); } public static void loadFixedDex(Context context) { if (context == null) { return; } File fileDir = context.getDir(MyConstants.DEX_DIR, Context.MODE_PRIVATE); File[] files = fileDir.listFiles(); for (File file : files) { Log.d("test",file.getName()); if (file.getName().startsWith("MyTestClass") && file.getName().endsWith(".dex")) { loadedDex.add(file); } } //和之前apk里面的dex合并 doDexInject(context, fileDir, loadedDex); Toast.makeText(context, "修复成功", Toast.LENGTH_SHORT).show(); } private static void doDexInject(Context context, File filesDir, HashSet<File> loadedDex) { String optimizeDir = filesDir.getAbsolutePath() + File.separator + "opt_dex"; File fopt = new File(optimizeDir); if (!fopt.exists()) { fopt.mkdirs(); } //加载应用程序的dex //1.拿到系统的dex PathClassLoader pathloader = (PathClassLoader) context.getClassLoader(); //2.拿到自己的dex for (File dex : loadedDex) { DexClassLoader classLoader = new DexClassLoader(dex.getAbsolutePath(), fopt.getAbsolutePath(), null, pathloader); //合并 /** * BaseDexClassLoader-->DexPathList * DexPathList-->Element[] dexElements * 把Element[] dexElements改了一一合并 */ try { Object dexObj = getPathList(classLoader); Object pathObj = getPathList(pathloader); Object mDexElementsList=getDexElements(dexObj); Object pathDexElementsList=getDexElements(pathObj); //合并 Object dexElements = combineArray(mDexElementsList, pathDexElementsList); //需要重新赋值给Element[] dexElements Object pathList=getPathList(pathloader); setField(pathList,pathList.getClass(),"dexElements",dexElements); } catch (Exception e) { e.printStackTrace(); } } } private static Object getDexElements(Object dexObj) throws NoSuchFieldException, IllegalAccessException { return getField(dexObj,dexObj.getClass(),"dexElements"); } private static Object getField(Object obj, Class<?> cl, String field) throws NoSuchFieldException, IllegalAccessException { //获取到baseDexClassLoader里面名字叫做field的成员 Field localField = cl.getDeclaredField(field); localField.setAccessible(true); return localField.get(obj); } private static void setField(Object obj,Class<?> cl,String field,Object value) throws NoSuchFieldException, IllegalAccessException { Field localField=cl.getDeclaredField(field); localField.setAccessible(true); localField.set(obj,value); } private static Object getPathList(Object baseDexClassLoader) throws Exception { return getField(baseDexClassLoader,Class.forName("dalvik.system.BaseDexClassLoader"),"pathList"); } //两个集合的合并 private static Object combineArray(Object arryLhs,Object arryRhs){ Class<?> localClass=arryLhs.getClass().getComponentType(); int i= Array.getLength(arryLhs); int j=i+Array.getLength(arryRhs); Object result=Array.newInstance(localClass,j); for (int k=0;k<j;++k){ if (k<i){ Array.set(result,k,Array.get(arryLhs,k)); }else{ Array.set(result,k,Array.get(arryRhs,k-i)); } } return result; } }
true
0bb2ee98b0e9e32abfe9b30496c84ee8ceda589a
Java
yhuiyang/my-test-apps
/AndroidProjects/GNHelper/src/com/yhlab/guessnumberhelper/guess/chooser/OneTwoThreeFourChooser.java
UTF-8
2,758
2.640625
3
[]
no_license
package com.yhlab.guessnumberhelper.guess.chooser; import java.util.Random; import android.util.Log; import com.yhlab.guessnumberhelper.guess.ChooserFactory; import com.yhlab.guessnumberhelper.guess.GuessTreeNode; import com.yhlab.guessnumberhelper.guess.IChooserCreater; import com.yhlab.guessnumberhelper.guess.IGuessChooser; import com.yhlab.guessnumberhelper.guess.Utility; public class OneTwoThreeFourChooser implements IGuessChooser { static { ChooserFactory factory = ChooserFactory.getInstance(); factory.registerChooser("OneTwoThreeFour", new Builder()); } private static final String TAG = "OneTwoThreeFourChooser"; private Random random; private int candidate[]; public OneTwoThreeFourChooser(Random random) { if (random == null) throw new NullPointerException(); this.random = random; } public int nextGuess(GuessTreeNode node) { if (this.candidate == null) { this.candidate = Utility.generateCandidates( node.getDigitCount(), node.getSymbolCount()); } if (node.size() <= candidate.length / 1000) return node.getNumber(0); int index = 0; int digitCount = node.getDigitCount(); int symbolCount = node.getSymbolCount(); int depth = node.getDepth(); switch (depth) { case 1: case 2: for (int d = 0; d < digitCount - 1; d++) { int tempProduct = 1; int symbol = symbolCount; for (int d2 = d; d2 < digitCount - 1; d2++) { tempProduct *= (symbol - d2 - 1); } index += tempProduct; } index++; if (depth == 2) { index *= (digitCount + 1); } break; default: index = random.nextInt(candidate.length); break; } return candidate[index]; } public String toString() { String name = this.getClass().getName(); int index = name.lastIndexOf('.'); return index < 0 ? name : name.substring(index + 1); } private static class Builder implements IChooserCreater { public IGuessChooser createChooser(String[] argv) { long seed = argv.length == 0 ? System.currentTimeMillis() : Long.parseLong(argv[0]); Random random = new Random(seed); IGuessChooser chooser = new OneTwoThreeFourChooser(random); Log.d(TAG, chooser + " created with seed " + seed); return chooser; } } }
true
b34f84c9f27d46cff19a835dfb7f7ee1b4ab3940
Java
Fernando-belitama/Sistema-de-Gestion-ISTER
/src/ec/edu/ister/vista/docenteAdmin/MateriaAdmin/EditarMateria.java
UTF-8
10,482
2.03125
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 ec.edu.ister.vista.docenteAdmin.MateriaAdmin; import ec.edu.ister.controlador.Coordinador; /** * * @author FERNANDO */ public class EditarMateria extends javax.swing.JPanel { Coordinador coordinador; public EditarMateria(Coordinador coord) { initComponents(); coordinador=coord; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextField7 = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel2.setFont(new java.awt.Font("Century Schoolbook", 1, 36)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("EDICIÓN MATERIA"); jLabel11.setFont(new java.awt.Font("Century Schoolbook", 1, 14)); // NOI18N jLabel11.setText("Limpiar"); jLabel3.setText("RELOJ"); jTextField7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField7ActionPerformed(evt); } }); jLabel12.setFont(new java.awt.Font("Century Schoolbook", 1, 14)); // NOI18N jLabel12.setText("Guardar"); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/LogoSinBase.png"))); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/LogoSinFonfoRumi.png"))); // NOI18N jTextField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField3ActionPerformed(evt); } }); jLabel10.setFont(new java.awt.Font("Century Schoolbook", 1, 12)); // NOI18N jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel10.setText("CODIGO MATERIA"); jLabel5.setFont(new java.awt.Font("Century Schoolbook", 1, 12)); // NOI18N jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel5.setText("NOMBRE MATERIA"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(86, 86, 86) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(135, 135, 135) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(573, 573, 573) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(454, 454, 454) .addComponent(jLabel11) .addGap(232, 232, 232) .addComponent(jLabel12) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 683, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(300, 300, 300)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(76, 76, 76) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(114, 114, 114)) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(41, 41, 41) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jLabel12)) .addGap(32, 32, 32) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void jTextField7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField7ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField7ActionPerformed private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField3ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField7; // End of variables declaration//GEN-END:variables }
true
7d074fff114c5777e57de8248184b779e3d4a249
Java
vcaibis/Nautischool
/app/src/main/java/ch/hevs/nautischool/LoginActivity.java
UTF-8
3,464
2.25
2
[]
no_license
package ch.hevs.nautischool; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import ch.hevs.nautischool.xmpp.LocalBinder; import ch.hevs.nautischool.xmpp.MyService; import ch.hevs.nautischool.xmpp.MyXMPP; import ch.hevs.nautischool.xmpp.SettingsPrefs; public class LoginActivity extends AppCompatActivity { EditText username ; EditText password ; private static final String TAG = "LoginActivity"; private boolean mBounded; private MyService mService; private final ServiceConnection mConnection = new ServiceConnection() { @SuppressWarnings("unchecked") @Override public void onServiceConnected(final ComponentName name, final IBinder service) { mService = ((LocalBinder<MyService>) service).getService(); mBounded = true; Log.d(TAG, "onServiceConnected"); } @Override public void onServiceDisconnected(final ComponentName name) { mService = null; mBounded = false; Log.d(TAG, "onServiceDisconnected"); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //Define variables username = findViewById(R.id.edit_text_username); password = findViewById(R.id.edit_text_password); SettingsPrefs settings = new SettingsPrefs(this); username.setText(settings.getUser()); password.setText(settings.getPassword()); } /** * Function to log the user * @param view */ public void login(View view) { if(testLogin()){ startActivity(new Intent(LoginActivity.this, mainActivity.class)); } } /** * Function to test the EditText values * And Start the BindService * @return false if empty */ private boolean testLogin() { String sUsername = username.getText().toString(); String sPassword = password.getText().toString(); if(sUsername.isEmpty()){ username.setError("Enter a username"); return false; } if(sPassword.isEmpty()){ password.setError("Enter a password"); return false; } //Set the preferences SettingsPrefs settings = new SettingsPrefs(this); settings.setUser(sUsername); settings.setPassword(sPassword); settings.save(); // launch the service doBindService(); return true; } public void cancel(View view) { doUnbindService(); MyXMPP.instance = null; MyXMPP.instanceCreated = false; } @Override protected void onDestroy() { super.onDestroy(); doUnbindService(); } void doBindService() { bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE); } void doUnbindService() { if (mConnection != null) { unbindService(mConnection); } } public MyService getmService() { return mService; } }
true
7b262f97166db1ffaae862dccd4cba14c3ec9121
Java
mhsilva/ScriptGenerator
/src/main/java/com/mhf/script/generator/util/SaveProjectHelper.java
UTF-8
628
2.1875
2
[]
no_license
package com.mhf.script.generator.util; import java.io.FileWriter; import java.io.IOException; import com.google.gson.Gson; public class SaveProjectHelper { public void generateProject(ScriptGeneratorModel scriptGeneratorModel) throws IOException { Gson gson = new Gson(); String json = gson.toJson(scriptGeneratorModel); Executor exec = new Executor(); FileWriter writer = new FileWriter(exec.createOutputFile(scriptGeneratorModel.getFilePath(), scriptGeneratorModel.getScriptName() + "_PROJECT", ".json")); writer.write(json); writer.close(); } }
true
d1772cfdf2ec4836b9140188f3519461b2d71ddb
Java
devsops/Poc_jenkins
/libraries/android/ipsadmin/src/main/java/com/bosch/pai/ipsadmin/bearing/core/operation/processor/DetectionRequestProcessor.java
UTF-8
1,449
2.046875
2
[]
no_license
package com.bosch.pai.ipsadmin.bearing.core.operation.processor; import com.bosch.pai.ipsadmin.bearing.core.operation.detection.location.LocationDetectorUtil; import com.bosch.pai.ipsadmin.bearing.core.operation.detection.site.SiteDetectorUtil; import com.bosch.pai.bearing.event.Event; import com.bosch.pai.bearing.event.Sender; /** * The type Detection request processor. */ abstract class DetectionRequestProcessor implements Runnable { /** * The Request id. */ protected String requestID; /** * The Event. */ protected Event event; /** * The Sender. */ protected Sender sender; /** * The Location detector util. */ protected LocationDetectorUtil locationDetectorUtil; /** * The Site detector util. */ protected SiteDetectorUtil siteDetectorUtil; /** * The Thresh detector util. */ //protected ThreshDetectorUtil threshDetectorUtil; /** * Instantiates a new Detection request processor. * * @param requestID the request id * @param event the event * @param sender the sender */ protected DetectionRequestProcessor(String requestID, Event event, Sender sender) { this.requestID = requestID; this.event = event; this.sender = sender; this.locationDetectorUtil = new LocationDetectorUtil(); this.siteDetectorUtil = new SiteDetectorUtil(); } }
true
6384edd7a3792e14df99a094bcc1140f18659055
Java
max40a/GeekHubHomeWorks
/HomeWork3/src/Main.java
UTF-8
1,820
3.609375
4
[]
no_license
import products.interfaces.Product; import inventory.Inventory; import inventory.InventoryManager; import products.creator.ProductCreator; import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { Inventory<Product> inventory = new Inventory<>(); Product product; String productName; double prise; boolean isExit = true; do { System.out.println("Add the product to your inventory:\n\t\"Bread\"\n\t" + "\"Cheese\"\n\t\"Sausage\"\n\t\"q\" - Quit and print result.\n"); System.out.print("Chose : "); do { productName = scanner.next(); } while (!validateInputString(productName)); if (productName.equals("q")) { isExit = false; } else { System.out.print("Enter the " + productName + " prise : "); prise = scanner.nextDouble(); System.out.println(); product = ProductCreator.productCreate(productName, prise); if (product != null) { inventory.addProduct(product); } } } while (isExit); InventoryManager manager = new InventoryManager(inventory); System.out.println(manager.printResult()); } private static boolean validateInputString(String productName) { switch (productName) { case "Bread": case "Cheese": case "Sausage": case "q": return true; } System.out.println("Incorrect products. Permissible value : (Bread, Cheese, Sausage or \"q\" for exit and print result.)"); return false; } }
true
c0abff7b2775d2317f5ad5659e8872847751db59
Java
lineCode/quorum-ci
/Quorum3Plugins/ParserPlugin/src/plugins/quorum/Libraries/Language/Compile/Translate/JavaBytecodeFieldWriter.java
UTF-8
771
1.804688
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 plugins.quorum.Libraries.Language.Compile.Translate; import org.objectweb.asm.FieldVisitor; /** * * @author stefika */ public class JavaBytecodeFieldWriter { public java.lang.Object $me = null; private FieldVisitor visitor; /** * @return the visitor */ public FieldVisitor getFieldVisitor() { return visitor; } /** * @param visitor the visitor to set */ public void setFieldVisitor(FieldVisitor visitor) { this.visitor = visitor; } public void VisitEnd() { visitor.visitEnd(); } }
true
12ff34e14d720b956dd166235c7e0bfae79928f9
Java
wangxydhc/ProjectRes
/Spring_0100_AbstractOrientedPrograming/test/com/bjsxt/service/UserServiceTest.java
IBM852
605
2.09375
2
[]
no_license
package com.bjsxt.service; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.bjsxt.model.User; import com.bjsxt.spring.BeanFactory; import com.bjsxt.spring.ClassPathXmlApplicationContext; //ģspring public class UserServiceTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testAdd() throws Exception { BeanFactory factory=new ClassPathXmlApplicationContext(); UserService service=(UserService)factory.getBean("userService"); User u=new User(); service.add(u); } }
true
f0eb2d7bb7cea887ce8b30ccd9018a67baef293c
Java
SunShine993-Y/AppInfoSystem
/src/main/java/com/bdqn/controller/backend/BackendLoginController.java
UTF-8
1,114
2.0625
2
[]
no_license
package com.bdqn.controller.backend; import com.bdqn.pojo.BackendUser; import com.bdqn.service.backend.BackendUserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping("/manager") public class BackendLoginController { @Resource private BackendUserService backendUserService; @RequestMapping("/login") public String login(){ return "backendlogin"; } @RequestMapping("/dologin") public String doLogin(HttpServletRequest request, @RequestParam String userCode, @RequestParam String userPassword){ BackendUser backendUser = backendUserService.doLogin(userCode,userPassword); if(backendUser == null){ request.setAttribute("error","用户名或密码错误"); return "backendlogin"; } request.getSession().setAttribute("userSession",backendUser); return "backend/main"; } }
true
3776baf53e7526ecc72d64450dc4aa7f1a795ed9
Java
wangscript007/HaobeiBuiness
/baselib/src/main/java/com/netmi/baselibrary/utils/FastBundle.java
UTF-8
758
2.359375
2
[]
no_license
package com.netmi.baselibrary.utils; import android.os.Bundle; /** * 类描述: * 创建人:Simple * 创建时间:2017/12/27 11:13 * 修改备注: */ public class FastBundle { private Bundle bundle; public FastBundle() { bundle = new Bundle(); } public Bundle putInt(String key, int value) { bundle.putInt(key, value); return bundle; } public Bundle putString(String key, String value) { bundle.putString(key, value); return bundle; } public FastBundle put(String key, String value) { bundle.putString(key, value); return this; } public FastBundle put(String key, int value) { bundle.putInt(key, value); return this; } }
true
ee9774efea30e8ec0d42f05dfbd7d030f0d75eb8
Java
aaAsuna/wms
/wms/src/main/java/org/ricardo/wms/mapper/SystemMenuMapper.java
UTF-8
733
1.992188
2
[]
no_license
package org.ricardo.wms.mapper; import org.apache.ibatis.annotations.Param; import org.ricardo.wms.domain.SystemMenu; import org.ricardo.wms.query.QueryObject; import java.util.List; import java.util.Map; public interface SystemMenuMapper { int deleteByPrimaryKey(Long id); int insert(SystemMenu record); SystemMenu selectByPrimaryKey(Long id); List<SystemMenu> selectAll(); int updateByPrimaryKey(SystemMenu record); int queryForCount(QueryObject qo); List<SystemMenu> queryForList(QueryObject qo); List<Map<String, Object>> loadMenusByParentSn(String parentSn); List<Map<String, Object>> loadMenusByParentSnAndEmpId(@Param("parentSn") String parentSn, @Param("EmpId") Long EmpId); }
true
634499dd2d89ab990f35ae038497beb9b6287704
Java
studyferko/java-orders
/src/main/java/com/lambda/orders/services/CustomerServiceImpl.java
UTF-8
1,617
2.390625
2
[ "MIT" ]
permissive
package com.lambda.orders.services; import com.lambda.orders.repos.CustomerRepository; import com.lambda.orders.repos.OrderRepository; import com.lambda.orders.models.Agent; import com.lambda.orders.models.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.ArrayList; @Transactional @Service(value="customerService") public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerRepository customerRepo; @Autowired private OrderRepository orderRepo; @Override public ArrayList<Customer> findAll() { ArrayList<Customer> customers = new ArrayList<>(); customerRepo.findAll().iterator().forEachRemaining(c -> customers.add(c)); for (Customer c: customers) { c.setOrders(orderRepo.findAllByCustomer(c)); } return customers; } @Override public Customer findCustomerByName(String custName) { return customerRepo.findCustomerByCustName(custName); } @Override public ArrayList<Customer> findAllByAgent(Agent agent) { return null; } @Transactional @Override public Customer save(Customer customer) { customerRepo.save(customer); return customerRepo.findCustomerByCustName(customer.getCustName()); } @Transactional @Override public Customer update(Customer customer, long custCode) { return null; } @Override public void delete(long custCode) { } }
true
0ae951428854916e650dbadd51b3a4c2f0b4b7f6
Java
DrafaKiller/BrokenBlock
/src/main/java/com/drafakiller/brokenblock/commands/ToggleCommand.java
UTF-8
1,733
2.859375
3
[]
no_license
package com.drafakiller.brokenblock.commands; import com.drafakiller.brokenblock.BrokenBlock; import com.drafakiller.brokenblock.Message; import com.drafakiller.commandmanager.SubCommand; import com.drafakiller.commandmanager.SubCommandResult; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class ToggleCommand extends SubCommand { public ToggleCommand() { this.name = "toggle"; this.info = "Toggles whether the plugin is enabled or disabled."; this.usage = new String[][] { { "on", "off" } }; } public Boolean onCommand (@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, SubCommandResult result) { BrokenBlock plugin = (BrokenBlock) this.getPlugin(); if (sender instanceof Player && result != null && plugin != null) { Player player = (Player) sender; if (result.isUsage) { switch (result.getCurrentArgument()) { case "on": if (!plugin.isPlayerEnabled(player)) { plugin.togglePlayer(player, true); player.sendMessage(Message.TOGGLED_ON); } else { player.sendMessage(Message.ALREADY_TOGGLED_ON); } return true; case "off": if (plugin.isPlayerEnabled(player)) { plugin.togglePlayer(player, false); player.sendMessage(Message.TOGGLED_OFF); } else { player.sendMessage(Message.ALREADY_TOGGLED_OFF); } return true; } } else { plugin.togglePlayer(player); if (plugin.isPlayerEnabled(player)) { player.sendMessage(Message.TOGGLED_ON); } else { player.sendMessage(Message.TOGGLED_OFF); } return true; } } return false; } }
true
849c8f67961d69aaa84c6217868c04fa6c77fe93
Java
pjsong/history-maven-top
/dbClient/src/test/java/bean/CodeList.java
UTF-8
1,352
2.09375
2
[]
no_license
package bean; import java.io.Serializable; import javax.persistence.*; import constants.DbInstanceId; import java.sql.Time; /** * The persistent class for the code_list database table. * */ @Entity(name="code_list") public class CodeList extends DbInstanceId{ private static final long serialVersionUID = 1L; private int rowId; private String category; private String code; private String name; private Time onMarketTime; public CodeList() { } @Id @Column(name = "rowId") @GeneratedValue(strategy=GenerationType.TABLE) public int getRowId() { return this.rowId; } public void setRowId(int rowId) { this.rowId = rowId; } @Column(name = "category") public String getCategory() { return this.category; } public void setCategory(String category) { this.category = category; } @Column(name = "code") public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } @Column(name = "name") public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "onMarketTime") public Time getOnMarketTime() { return this.onMarketTime; } public void setOnMarketTime(Time onMarketTime) { this.onMarketTime = onMarketTime; } }
true
0677590785d5fa56e5e9055cfdbba3fd50d28a65
Java
mevogn/advent-code-2016
/src/main/java/advent/PixelLighter.java
UTF-8
127
1.859375
2
[]
no_license
package advent; import java.util.List; public interface PixelLighter { int numberPixelsLit(List<String> instructions); }
true
f20ce6ca6b33ea9fa8b08e514ca2a76e514707ba
Java
yikai116/K_table
/app/src/main/java/com/exercise/p/k_table/model/AbstractLogin.java
UTF-8
2,431
2.25
2
[]
no_license
package com.exercise.p.k_table.model; import android.os.AsyncTask; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.List; import java.util.Map; /** * Created by p on 2017/2/8. */ public abstract class AbstractLogin extends AsyncTask<Void,Void,Boolean>{ String user_id; String user_psw; boolean internet = true; boolean psw = true; String cookie; /** * login 默认登录川大教务处 * @return 返回是否登录成功 */ boolean login(){ try { URL login_url = new URL("http://zhjw.scu.edu.cn/loginAction.do"); HttpURLConnection connection = (HttpURLConnection) login_url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(1000*5); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); String params = "zjh=" + URLEncoder.encode(user_id,"UTF-8") + "&mm=" + URLEncoder.encode(user_psw,"UTF-8"); os.write(params.getBytes()); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"GB2312")); String line; while ((line = reader.readLine()) != null) { if (line.contains("密码不正确")||line.contains("证件号不存在")){ psw = false; return false; } } // Log.i("Login","正确"); Map<String, List<String>> header = connection.getHeaderFields(); cookie = header.get("Set-Cookie").get(0); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); internet = false; return false; } return true; } AbstractLogin(String user_id, String user_psw){ this.user_id = user_id; this.user_psw = user_psw; } /** * 执行异步任务 */ public void run(){ this.execute(); } }
true
9cb10336a1960a8b079dd89691d868250638c8ae
Java
AltamashA/university-api
/My-University/src/main/java/com/restapi/myuniversityapi/courses/Course.java
UTF-8
1,085
2.53125
3
[]
no_license
package com.restapi.myuniversityapi.courses; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import com.restapi.myuniversityapi.topics.Topic; @Entity public class Course { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="student_id") private long id; private String name; @ManyToOne @Column (name="topicId") private Topic topic; public Topic getTopic() { return topic; } public void setTopic(Topic topic) { this.topic = topic; } public Course() { } public Course(long id, String name, Topic topic) { super(); this.id = id; this.name = name; this.topic = topic; } @Override public String toString() { return "Course [id=" + id + ", name=" + name + "]"; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
c3ff8f2ca3e697c378d1a5ff075b6ad59348d3bd
Java
Unidata/netcdf-java
/cdm-test-utils/src/main/java/ucar/unidata/util/test/CheckPointFeatureDataset.java
UTF-8
25,523
1.71875
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 1998-2020 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.unidata.util.test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.invoke.MethodHandles; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.ma2.DataType; import ucar.ma2.StructureData; import ucar.ma2.StructureMembers; import ucar.nc2.VariableSimpleIF; import ucar.nc2.constants.FeatureType; import ucar.nc2.ft.DsgFeatureCollection; import ucar.nc2.ft.FeatureDataset; import ucar.nc2.ft.FeatureDatasetFactoryManager; import ucar.nc2.ft.FeatureDatasetPoint; import ucar.nc2.ft.PointFeature; import ucar.nc2.ft.PointFeatureCC; import ucar.nc2.ft.PointFeatureCCC; import ucar.nc2.ft.PointFeatureCollection; import ucar.nc2.ft.ProfileFeature; import ucar.nc2.ft.ProfileFeatureCollection; import ucar.nc2.ft.StationProfileFeature; import ucar.nc2.ft.StationProfileFeatureCollection; import ucar.nc2.ft.StationTimeSeriesFeature; import ucar.nc2.ft.StationTimeSeriesFeatureCollection; import ucar.nc2.ft.TrajectoryProfileFeature; import ucar.nc2.ft.TrajectoryProfileFeatureCollection; import ucar.nc2.ft.point.CollectionInfo; import ucar.nc2.ft.point.DsgCollectionHelper; import ucar.nc2.time.CalendarDate; import ucar.nc2.time.CalendarDateRange; import ucar.nc2.time.CalendarDateUnit; import ucar.nc2.util.IOIterator; import ucar.nc2.write.Ncdump; import ucar.unidata.geoloc.EarthLocation; import ucar.unidata.geoloc.LatLonPoint; import ucar.unidata.geoloc.LatLonRect; import ucar.unidata.util.StringUtil2; /** Read and check a point feature dataset, return number of point features. */ public class CheckPointFeatureDataset { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static boolean showStructureData = false; private static boolean showAll = false; private final String location; private final FeatureType ftype; private final boolean show; public CheckPointFeatureDataset(String location, FeatureType ftype, boolean show) { this.location = location; this.ftype = ftype; this.show = show; } // return number of PointFeatures public int check() throws IOException { return checkPointFeatureDataset(location, ftype, show); } // return number of PointFeatures private int checkPointFeatureDataset(String location, FeatureType type, boolean show) throws IOException { File fileIn = new File(location); String absIn = fileIn.getCanonicalPath(); absIn = StringUtil2.replace(absIn, "\\", "/"); System.out.printf("================ TestPointFeatureCollection read %s %n", absIn); File cwd = new File("."); System.out.printf("**** CWD = %s%n", cwd.getAbsolutePath()); File f = new File(absIn); System.out.printf("**** %s = %s%n", f.getAbsolutePath(), f.exists()); Formatter out = new Formatter(); try (FeatureDataset fdataset = FeatureDatasetFactoryManager.open(type, location, null, out)) { if (fdataset == null) { System.out.printf("**failed on %s %n --> %s %n", location, out); assert false; } // FeatureDataset if (showAll) { System.out.printf("----------- testPointDataset getDetailInfo -----------------%n"); fdataset.getDetailInfo(out); System.out.printf("%s %n", out); } else { System.out.printf(" Feature Type %s %n", fdataset.getFeatureType()); } return checkPointFeatureDataset(fdataset, show); } } public static int checkPointFeatureDataset(FeatureDataset fdataset, boolean show) throws IOException { long start = System.currentTimeMillis(); int count = 0; CalendarDate d1 = fdataset.getCalendarDateStart(); CalendarDate d2 = fdataset.getCalendarDateEnd(); if ((d1 != null) && (d2 != null)) { Assert.assertTrue("calendar date min <= max", d1.isBefore(d2) || d1.equals(d2)); } List<VariableSimpleIF> dataVars = fdataset.getDataVariables(); Assert.assertNotNull("fdataset.getDataVariables()", dataVars); for (VariableSimpleIF v : dataVars) { Assert.assertNotNull(v.getShortName(), fdataset.getDataVariable(v.getShortName())); } // FeatureDatasetPoint Assert.assertTrue("fdataset instanceof FeatureDatasetPoint", fdataset instanceof FeatureDatasetPoint); FeatureDatasetPoint fdpoint = (FeatureDatasetPoint) fdataset; for (DsgFeatureCollection fc : fdpoint.getPointFeatureCollectionList()) { checkDsgFeatureCollection(fc); if (fc instanceof PointFeatureCollection) { PointFeatureCollection pfc = (PointFeatureCollection) fc; count = checkPointFeatureCollection(pfc, show); Assert.assertEquals("PointFeatureCollection getData count = size", count, pfc.size()); } else if (fc instanceof StationTimeSeriesFeatureCollection) { count = checkStationFeatureCollection((StationTimeSeriesFeatureCollection) fc); // testNestedPointFeatureCollection((StationTimeSeriesFeatureCollection) fc, show); } else if (fc instanceof StationProfileFeatureCollection) { count = checkStationProfileFeatureCollection((StationProfileFeatureCollection) fc, show); if (showStructureData) { showStructureData((StationProfileFeatureCollection) fc); } } else if (fc instanceof TrajectoryProfileFeatureCollection) { count = checkSectionFeatureCollection((TrajectoryProfileFeatureCollection) fc, show); } else if (fc instanceof ProfileFeatureCollection) { count = checkProfileFeatureCollection((ProfileFeatureCollection) fc, show); } else { count = checkOther(fc, show); } checkInfo(fc); } long took = System.currentTimeMillis() - start; System.out.printf(" nobs=%d took= %d msec%n", count, took); return count; } static void checkDsgFeatureCollection(DsgFeatureCollection dsg) throws IOException { String what = dsg.getClass().getName(); Assert.assertNotNull(what + " name", dsg.getName()); Assert.assertNotNull(what + " featureTYpe", dsg.getCollectionFeatureType()); Assert.assertNotNull(what + " timeUnit", dsg.getTimeUnit()); // Assert.assertNotNull(what + " altUnits", dsg.getAltUnits()); // Assert.assertNotNull(what + " extraVars", dsg.getExtraVariables()); } static void checkInfo(DsgFeatureCollection dsg) throws IOException { Assert.assertNotNull(dsg.getBoundingBox()); Assert.assertNotNull(dsg.getCalendarDateRange()); Assert.assertNotNull(dsg.size() > 0); } static int checkPointFeatureCollection(PointFeatureCollection pfc, boolean show) throws IOException { long start = System.currentTimeMillis(); int counts = 0; for (PointFeature pf : pfc) { checkPointFeature(pf, pfc.getTimeUnit()); counts++; } long took = System.currentTimeMillis() - start; if (show) { System.out.println(" testPointFeatureCollection subset count= " + counts + " full iter took= " + took + " msec"); } checkPointFeatureCollectionBB(pfc, show); return counts; } static int checkProfileFeatureCollection(ProfileFeatureCollection profileFeatureCollection, boolean show) throws IOException { long start = System.currentTimeMillis(); int count = 0; Set<String> profileNames = new HashSet<>(); for (ProfileFeature profile : profileFeatureCollection) { checkDsgFeatureCollection(profile); Assert.assertNotNull("ProfileFeature time", profile.getTime()); Assert.assertNotNull("ProfileFeature latlon", profile.getLatLon()); Assert.assertNotNull("ProfileFeature featureData", profile.getFeatureData()); Assert.assertTrue(!profileNames.contains(profile.getName())); profileNames.add(profile.getName()); // assert pf.getTime() != null; count += checkPointFeatureCollection(profile, show); } long took = System.currentTimeMillis() - start; if (show) { System.out.println( " testStationProfileFeatureCollection complete count= " + count + " full iter took= " + took + " msec"); } return count; } static int checkStationFeatureCollection(StationTimeSeriesFeatureCollection sfc) throws IOException { System.out.printf("--------------------------\nComplete Iteration for %s %n", sfc.getName()); int countStns = countLocations(sfc); // try a subset LatLonRect bb = sfc.getBoundingBox(); Assert.assertNotNull(bb); LatLonRect bb2 = new LatLonRect(bb.getLowerLeftPoint(), bb.getHeight() / 2, bb.getWidth() / 2); System.out.println(" BB Subset= " + bb2.toString2()); StationTimeSeriesFeatureCollection sfcSub = sfc.subset(bb2); int countSub = countLocations(sfcSub); Assert.assertTrue(countSub <= countStns); System.out.println(" nobs= " + sfcSub.size()); /* * test info * CollectionInfo info = new DsgCollectionHelper(sfc).calcBounds(); // sets internal values * Assert.assertNotNull(info); * CalendarDateRange dr = sfc.getCalendarDateRange(); * Assert.assertNotNull(dr); * Assert.assertEquals(info.getCalendarDateRange(null), dr); * * // subset(bb, dr); * long diff = dr.getEnd().getDifferenceInMsecs(dr.getStart()); * CalendarDate mid = dr.getStart().add(diff/2, CalendarPeriod.Field.Millisec); * CalendarDateRange drsubset = CalendarDateRange.of(dr.getStart(), mid); * System.out.println(" CalendarDateRange Subset= " + drsubset); * StationTimeSeriesFeatureCollection sfcSub2 = sfc.subset(bb2, drsubset); * for (StationTimeSeriesFeature sf : sfcSub2) { * Assert.assertTrue( bb2.contains(sf.getLatLon())); * for (PointFeature pf : sf) { * Assert.assertEquals(sf.getLatLon(), pf.getLocation().getLatLon()); * Assert.assertTrue(drsubset.includes(pf.getObservationTimeAsCalendarDate())); * // Assert.assertTrue( pf.getClass().getName(), pf instanceof StationFeature); * } * } * System.out.println(" nobs= " + sfcSub2.size()); * Assert.assertTrue(sfcSub2.size() <= sfcSub.size()); // */ System.out.println("Flatten= " + bb2.toString2()); PointFeatureCollection flatten = sfc.flatten(bb2, null); int countFlat = countLocations(flatten); assert countFlat <= countStns; flatten = sfc.flatten(null, null, null); return countObs(flatten); } static int countLocations(StationTimeSeriesFeatureCollection sfc) throws IOException { System.out.printf(" Station List Size = %d %n", sfc.getStationFeatures().size()); // check uniqueness Map<String, StationTimeSeriesFeature> stns = new HashMap<>(5000); Map<MyLocation, StationTimeSeriesFeature> locs = new HashMap<>(5000); int dups = 0; for (StationTimeSeriesFeature sf : sfc) { StationTimeSeriesFeature other = stns.get(sf.getName()); if (other != null && dups < 10) { System.out.printf(" duplicate name = %s %n", sf); System.out.printf(" of = %s %n", other); dups++; } else { stns.put(sf.getName(), sf); } MyLocation loc = new MyLocation(sf); StationTimeSeriesFeature already = locs.get(loc); if (already != null) { System.out.printf(" duplicate location %s(%s) of %s(%s) %n", sf.getName(), sf.getDescription(), already.getName(), already.getDescription()); } else { locs.put(loc, sf); } } System.out.printf(" duplicate names = %d %n", dups); System.out.printf(" unique locs = %d %n", locs.size()); System.out.printf(" unique stns = %d %n", stns.size()); return stns.size(); } static int checkStationProfileFeatureCollection(StationProfileFeatureCollection stationProfileFeatureCollection, boolean show) throws IOException { long start = System.currentTimeMillis(); int count = 0; for (StationProfileFeature spf : stationProfileFeatureCollection) { checkDsgFeatureCollection(spf); Assert.assertNotNull("StationProfileFeature latlon", spf.getLatLon()); Assert.assertNotNull("StationProfileFeature featureData", spf.getFeatureData()); // iterates through the profile but not the profile data List<CalendarDate> times = spf.getTimes(); if (showAll) { System.out.printf(" times= "); for (CalendarDate t : times) { System.out.printf("%s, ", t); } System.out.printf("%n"); } Set<String> profileNames = new HashSet<>(); for (ProfileFeature profile : spf) { checkDsgFeatureCollection(profile); Assert.assertNotNull("ProfileFeature time", profile.getTime()); Assert.assertNotNull("ProfileFeature latlon", profile.getLatLon()); Assert.assertNotNull("ProfileFeature featureData", profile.getFeatureData()); Assert.assertTrue(!profileNames.contains(profile.getName())); profileNames.add(profile.getName()); if (show) { System.out.printf(" ProfileFeature=%s %n", profile.getName()); } count += checkPointFeatureCollection(profile, show); } } long took = System.currentTimeMillis() - start; if (show) { System.out.println( " testStationProfileFeatureCollection complete count= " + count + " full iter took= " + took + " msec"); } return count; } static int checkSectionFeatureCollection(TrajectoryProfileFeatureCollection sectionFeatureCollection, boolean show) throws IOException { long start = System.currentTimeMillis(); int count = 0; for (TrajectoryProfileFeature section : sectionFeatureCollection) { checkDsgFeatureCollection(section); Assert.assertNotNull("SectionFeature featureData", section.getFeatureData()); Set<String> profileNames = new HashSet<>(); for (ProfileFeature profile : section) { checkDsgFeatureCollection(profile); Assert.assertNotNull("ProfileFeature time", profile.getTime()); Assert.assertNotNull("ProfileFeature latlon", profile.getLatLon()); Assert.assertNotNull("ProfileFeature featureData", profile.getFeatureData()); Assert.assertTrue(!profileNames.contains(profile.getName())); profileNames.add(profile.getName()); if (show) { System.out.printf(" ProfileFeature=%s %n", profile.getName()); } count += checkPointFeatureCollection(profile, show); } } long took = System.currentTimeMillis() - start; if (show) { System.out.println( " testStationProfileFeatureCollection complete count= " + count + " full iter took= " + took + " msec"); } return count; } // stuff we havent got around to coding specific tests for static int checkOther(DsgFeatureCollection dsg, boolean show) throws IOException { long start = System.currentTimeMillis(); int count = 0; // we will just run through everything try { CollectionInfo info = new DsgCollectionHelper(dsg).calcBounds(); if (show) { System.out.printf(" info=%s%n", info); } count = info.nobs; } catch (IOException e) { e.printStackTrace(); return 0; } long took = System.currentTimeMillis() - start; if (show) { System.out .println(" testNestedPointFeatureCollection complete count= " + count + " full iter took= " + took + " msec"); } return count; } ///////////////////////////////////////////// // check that the location and times are filled out // read and test the data static private void checkPointFeature(PointFeature pobs, CalendarDateUnit timeUnit) throws java.io.IOException { Assert.assertNotNull("PointFeature location", pobs.getLocation()); Assert.assertNotNull("PointFeature time", pobs.getNominalTimeAsCalendarDate()); Assert.assertNotNull("PointFeature dataAll", pobs.getDataAll()); Assert.assertNotNull("PointFeature featureData", pobs.getFeatureData()); Assert.assertEquals("PointFeature makeCalendarDate", timeUnit.makeCalendarDate(pobs.getObservationTime()), pobs.getObservationTimeAsCalendarDate()); assert timeUnit.makeCalendarDate(pobs.getObservationTime()).equals(pobs.getObservationTimeAsCalendarDate()); checkData(pobs.getDataAll()); } // read each field, check datatype static private void checkData(StructureData sdata) { for (StructureMembers.Member member : sdata.getMembers()) { DataType dt = member.getDataType(); if (dt == DataType.FLOAT) { sdata.getScalarFloat(member); sdata.getJavaArrayFloat(member); } else if (dt == DataType.DOUBLE) { sdata.getScalarDouble(member); sdata.getJavaArrayDouble(member); } else if (dt == DataType.BYTE) { sdata.getScalarByte(member); sdata.getJavaArrayByte(member); } else if (dt == DataType.SHORT) { sdata.getScalarShort(member); sdata.getJavaArrayShort(member); } else if (dt == DataType.INT) { sdata.getScalarInt(member); sdata.getJavaArrayInt(member); } else if (dt == DataType.LONG) { sdata.getScalarLong(member); sdata.getJavaArrayLong(member); } else if (dt == DataType.CHAR) { sdata.getScalarChar(member); sdata.getJavaArrayChar(member); sdata.getScalarString(member); } else if (dt == DataType.STRING) { sdata.getScalarString(member); } if ((dt != DataType.STRING) && (dt != DataType.CHAR) && (dt != DataType.STRUCTURE) && (dt != DataType.SEQUENCE)) { sdata.convertScalarFloat(member.getName()); } } } static void showStructureData(PointFeatureCCC ccc) throws IOException { PrintWriter pw = new PrintWriter(System.out); IOIterator<PointFeatureCC> iter = ccc.getCollectionIterator(); while (iter.hasNext()) { PointFeatureCC cc = iter.next(); System.out.printf(" 1.hashCode=%d %n", cc.hashCode()); IOIterator<PointFeatureCollection> iter2 = cc.getCollectionIterator(); while (iter2.hasNext()) { PointFeatureCollection pfc = iter2.next(); System.out.printf(" 2.hashcode%d %n", pfc.hashCode()); for (ucar.nc2.ft.PointFeature pointFeature : pfc) { System.out.printf(" 3.hashcode=%d %n", pointFeature.hashCode()); StructureData sdata = pointFeature.getDataAll(); logger.debug(Ncdump.printStructureData(sdata)); } } } } ///////////////////////////////////////////////////// static int checkPointFeatureCollectionBB(PointFeatureCollection pfc, boolean show) throws IOException { if (show) { System.out.printf("----------- testPointFeatureCollection -----------------%n"); System.out.println(" test PointFeatureCollection " + pfc.getName()); System.out.println(" calcBounds"); } if (show) { System.out.println(" bb= " + pfc.getBoundingBox()); System.out.println(" dateRange= " + pfc.getCalendarDateRange()); System.out.println(" npts= " + pfc.size()); } int n = pfc.size(); if (n == 0) { System.out.println(" empty " + pfc.getName()); return 0; // empty } LatLonRect bb = pfc.getBoundingBox(); assert bb != null; CalendarDateRange dr = pfc.getCalendarDateRange(); assert dr != null; // read all the data - check that it is contained in the bbox, dateRange if (show) { System.out.println(" complete iteration"); } long start = System.currentTimeMillis(); int count = 0; for (PointFeature pf : pfc) { checkPointFeature(pf, pfc.getTimeUnit()); if (!bb.contains(pf.getLocation().getLatLon())) { System.out.printf(" point not in BB = %s on %s %n", pf.getLocation().getLatLon(), pfc.getName()); } if (!dr.includes(pf.getObservationTimeAsCalendarDate())) { System.out.printf(" date out of Range= %s on %s %n", pf.getObservationTimeAsCalendarDate(), pfc.getName()); } count++; } long took = System.currentTimeMillis() - start; if (show) { System.out.println(" testPointFeatureCollection complete count= " + count + " full iter took= " + took + " msec"); } // subset with a bounding box, test result is in the bounding box LatLonRect bb2 = new LatLonRect(bb.getLowerLeftPoint(), bb.getHeight() / 2, bb.getWidth() / 2); PointFeatureCollection subset = pfc.subset(bb2, null); if (show) { System.out.println(" subset bb= " + bb2.toString2()); } assert subset != null; start = System.currentTimeMillis(); int counts = 0; for (PointFeature pf : subset) { LatLonPoint llpt = pf.getLocation().getLatLon(); if (!bb2.contains(llpt)) { System.out.printf(" point not in BB = %s on %s %n", llpt, pfc.getName()); bb2.contains(llpt); } checkPointFeature(pf, pfc.getTimeUnit()); counts++; } took = System.currentTimeMillis() - start; if (show) { System.out.println(" testPointFeatureCollection subset count= " + counts + " full iter took= " + took + " msec"); } return count; } //////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// public static void checkLocation(String location, FeatureType type, boolean show) throws IOException { Formatter out = new Formatter(); FeatureDataset fdataset = FeatureDatasetFactoryManager.open(type, location, null, out); if (fdataset == null) { System.out.printf("**failed on %s %n --> %s %n", location, out); assert false; } assert fdataset instanceof FeatureDatasetPoint; FeatureDatasetPoint fdpoint = (FeatureDatasetPoint) fdataset; List<DsgFeatureCollection> collectionList = fdpoint.getPointFeatureCollectionList(); DsgFeatureCollection fc = collectionList.get(0); if (fc instanceof PointFeatureCollection) { PointFeatureCollection pfc = (PointFeatureCollection) fc; countLocations(pfc); LatLonRect bb = pfc.getBoundingBox(); LatLonRect bb2 = new LatLonRect(bb.getLowerLeftPoint(), bb.getHeight() / 2, bb.getWidth() / 2); PointFeatureCollection subset = pfc.subset(bb2, (CalendarDateRange) null); countLocations(subset); } else if (fc instanceof StationTimeSeriesFeatureCollection) { StationTimeSeriesFeatureCollection sfc = (StationTimeSeriesFeatureCollection) fc; PointFeatureCollection pfcAll = sfc.flatten(null, (CalendarDateRange) null); System.out.printf("Unique Locations all = %d %n", countLocations(pfcAll)); LatLonRect bb = sfc.getBoundingBox(); assert bb != null; LatLonRect bb2 = new LatLonRect(bb.getLowerLeftPoint(), bb.getHeight() / 2, bb.getWidth() / 2); PointFeatureCollection pfcSub = sfc.flatten(bb2, (CalendarDateRange) null); System.out.printf("Unique Locations sub1 = %d %n", countLocations(pfcSub)); StationTimeSeriesFeatureCollection sfcSub = sfc.subset(bb2); PointFeatureCollection pfcSub2 = sfcSub.flatten(null, (CalendarDateRange) null); System.out.printf("Unique Locations sub2 = %d %n", countLocations(pfcSub2)); // Dons sfc = sfc.subset(bb2); PointFeatureCollection subDon = sfc.flatten(bb2, (CalendarDateRange) null); System.out.printf("Unique Locations subDon = %d %n", countLocations(subDon)); } } static int countLocations(PointFeatureCollection pfc) throws IOException { int count = 0; Set<MyLocation> locs = new HashSet<>(80000); pfc.resetIteration(); while (pfc.hasNext()) { PointFeature pf = pfc.next(); MyLocation loc = new MyLocation(pf.getLocation()); if (!locs.contains(loc)) { locs.add(loc); } count++; // if (count % 1000 == 0) System.out.printf("Count %d%n", count); } System.out.printf("Count Points = %d Unique points = %d %n", count, locs.size()); return locs.size(); // The problem is that all the locations are coming up with the same value. This: // always returns the same lat/lon/alt (of the first observation). // (pos was populated going through the PointFeatureIterator). } static int countObs(PointFeatureCollection pfc) throws IOException { int count = 0; pfc.resetIteration(); while (pfc.hasNext()) { PointFeature pf = pfc.next(); StructureData sd = pf.getDataAll(); count++; } return count; } private static class MyLocation { double lat, lon, alt; public MyLocation(EarthLocation from) { this.lat = from.getLatitude(); this.lon = from.getLongitude(); this.alt = Double.isNaN(from.getAltitude()) ? 0.0 : from.getAltitude(); } @Override public boolean equals(Object oo) { if (this == oo) { return true; } if (!(oo instanceof MyLocation)) { return false; } MyLocation other = (MyLocation) oo; return (lat == other.lat) && (lon == other.lon) && (alt == other.alt); } @Override public int hashCode() { if (hashCode == 0) { int result = 17; result += 37 * result + lat * 10000; result += 37 * result + lon * 10000; result += 37 * result + alt * 10000; hashCode = result; } return hashCode; } private int hashCode = 0; } }
true
10cf2edcad27c13cb6c8d02842b28e66907b4d01
Java
The-hated-one/Data-Structures-Algorithms
/GFG/Arrays/Remove_duplicates_from_sorted_array.java
UTF-8
1,829
3.828125
4
[]
no_license
/* Given a sorted array A of size N. The function remove_duplicate takes two arguments . The first argument is the sorted array A[ ] and the second argument is 'N' the size of the array and returns the size of the new converted array A[ ] with no duplicate element. Input Format: The first line of input contains T denoting the no of test cases . Then T test cases follow . The first line of each test case contains an Integer N and the next line contains N space separated values of the array A[ ] . Output Format: For each test case output will be the transformed array with no duplicates. Your Task: Your task to complete the function remove_duplicate which removes the duplicate elements from the array . Constraints: 1 <= T <= 100 1 <= N <= 104 1 <= A[ ] <= 106 Example: Input (To be used only for expected output) : 2 5 2 2 2 2 2 3 1 2 2 Output 2 1 2 *********************************************************************Solution*****************************************************************************/ import java.util.Scanner; class Delete_Duplicate { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T>0) { int N = sc.nextInt(); int a[] = new int[N]; for(int i=0; i<N; i++) a[i] = sc.nextInt(); GfG g = new GfG(); int n = g.remove_duplicate(a,N); for(int i=0; i<n; i++) System.out.print(a[i]+" "); System.out.println(); T--; } } } class GfG { int remove_duplicate(int a[], int n) { int j=0; for(int i=0;i<n-1;i++) { //this is to store only unique elements if(a[i]!=a[i+1]) { a[j]=a[i]; j++; } } a[j]=a[n-1]; return j+1; } }
true
0b90cec0c466b594b05541edd616a30261089abf
Java
Severed-Infinity/Semester4Project
/Semester4Project/src/com/project/database/Room.java
UTF-8
2,402
2.8125
3
[]
no_license
package com.project.database; import java.text.*; import java.util.*; /** * Project Semester4Project * * This class is part of a project * that is aimed at improving ITT's * timetable system * * Created by david on 4/30/2014. */ public class Room { public static final Deque<Room> ROOMS = null; private final int roomNumber; private final int roomSeating; private final String departmentCode; private final boolean lab; private final int shareRoomNumber; private Room( final int roomNumber, final int roomSeating, final String departmentCode, final boolean lab, final int shareRoomNumber ) { this.roomNumber = roomNumber; this.roomSeating = roomSeating; this.departmentCode = departmentCode; this.lab = lab; this.shareRoomNumber = shareRoomNumber; } public static Room createRoom( final int roomNumber, final int roomSeating, final String departmentCode, final boolean lab, final int shareRoomNumber ) {return new Room(roomNumber, roomSeating, departmentCode, lab, shareRoomNumber);} // --Commented out by Inspection START (5/2/2014 12:40 PM): // public int getRoomNumber() { // return this.roomNumber; // } // --Commented out by Inspection STOP (5/2/2014 12:40 PM) // --Commented out by Inspection START (5/2/2014 12:40 PM): // public int getRoomSeating() { // return this.roomSeating; // } // --Commented out by Inspection STOP (5/2/2014 12:40 PM) // --Commented out by Inspection START (5/2/2014 12:40 PM): // public String getDepartmentCode() { // return this.departmentCode; // } // --Commented out by Inspection STOP (5/2/2014 12:40 PM) // --Commented out by Inspection START (5/2/2014 12:40 PM): // public boolean isLab() { // return this.lab; // } // --Commented out by Inspection STOP (5/2/2014 12:40 PM) // --Commented out by Inspection START (5/2/2014 12:40 PM): // public int getShareRoomNumber() { // return this.shareRoomNumber; // } // --Commented out by Inspection STOP (5/2/2014 12:40 PM) @Override public String toString() { return MessageFormat.format( "Room'{'roomNumber={0}, roomSeating={1}, departmentCode=''{2}'', lab={3}, " + "shareRoomNumber={4}'}'", this.roomNumber, this.roomSeating, this.departmentCode, this.lab, this.shareRoomNumber ); } }
true
8bdabe245a8e789ea1e9d7fb0b5c13c7f245a930
Java
levibostian/SyntaxDesigns_android
/app/src/main/java/edu/uni/cs/syntaxdesigns/Adapters/IngredientsListAdapter.java
UTF-8
2,484
2.4375
2
[]
no_license
package edu.uni.cs.syntaxdesigns.Adapters; import edu.uni.cs.syntaxdesigns.R; import edu.uni.cs.syntaxdesigns.adapter.BaseArrayAdapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class IngredientsListAdapter extends BaseArrayAdapter { private List<String> mIngredients; private IngredientsGridListener mCallback; private boolean mIsWithIngredientList; public IngredientsListAdapter(Context context, List<String> ingredients, boolean isWithIngredientList) { super(context, 0, ingredients); mIngredients = ingredients; mIsWithIngredientList = isWithIngredientList; mInflater = LayoutInflater.from(context); } private static class ViewHolder { TextView ingredient; ImageView removeIngredient; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = mInflater.inflate(R.layout.filter_ingredient_row, parent, false); viewHolder = new ViewHolder(); viewHolder.ingredient = (TextView) convertView.findViewById(R.id.ingredient_name); viewHolder.removeIngredient = (ImageView) convertView.findViewById(R.id.delete_ingredient); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.ingredient.setText(mIngredients.get(position)); viewHolder.removeIngredient.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mIsWithIngredientList) { mCallback.removeWithIngredientFromFilterUtil(mIngredients.get(position)); } else { mCallback.removeWithoutIngredientFromtFilterUtil(mIngredients.get(position)); } notifyDataSetChanged(); } }); return convertView; } public void setCallbacks(IngredientsGridListener callback) { mCallback = callback; } public interface IngredientsGridListener { void removeWithIngredientFromFilterUtil(String ingredient); void removeWithoutIngredientFromtFilterUtil(String ingredient); } }
true
622aa139e6d88fb1124d169ca881fbb2a17c765a
Java
luisromangz/grc-framework
/GreenRiverCommons/src/com/greenriver/commons/collections/specialized/DateRangeSortedList.java
UTF-8
9,326
2.953125
3
[]
no_license
package com.greenriver.commons.collections.specialized; import com.greenriver.commons.DatePart; import com.greenriver.commons.DateRange; import com.greenriver.commons.Dates; import com.greenriver.commons.collections.SortedArrayList; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; /** * @author Miguel Angel */ public class DateRangeSortedList extends SortedArrayList<DateRange> { private class DateRangeComparator implements Comparator<DateRange>, Serializable { public int compare(DateRange o1, DateRange o2) { return o1.compareTo(o2, datePart); } } private DatePart datePart; public DatePart getDatePart() { return datePart; } public DateRangeSortedList() { this(DatePart.DATE_TIME); } public DateRangeSortedList(DatePart part) { this(10, part); } public DateRangeSortedList(int initialCapacity) { this(initialCapacity, DatePart.DATE_TIME); } public DateRangeSortedList(int initialCapacity, DatePart part) { super(initialCapacity); this.datePart = part; this.setComparator(new DateRangeComparator()); } public DateRangeSortedList(Collection<DateRange> dateRanges) { this(dateRanges, DatePart.DATE_TIME); } public DateRangeSortedList(Collection<DateRange> dateRanges, DatePart part) { super(dateRanges.size()); this.setComparator(new DateRangeComparator()); this.datePart = part; this.addAll(dateRanges); } private DateRange clone(DateRange dateRange) { try { return (DateRange) dateRange.clone(); } catch (CloneNotSupportedException ex) { return null; } } /** * Adds a new range to the list merging it with any existing range if they * intersects or if they are consecutive. * @param candidate * @return true if added or false if not (only if it already exists) * @throws IllegalStateException when the element can't be added and it * didn't existed in the collection. */ @Override public boolean add(DateRange candidate) throws IllegalStateException { if (candidate.isEmpty() || candidate.isInfinite()) { throw new IllegalArgumentException("Empty or infinite ranges are not allowed"); } DateRange dateRange = null; DateRange increasedRange = null; int pos = 0; increasedRange = this.increaseRangeForComparison(candidate); while (pos <= this.size()) { if (pos == this.size()) { return super.addAt(pos, clone(candidate), true); } dateRange = this.get(pos); if (dateRange.equals(candidate, this.datePart)) { //range already in collection, bye bye! return false; } if (increasedRange.intersects(dateRange, datePart)) { //The candidate can be merged with the existing range dateRange.merge(candidate, datePart); //We need to check if any other range must be merged with this this.mergeAdjacentRanges(pos); return true; } else if (candidate.after(dateRange, datePart)) { //The range is after the current one so we must increase this pos++; } else if (candidate.before(dateRange, datePart)) { //The range goes before the current one return super.addAt(pos, clone(candidate), true); } } //We must append the range to the end return super.addAt(this.size(), clone(candidate), true); } /** * When a range is merged the next ranges must be checked to see if they * intersect the merged one or if they are consecutive to merge them too * @param pos Position of the recently merged range. */ private void mergeAdjacentRanges(int pos) { DateRange currentRange = this.get(pos); DateRange increasedRange = this.increaseRangeForComparison(currentRange); pos++; while (pos < this.size() && increasedRange.intersects(this.get(pos))) { //Merge the range, update the range used for test and remove the //merged one from the list to don't check it again. currentRange.merge(this.get(pos), datePart); increasedRange = this.increaseRangeForComparison(currentRange); this.remove(pos); } return; } /** * Increases the range bounds using the current date part to make easier * to detect consecutive ranges. * @param range * @return */ private DateRange increaseRangeForComparison(DateRange range) { GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); Date min = null; Date max = null; switch (this.datePart) { case DATE: min = Dates.getDatePart(range.getMin()); cal.setTime(min); cal.add(GregorianCalendar.DAY_OF_MONTH, -1); min = cal.getTime(); max = Dates.getDatePart(range.getMax()); cal.setTime(max); cal.add(GregorianCalendar.DAY_OF_MONTH, 1); max = cal.getTime(); break; case DATE_TIME: case TIME: cal.setTime(range.getMin()); cal.add(GregorianCalendar.MILLISECOND, -1); min = cal.getTime(); cal.setTime(range.getMax()); cal.add(GregorianCalendar.MILLISECOND, 1); max = cal.getTime(); break; default: throw new IllegalArgumentException("Date part not supported"); } return new DateRange(min, max); } public Date getMin() { if (this.size() == 0) { return null; } return this.get(0).getMin(); } public Date getMax() { if (this.size() == 0) { return null; } return this.get(this.size() - 1).getMax(); } public DateRangeSortedList getIntersection(DateRangeSortedList other) { if (other.datePart != this.datePart) { throw new IllegalArgumentException("Incompatible date parts"); } DateRangeSortedList result = new DateRangeSortedList(this.datePart); // TODO: Optimize this for (DateRange range : this) { for (DateRange otherRange : other) { if (range.intersects(otherRange, this.datePart)) { result.add(range.getIntersection(otherRange, this.datePart)); } } } return result; } public boolean containsDate(Date date) { for (DateRange range : this) { if (range.contains(date, datePart)) { return true; } } return false; } @Override public boolean remove(Object o) { if (o == null) { throw new NullPointerException( "Null not allowed as an item of this collection"); } if (!DateRange.class.isAssignableFrom(o.getClass())) { throw new ClassCastException("Class " + o.getClass() + " can't be cast to " + DateRange.class); } boolean modified = false; DateRange target = (DateRange) o; DateRange candidate = null; int pos = 0; List<DateRange> newItems = null; // For each range in the collection that intersects with the present // one we must: // a- Remove it entirely if the collection's range is contained in the // range to remove // b- Replace the collection's range with another range(s) with the // difference between the collection's range and the range to remove // Iterate using a loop as we will doing replacements and element // removal and is easier this way while(pos < this.size()) { candidate = this.get(pos); if (!candidate.intersects(target, datePart)) { pos++; continue; } // collection surely updated modified = true; // Case a- is always done, case b- is only done when the ranges // doesn't match and we need to addDateToRange the remains of the candidate this.remove(pos); if (candidate.isContained(target, datePart)) { continue; } newItems = candidate.getDifference(target, datePart); for (int i=0; i<newItems.size(); i++) { this.add(pos + i, newItems.get(i)); } pos += newItems.size(); } return modified; } @Override @SuppressWarnings("element-type-mismatch") public boolean removeAll(Collection<?> c) { boolean updated = false; for (Object obj : c) { updated |= this.remove(obj); } return updated; } }
true
585b9447ddd4f9d5016eb10a992b75a1cc71a9e2
Java
1627762273/GridDividerMoreTypeItemDecoration
/GridDividerMoreTypeItemDecoration.java
UTF-8
15,458
2.265625
2
[]
no_license
package com.starlight.mobile.android.smsone.common; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.support.annotation.ColorInt; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.View; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; /** * 区别于GridDividerItemDecoration, 这个适合有HeaderType,在Header下又有图片类型的,在Adapter中item布局可以不使用recyclerView * * 也就是相当于不需要Recyclerview 嵌套recyclerview了 */ public class GridDividerMoreTypeItemDecoration extends RecyclerView.ItemDecoration { public static final String TAG = "GridMoreTypeDecoration"; private Paint mPaint; private int mDividerWidth; //您所需指定的间隔宽度,主要为第一列和最后一列与父控件的间隔;行间距,列间距将动态分配 private int mFirstRowTopMargin = 0; //第一行顶部是否需要间隔 private boolean isNeedSpace = false;//第一列和最后一列是否需要指定间隔(默认不指定) private boolean isLastRowNeedSpace = false;//最后一行是否需要间隔(默认不需要) int spanCount = 0; private Context mContext; private Path mPath = null; /** * 意思是存储每一个个HeadView 的之前所有Item包括自己的数量 */ LinkedHashMap<Integer,Integer> headPositionTotalCountMap = new LinkedHashMap<>(); /** * 每一个子Item(非HeadView),存储自己对应的headView的Item数量, * 主要用于取余计算时,位置换算 */ LinkedHashMap<Integer,Integer> subItemPositionCountMap = new LinkedHashMap<>(); /** * * @param dividerWidth 间隔宽度 * @param isNeedSpace 第一列和最后一列是否需要间隔 */ public GridDividerMoreTypeItemDecoration(Context context, int dividerWidth, boolean isNeedSpace) { this(context,dividerWidth,0,isNeedSpace,false); } /** * * @param dividerWidth 间隔宽度 * @param isNeedSpace 第一列和最后一列是否需要间隔 * @param firstRowTopMargin 第一行顶部是否需要间隔(根据间隔大小判断) */ public GridDividerMoreTypeItemDecoration(Context context, int dividerWidth, int firstRowTopMargin, boolean isNeedSpace) { this(context,dividerWidth,firstRowTopMargin,isNeedSpace,false); } /** * @param dividerWidth 间隔宽度 * @param firstRowTopMargin 第一行顶部是否需要间隔 * @param isNeedSpace 第一列和最后一列是否需要间隔 * @param isLastRowNeedSpace 最后一行是否需要间隔 */ public GridDividerMoreTypeItemDecoration(Context context, int dividerWidth, int firstRowTopMargin, boolean isNeedSpace, boolean isLastRowNeedSpace) { this(context,dividerWidth,firstRowTopMargin,isNeedSpace,isLastRowNeedSpace, Color.GRAY); } /** * @param dividerWidth 间隔宽度 * @param firstRowTopMargin 第一行顶部是否需要间隔 * @param isNeedSpace 第一列和最后一列是否需要间隔 * @param isLastRowNeedSpace 最后一行是否需要间隔 */ public GridDividerMoreTypeItemDecoration(Context context, int dividerWidth, int firstRowTopMargin, boolean isNeedSpace, boolean isLastRowNeedSpace, @ColorInt int color) { mDividerWidth = dividerWidth; this.isNeedSpace = isNeedSpace; this.mContext = context; this.isLastRowNeedSpace = isLastRowNeedSpace; this.mFirstRowTopMargin = firstRowTopMargin; mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // mPaint.setColor(color); mPaint.setColor(Color.parseColor("#d6d6d6")); mPaint.setStyle(Paint.Style.STROKE); mPaint.setPathEffect(new DashPathEffect(new float[]{10,5},0)); mPath = new Path(); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); int top = 0; int left = 0; int right = 0; int bottom = 0; int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); spanCount = getSpanCount(parent); int spanSize = getSpanSize(itemPosition,parent); Log.e(TAG,"itemPosition =="+itemPosition); Log.e(TAG,"spanCount =="+spanCount); Log.e(TAG,"spanSize =="+spanSize); if(spanSize == spanCount){//这是有HeaderView 的情况 left = mDividerWidth; right = mDividerWidth; bottom = 0; top = itemPosition == 0 ? mDividerWidth : 2*mDividerWidth;//为了画分隔线,第一行HeaderView不需要画分隔线 if(!headPositionTotalCountMap.containsKey(itemPosition)) { headPositionTotalCountMap.put(itemPosition,itemPosition+1); } }else {//类似HeaderView 下的子item if(!subItemPositionCountMap.containsKey(itemPosition)) { int headViewTotalCount = headPositionTotalCountMap.size() == 0 ? 0 : getMapTail(headPositionTotalCountMap).getValue(); subItemPositionCountMap.put(itemPosition, headViewTotalCount); } int maxAllDividerWidth = getMaxDividerWidth(view); //获得最大剩余宽度 int spaceWidth = 0;//首尾两列与父布局之间的间隔 if (isNeedSpace) spaceWidth = mDividerWidth; int eachItemWidth = maxAllDividerWidth / spanCount;//每个Item left+right int dividerItemWidth = (maxAllDividerWidth - 2 * spaceWidth) / (spanCount - 1);//item与item之间的距离 Log.w(TAG,"subCountMap.get(itemPosition)) =="+subItemPositionCountMap.get(itemPosition)); Log.w(TAG,"(itemPosition-subCountMap.get(itemPosition)) % spanCount ==="+(itemPosition-subItemPositionCountMap.get(itemPosition)) % spanCount); left = (itemPosition-subItemPositionCountMap.get(itemPosition)) % spanCount * (dividerItemWidth - eachItemWidth) + spaceWidth; right = eachItemWidth - left; bottom = 0; top = mDividerWidth; } outRect.set(left, top, right, bottom); } /** * 获取最近一个Entry * @param headCountMap * @return */ private Map.Entry<Integer,Integer> getMapTail(LinkedHashMap<Integer,Integer> headCountMap) { Iterator<Map.Entry<Integer,Integer>> iterator = headCountMap.entrySet().iterator(); Map.Entry tail = null; while (iterator.hasNext()){ tail = iterator.next(); } return tail; } /** * 获取Item View的大小,若无则自动分配空间 * 并根据 屏幕宽度-View的宽度*spanCount 得到屏幕剩余空间 * @param view * @return */ private int getMaxDividerWidth(View view) { int itemWidth = view.getLayoutParams().width; int itemHeight = view.getLayoutParams().height; int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels > mContext.getResources().getDisplayMetrics().heightPixels ? mContext.getResources().getDisplayMetrics().heightPixels : mContext.getResources().getDisplayMetrics().widthPixels; int maxDividerWidth = screenWidth-itemWidth * spanCount; if(itemHeight < 0 || itemWidth < 0 || (isNeedSpace && maxDividerWidth <= (spanCount-1) * mDividerWidth)){ view.getLayoutParams().width = getAttachCloumnWidth(); view.getLayoutParams().height = getAttachCloumnWidth(); maxDividerWidth = screenWidth-view.getLayoutParams().width * spanCount; } return maxDividerWidth; } /** * 根据屏幕宽度和item数量分配 item View的width和height * @return */ private int getAttachCloumnWidth() { int itemWidth = 0; int spaceWidth = 0; try { int width = mContext.getResources().getDisplayMetrics().widthPixels > mContext.getResources().getDisplayMetrics().heightPixels ? mContext.getResources().getDisplayMetrics().heightPixels : mContext.getResources().getDisplayMetrics().widthPixels; if(isNeedSpace) spaceWidth = 2 * mDividerWidth; itemWidth = (width-spaceWidth) / spanCount - 40; } catch (Exception e) { e.printStackTrace(); } return itemWidth; } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); draw(c, parent); } //绘制不同HeadView之间虚线分割线 private void draw(Canvas canvas, RecyclerView parent) { int width = mContext.getResources().getDisplayMetrics().widthPixels > mContext.getResources().getDisplayMetrics().heightPixels ? mContext.getResources().getDisplayMetrics().heightPixels : mContext.getResources().getDisplayMetrics().widthPixels; int spanCount = getSpanCount(parent); int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { View child = parent.getChildAt(i); int itemPosition = ((RecyclerView.LayoutParams) child.getLayoutParams()).getViewLayoutPosition(); int spanSize = getSpanSize(itemPosition,parent); if(spanCount == spanSize && itemPosition != 0){ mPath.reset(); mPath.moveTo(child.getLeft()-5,child.getTop()-mDividerWidth); mPath.lineTo(width-mDividerWidth+5,child.getTop()-mDividerWidth); canvas.drawPath(mPath,mPaint); } } } // //绘制item分割线 // private void draw(Canvas canvas, RecyclerView parent) { // int childCount = parent.getChildCount(); // for (int i = 0; i < childCount; i++) { // View child = parent.getChildAt(i); // RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams(); // // //画水平分隔线 // int left = child.getLeft(); // int right = child.getRight(); // int top = child.getBottom() + layoutParams.bottomMargin; // int bottom = top + mDividerWidth; // if (mPaint != null) { // canvas.drawRect(left, top, right, bottom, mPaint); // } // //画垂直分割线 // top = child.getTop(); // bottom = child.getBottom() + mDividerWidth; // left = child.getRight() + layoutParams.rightMargin; // right = left + mDividerWidth; // if (mPaint != null) { // canvas.drawRect(left, top, right, bottom, mPaint); // } // } // } /** * 判读是否是第一列 * @param parent * @param pos * @param spanCount * @param childCount * @return */ private boolean isFirstColumn(RecyclerView parent, int pos, int spanCount, int childCount) { RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { if (pos % spanCount == 0) { return true; } } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); if (orientation == StaggeredGridLayoutManager.VERTICAL) { if (pos % spanCount == 0) {// 第一列 return true; } } else { } } return false; } /** * 判断是否是最后一列 * @param parent * @param pos * @param spanCount * @param childCount * @return */ private boolean isLastColumn(RecyclerView parent, int pos, int spanCount, int childCount) { RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { if ((pos + 1) % spanCount == 0) {// 如果是最后一列,则不需要绘制右边 return true; } } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); if (orientation == StaggeredGridLayoutManager.VERTICAL) { if ((pos + 1) % spanCount == 0) {// 最后一列 return true; } } else { } } return false; } /** * 判读是否是最后一行 * @param parent * @param pos * @param spanCount * @param childCount * @return */ private boolean isLastRow(RecyclerView parent, int pos, int spanCount, int childCount) { RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { int lines = childCount % spanCount == 0 ? childCount / spanCount : childCount / spanCount + 1; return lines == pos / spanCount + 1; } else if (layoutManager instanceof StaggeredGridLayoutManager) { } return false; } /** * 判断是否是第一行 * @param parent * @param pos * @param spanCount * @param childCount * @return */ private boolean isFirstRow(RecyclerView parent, int pos, int spanCount, int childCount) { RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { if ((pos / spanCount + 1) == 1) { return true; } else { return false; } } else if (layoutManager instanceof StaggeredGridLayoutManager) { } return false; } /** * 获取列数 * @param parent * @return */ private int getSpanCount(RecyclerView parent) { int spanCount = -1; RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { spanCount = ((GridLayoutManager) layoutManager).getSpanCount(); } else if (layoutManager instanceof StaggeredGridLayoutManager) { spanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount(); } return spanCount; } /** * 返回recyclview 设置了setSpanSizeLookup,判断几个单元格合并为一个 * @param position * @return */ private int getSpanSize(int position,RecyclerView parent){ int spanSize = -1; RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { spanSize = ((GridLayoutManager) layoutManager).getSpanSizeLookup().getSpanSize(position); } else if (layoutManager instanceof StaggeredGridLayoutManager) { } return spanSize; } }
true
0caf85702360c44cdf96fdee8c988632a9ba240e
Java
gil2455526/Ouvido
/src/main/java/com/gilwanderley/ouvido/Janela.java
UTF-8
8,137
2.34375
2
[]
no_license
package com.gilwanderley.ouvido; import edu.cmu.sphinx.api.Configuration; import edu.cmu.sphinx.api.LiveSpeechRecognizer; import edu.cmu.sphinx.api.SpeechResult; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import java.awt.datatransfer.*; import java.awt.Toolkit; /** * @author Gil w */ public class Janela extends javax.swing.JFrame { public Janela() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { Abrir = new javax.swing.JToggleButton(); Copiar = new javax.swing.JToggleButton(); TextoUI = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Ouvido"); setLocation(new java.awt.Point(500, 250)); setResizable(false); Abrir.setText("Abrir"); Abrir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AbrirActionPerformed(evt); } }); Copiar.setText("Copiar para área de transferência"); Copiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CopiarActionPerformed(evt); } }); TextoUI.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N TextoUI.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); TextoUI.setText("Ouvido"); 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.CENTER) .addGroup(layout.createSequentialGroup() .addComponent(Abrir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Copiar)) .addComponent(TextoUI, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Copiar, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE) .addComponent(Abrir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(TextoUI) .addContainerGap(20, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void AbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AbrirActionPerformed Configuration configuration = new Configuration(); configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us"); configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict"); configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp"); LiveSpeechRecognizer recognizer; try { recognizer = new LiveSpeechRecognizer(configuration); } catch (IOException ex) { Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex); TextoUI.setText("Erro Iniciando Sphinx4"); return; } if(Abrir.isSelected()){ Copiar.setSelected(false); recognizer.stopRecognition(); recognizer.startRecognition(true); TextoUI.setText("Ouvindo..."); } else{ TextoUI.setText("Abrindo..."); SpeechResult result = recognizer.getResult(); Runtime runTime = Runtime.getRuntime(); Process process = null; try { process = runTime.exec(result.getHypothesis()); } catch (IOException ex) { Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex); TextoUI.setText("Erro abrindo programa"); return; } process.destroy(); } }//GEN-LAST:event_AbrirActionPerformed private void CopiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CopiarActionPerformed Configuration configuration = new Configuration(); configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us"); configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict"); configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp"); LiveSpeechRecognizer recognizer; try { recognizer = new LiveSpeechRecognizer(configuration); } catch (IOException ex) { Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex); TextoUI.setText("Erro Iniciando Sphinx4"); return; } if(Copiar.isSelected()){ Abrir.setSelected(false); recognizer.stopRecognition(); recognizer.startRecognition(true); TextoUI.setText("Ouvindo..."); } else{ TextoUI.setText("Trabalhando nisso..."); SpeechResult result = recognizer.getResult(); Clipboard copiar = Toolkit.getDefaultToolkit ().getSystemClipboard (); StringSelection stringSelection = new StringSelection (result.getHypothesis()); copiar.setContents (stringSelection, null); } }//GEN-LAST:event_CopiarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Janela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Janela().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JToggleButton Abrir; private javax.swing.JToggleButton Copiar; private javax.swing.JLabel TextoUI; // End of variables declaration//GEN-END:variables }
true
39305e29ce77ae8e1e7ac868dee4982efef7d77a
Java
bharth-stack/java_programs
/SwitchCases.java
UTF-8
1,130
3.453125
3
[]
no_license
package pkgswitch.cases; import java.util.*; public class SwitchCases { public static void main(String[] args) { int dayno; Scanner s=new Scanner(System.in); System.out.println("enter the Month:"); dayno=s.nextInt(); switch(dayno) { case 1:System.out.println("JANUARY"); break; case 2:System.out.println("FEBRUARY"); break; case 3:System.out.println("MARCH"); break; case 4:System.out.println("APRIL"); break; case 5:System.out.println("MAY"); break; case 6:System.out.println("JUNE"); break; case 7:System.out.println("JULY"); break; case 8:System.out.println("AUGUST"); break; case 9:System.out.println("SEPTEBER"); break; case 10:System.out.println("OCTOBER"); break; case 11:System.out.println("NOVEMBER"); break; case 12:System.out.println("DECEMBER"); break; default :System.out.println("wrong input"); break; } } }
true
30969815dfe6ba063cdf778b6fda244bd8d02834
Java
Gleb394/Mateacademy
/src/main/java/homeWork/HomeWork2.java
UTF-8
1,134
3.625
4
[]
no_license
package homeWork; public class HomeWork2 { public String palindrome(String word) { int backward = word.length() - 1; for (int i = 0; backward > i; i++) { if (word.charAt(i) != word.charAt(backward)) { return "isn't palindrome"; } backward--; } return "is polindrome"; } public void reverse(int i, int j, String letters) { int counter = 0; System.out.print(letters + " - substring " + "\""); while (i <= j) { System.out.print(letters.charAt(i)); i++; counter++; } i = i - counter; System.out.print("\""); System.out.print(" was reversed to " + "\""); while (j >= i) { System.out.print(letters.charAt(j)); j--; } System.out.print("\""); } public int frequency(char letter, String letters) { int counter = 0; for (char chars : letters.toCharArray()) { if (letter == chars) { counter++; } } return counter; } }
true
3c05addc979239a1490cef7f42e8a3c8396442c9
Java
hansdelgado/gchCibertec
/src/main/java/pe/edu/cibertec/gch/modelo/Curso.java
UTF-8
2,364
2.53125
3
[]
no_license
package pe.edu.cibertec.gch.modelo; /** * Es el conjunto de temas agrupados para ser dictados dentro de un tiempo * acordado. Puede estar asociado a distintos programas en el tiempo. */ public class Curso { private String codigo; private String nombre; private String descripcion; private String objetivos; private String requisitos; //private int duracion; private String duracion; private EstadoActividad estado; public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public Curso conCodigo(String codigo) { setCodigo(codigo); return this; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Curso conNombre(String nombre) { setNombre(nombre); return this; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Curso conDescripcion(String descripcion) { setDescripcion(descripcion); return this; } public String getObjetivos() { return objetivos; } public void setObjetivos(String objetivos) { this.objetivos = objetivos; } public Curso conObjetivos(String objetivos) { setObjetivos(objetivos); return this; } public String getRequisitos() { return requisitos; } public void setRequisitos(String requisitos) { this.requisitos = requisitos; } public Curso conRequisitos(String requisitos) { setRequisitos(requisitos); return this; } public String getDuracion() { return duracion; } public void setDuracion(String duracion) { this.duracion = duracion; } public Curso conDuracion(String duracion) { setDuracion(duracion); return this; } public EstadoActividad getEstado() { return estado; } public void setEstado(EstadoActividad estado) { this.estado = estado; } public Curso conEstado(EstadoActividad estado) { setEstado(estado); return this; } }
true
4ab29bea07a1612919396f1f7bc780b1272b557f
Java
Jindal-Ankit/TestExamplesJava
/src/com/ankit/practice/problems/SumSubArray.java
UTF-8
1,520
4.28125
4
[]
no_license
package com.ankit.practice.problems; public class SumSubArray { public static void main(String[] args) { int[] array = {3,6,9}; // 1 + (1+2) + (1+2+3) // 2 + (2+3) // 3 int n = array.length; int sum = 0; for(int i = 0 ; i < n ;i++){ for(int k = i ; k < n ;k++ ){ for(int j = i ;j <= k ;j++){ sum += array[j]; } } } System.out.println(sum); sumSubArr(array); } /* If we take a close look then we observe a pattern. Let take an example arr[] = [1, 2, 3], n = 3 All subarrays : [1], [1, 2], [1, 2, 3], [2], [2, 3], [3] here first element 'arr[0]' appears 3 times second element 'arr[1]' appears 4 times third element 'arr[2]' appears 3 times Every element arr[i] appears in two types of subsets: i) In sybarrays beginning with arr[i]. There are (n-i) such subsets. For example [2] appears in [2] and [2, 3]. ii) In (n-i)*i subarrays where this element is not first element. For example [2] appears in [1, 2] and [1, 2, 3]. Total of above (i) and (ii) = (n-i) + (n-i)*i = (n-i)(i+1) For arr[] = {1, 2, 3}, sum of subarrays is: arr[0] * ( 0 + 1 ) * ( 3 - 0 ) + arr[1] * ( 1 + 1 ) * ( 3 - 1 ) + arr[2] * ( 2 + 1 ) * ( 3 - 2 ) = 1*3 + 2*4 + 3*3 = 20*/ private static void sumSubArr(int[] arr) { int sum = 0; for(int i =0; i < arr.length ; i++){ sum +=(arr.length -i)*(i+1)*arr[i]; } System.out.println(sum); } }
true
875a9919053c9355bb8c3403657ca0d8741b4f3c
Java
limy901/Day-007
/Ran.java
UHC
632
3.59375
4
[]
no_license
import java.util.Random; class Ran { Listing list = new Listing(); //list.readF(); System.out.println("[0] : "+list.names[0]); Random r = new Random();//Ÿ r̶ ü . int n = 20;// , 20̴ϱ 20. void showNum(){ //ڻ̴ ޼ҵ int i = r.nextInt(n); //0~(n-1) ڻ. System.out.println("i : "+i); // i µ. System.out.println("ù° ǥ : "+list.names[0]); } public static void main(String[] args) { Ran ran = new Ran(); ran.showNum(); } }
true
2cd62d0ae64ad4c9a5c8111835357385498009a1
Java
houbb/mybatis
/src/main/java/com/github/houbb/mybatis/mapper/MapperSqlTemplate.java
UTF-8
730
2.40625
2
[ "Apache-2.0" ]
permissive
package com.github.houbb.mybatis.mapper; /** * sql 模板 * @author binbin.hou * @since 0.0.11 */ public class MapperSqlTemplate { /** * 唯一标识 * @since 0.0.11 */ private String id; /** * sql 本身 * @since 0.0.1 */ private String sql; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } @Override public String toString() { return "MapperSqlTemplate{" + "id='" + id + '\'' + ", sql='" + sql + '\'' + '}'; } }
true
700cc2f34a85845196f075ad4d4ac588792c3d7a
Java
hhru/checkstyle
/checkstyle-config-compilation-maven-plugin/src/main/java/ru/hh/checkstyle/maven/build/Utils.java
UTF-8
1,469
1.96875
2
[]
no_license
package ru.hh.checkstyle.maven.build; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; public final class Utils { private static final String LOAD_EXTERNAL_DTD = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; private static final String EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities"; private static final String EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; private static final EntityResolver EMPTY_ENTITY_RESOLVER = (publicId, systemId) -> new InputSource(new ByteArrayInputStream(new byte[0])); private Utils() { } public static DocumentBuilder createConfigDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // to be able to work offline w/o access to checkstyle.org factory.setValidating(false); factory.setFeature(LOAD_EXTERNAL_DTD, false); factory.setFeature(EXTERNAL_GENERAL_ENTITIES, false); factory.setFeature(EXTERNAL_PARAMETER_ENTITIES, false); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); // just in case documentBuilder.setEntityResolver(EMPTY_ENTITY_RESOLVER); return documentBuilder; } }
true
748dc4db110ad7bb22b1c74879280db829582329
Java
abhinavgla/patientmanagement
/src/main/java/com/ct/apac/patientmanagement/dao/User.java
UTF-8
859
2.234375
2
[]
no_license
package com.ct.apac.patientmanagement.dao; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "user") public class User extends AbstractEntity { @Column(name = "userId") private long userId; @Column(name = "userRole") private String userRole; @Column(name = "isUserActive") private boolean isUserActive; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserRole() { return userRole; } public void setUserRole(String userRole) { this.userRole = userRole; } public boolean isUserActive() { return isUserActive; } public void setUserActive(boolean userActive) { isUserActive = userActive; } }
true
c6533381fda370523c1b167ff293588029b94f0e
Java
waterbuckit/Honk
/src/com/water/bucket/interpreter/LexemeType.java
UTF-8
524
2.734375
3
[]
no_license
package com.water.bucket.interpreter; public enum LexemeType { // Single-character tokens. LEFT_PAREN, RIGHT_PAREN, LEFT_SQUARE, RIGHT_SQUARE, LEFT_BRACE, RIGHT_BRACE, COMMA, DOT, MINUS, PLUS, SEMICOLON, SLASH, STAR, PERCENT, // One or two character tokens. NOT, NOT_EQUAL, EQUAL, EQUAL_EQUAL, GREATER, GREATER_EQUAL, LESS, LESS_EQUAL, // Literals. IDENTIFIER, STRING, NUMBER, // Keywords. AND, CLASS, ELSE, FALSE, FUN, FOR, IF, NIL, OR, PRINT, RETURN, SUPER, THIS, TRUE, LET, WHILE, EOF; }
true
f12094e30dab9781ac12f29074a26ffb1da06b89
Java
joshhughess/WhatsForTea
/app/src/main/java/com/example/n0584052/whatsfortea/FoodAtHomeItem.java
UTF-8
649
2.421875
2
[]
no_license
package com.example.n0584052.whatsfortea; import java.io.Serializable; /** * Created by joshh on 22/03/2018. */ public class FoodAtHomeItem implements Serializable { private String foodAtHomeName; private String foodAtHomeQuantity; public void setFoodAtHomeName(String foodAtHomeName) { this.foodAtHomeName = foodAtHomeName; } public void setFoodAtHomeQuantity(String foodAtHomeQuantity) { this.foodAtHomeQuantity = foodAtHomeQuantity; } public String getFoodAtHomeName(){ return foodAtHomeName; } public String getFoodAtHomeQuantity(){ return foodAtHomeQuantity; } }
true
0327342071e0d5e9c9ebaee8551a6ec9528b60eb
Java
EIPsilly/WebSpace
/vueProject/recycle_system/recycle_systeml_springboot/src/main/java/com/example/recycle_system_springboot/pojo/dto/CollectorRegisterDto.java
UTF-8
400
1.679688
2
[]
no_license
package com.example.recycle_system_springboot.pojo.dto; import lombok.Data; @Data public class CollectorRegisterDto { private String collectorName; private String userName; private String password; private String repassword; private String phone; private String idcardNumber; private String siteName; private Double latitude; private Double longitude; }
true
b609a301d10a88a7ded0e572a9d93db17acad084
Java
mvcorrea/LS-1617-1
/src/main/java/pt/isel/ls/Formatters/WriterTag/TagCollection2HTML.java
UTF-8
4,156
2.515625
3
[]
no_license
package pt.isel.ls.Formatters.WriterTag; import pt.isel.ls.Containers.CheckList; import pt.isel.ls.Containers.Tag; import pt.isel.ls.Formatters.WebFormatter.WebDocument; import pt.isel.ls.Formatters.WebFormatter.WebTag; import java.io.IOException; import java.util.LinkedList; public class TagCollection2HTML { public String toHTML(LinkedList<Tag> tgs) throws IOException { WebDocument doc = new WebDocument(); doc.setTitle("Tags"); // menu WebTag menu = new WebTag("ul").setAttr("class", "nav navbar-nav navbar-right"); menu.addContent(new WebTag("li").addContent(new WebTag("a").setAttr("href","javascript:history.go(-1)").setData("Back"))); doc.setMenu(menu); WebTag main = new WebTag("div").setAttr("class", "container"); WebTag tableT = new WebTag("table").setAttr("class", "table table-striped").nl(); WebTag theadT = new WebTag("thead").nl(); theadT.addContent(new WebTag("th").setData("Name")); theadT.addContent(new WebTag("th").setData("Color")); tableT.addContent(theadT); WebTag tbodyT = new WebTag("tbody").nl(); tgs.forEach(tag -> { // String tags = chk.tags.stream().map(x -> x.tagName).collect(Collectors.joining(", ")); WebTag row = new WebTag("tr").nl(); // dead end row.addContent(new WebTag("td").addContent(new WebTag("a").setAttr("href","tags/"+tag.tagId).setData(tag.tagName))); //row.addContent(new WebTag("td").setData(tag.tagName)); row.addContent(new WebTag("td").setData(tag.tagColor)); tbodyT.addContent(row); }); tableT.addContent(tbodyT); // FORM WebTag form = new WebTag("form").setAttr("method", "post").setAttr("action", "/tags").setAttr("class",""); WebTag formContainer = new WebTag("div").setAttr("class", "row form-centered "); WebTag line0 = new WebTag("div").setAttr("class", "col-xs-2"); formContainer.addContent(line0); WebTag line1 = new WebTag("div").setAttr("class", "col-xs-3"); line1.addContent(new WebTag("label").setAttr("for", "name").setAttr("class", "sr-only").setData("Name")); line1.addContent(new WebTag("input").setAttr("type", "text").setAttr("name", "name").setAttr("class","form-control").setAttr("placeholder", "Name")); formContainer.addContent(line1); // WebTag line2 = new WebTag("div").setAttr("class", "col-xs-3"); // line2.addContent(new WebTag("label").setAttr("for", "name").setAttr("class", "sr-only").setData("Color")); // line2.addContent(new WebTag("input").setAttr("type", "text").setAttr("name", "color").setAttr("class","form-control").setAttr("placeholder", "Color")); // formContainer.addContent(line2); WebTag line2 = new WebTag("div").setAttr("class", "col-xs-3"); line2.addContent(new WebTag("select").setAttr("for", "name").setAttr("class", "form-control").setAttr("id", "colorlst").setAttr("name", "color")); //line2.addContent(new WebTag("input").setAttr("type", "text").setAttr("name", "color").setAttr("class","form-control").setAttr("placeholder", "Color")); formContainer.addContent(line2); WebTag line3 = new WebTag("div").setAttr("class", "col-xs-2"); line3.addContent(new WebTag("button").setAttr("type", "submit").setAttr("class", "btn btn-default").setData("Create Tag")); formContainer.addContent(line3); form.addContent(formContainer); main.addContent(new WebTag("h4").setAttr("class", "text-center").setData("Tags")); main.addContent(tableT); main.addContent(new WebTag("br")); main.addContent(new WebTag("h4").setAttr("class", "text-center").setData("Add New Tag")); main.addContent(form); main.addContent(new WebTag("br")); doc.addElem(main); // WebTag list = new WebTag("ul"); // tgs.forEach(tg -> { // list.addContent(new WebTag("li").setData(tg.tagName +" - "+ tg.tagColor)); // }); // // doc.addElem(list); return doc.toString(); } }
true
f91bf6deea937ea86b2fa750f58e6338ead0b5c8
Java
verynb/torchbackend
/torch_pj/src/main/java/com/torch/interfaces/userGroup/command/UserGroupChangeCommand.java
UTF-8
806
2.03125
2
[]
no_license
package com.torch.interfaces.userGroup.command; import org.hibernate.validator.constraints.NotBlank; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(value = "用户-用户组增加删除") public class UserGroupChangeCommand { @NotBlank(message = "group.groupid.required") @ApiModelProperty(value = "groupid", required = true) private String groupid; @NotBlank(message = "user.username.required") @ApiModelProperty(value = "用户登录名", required = true) private String username; public String getGroupid() { return groupid; } public void setGroupid(String groupid) { this.groupid = groupid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } // }
true
18d50f7e70521a3782fc133c1795aa455e77b448
Java
antoineCharpentier-19/Selenium-DSL
/org.xtext.imt.selenium/src-gen/org/xtext/example/mydsl/selenium/impl/ElementImpl.java
UTF-8
11,106
1.523438
2
[]
no_license
/** * generated by Xtext 2.19.0 */ package org.xtext.example.mydsl.selenium.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.xtext.example.mydsl.selenium.By; import org.xtext.example.mydsl.selenium.Element; import org.xtext.example.mydsl.selenium.SeleniumPackage; import org.xtext.example.mydsl.selenium.Variable; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Element</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.xtext.example.mydsl.selenium.impl.ElementImpl#getType <em>Type</em>}</li> * <li>{@link org.xtext.example.mydsl.selenium.impl.ElementImpl#getNumber <em>Number</em>}</li> * <li>{@link org.xtext.example.mydsl.selenium.impl.ElementImpl#getSelector <em>Selector</em>}</li> * <li>{@link org.xtext.example.mydsl.selenium.impl.ElementImpl#getTarget <em>Target</em>}</li> * <li>{@link org.xtext.example.mydsl.selenium.impl.ElementImpl#getVar <em>Var</em>}</li> * </ul> * * @generated */ public class ElementImpl extends ClickImpl implements Element { /** * The default value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected static final String TYPE_EDEFAULT = null; /** * The cached value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected String type = TYPE_EDEFAULT; /** * The default value of the '{@link #getNumber() <em>Number</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNumber() * @generated * @ordered */ protected static final int NUMBER_EDEFAULT = 0; /** * The cached value of the '{@link #getNumber() <em>Number</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNumber() * @generated * @ordered */ protected int number = NUMBER_EDEFAULT; /** * The cached value of the '{@link #getSelector() <em>Selector</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSelector() * @generated * @ordered */ protected By selector; /** * The default value of the '{@link #getTarget() <em>Target</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTarget() * @generated * @ordered */ protected static final String TARGET_EDEFAULT = null; /** * The cached value of the '{@link #getTarget() <em>Target</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTarget() * @generated * @ordered */ protected String target = TARGET_EDEFAULT; /** * The cached value of the '{@link #getVar() <em>Var</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVar() * @generated * @ordered */ protected Variable var; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ElementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SeleniumPackage.Literals.ELEMENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getType() { return type; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setType(String newType) { String oldType = type; type = newType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SeleniumPackage.ELEMENT__TYPE, oldType, type)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int getNumber() { return number; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setNumber(int newNumber) { int oldNumber = number; number = newNumber; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SeleniumPackage.ELEMENT__NUMBER, oldNumber, number)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public By getSelector() { return selector; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSelector(By newSelector, NotificationChain msgs) { By oldSelector = selector; selector = newSelector; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SeleniumPackage.ELEMENT__SELECTOR, oldSelector, newSelector); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setSelector(By newSelector) { if (newSelector != selector) { NotificationChain msgs = null; if (selector != null) msgs = ((InternalEObject)selector).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - SeleniumPackage.ELEMENT__SELECTOR, null, msgs); if (newSelector != null) msgs = ((InternalEObject)newSelector).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - SeleniumPackage.ELEMENT__SELECTOR, null, msgs); msgs = basicSetSelector(newSelector, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SeleniumPackage.ELEMENT__SELECTOR, newSelector, newSelector)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getTarget() { return target; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setTarget(String newTarget) { String oldTarget = target; target = newTarget; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SeleniumPackage.ELEMENT__TARGET, oldTarget, target)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Variable getVar() { if (var != null && var.eIsProxy()) { InternalEObject oldVar = (InternalEObject)var; var = (Variable)eResolveProxy(oldVar); if (var != oldVar) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, SeleniumPackage.ELEMENT__VAR, oldVar, var)); } } return var; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Variable basicGetVar() { return var; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setVar(Variable newVar) { Variable oldVar = var; var = newVar; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SeleniumPackage.ELEMENT__VAR, oldVar, var)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SeleniumPackage.ELEMENT__SELECTOR: return basicSetSelector(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SeleniumPackage.ELEMENT__TYPE: return getType(); case SeleniumPackage.ELEMENT__NUMBER: return getNumber(); case SeleniumPackage.ELEMENT__SELECTOR: return getSelector(); case SeleniumPackage.ELEMENT__TARGET: return getTarget(); case SeleniumPackage.ELEMENT__VAR: if (resolve) return getVar(); return basicGetVar(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SeleniumPackage.ELEMENT__TYPE: setType((String)newValue); return; case SeleniumPackage.ELEMENT__NUMBER: setNumber((Integer)newValue); return; case SeleniumPackage.ELEMENT__SELECTOR: setSelector((By)newValue); return; case SeleniumPackage.ELEMENT__TARGET: setTarget((String)newValue); return; case SeleniumPackage.ELEMENT__VAR: setVar((Variable)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SeleniumPackage.ELEMENT__TYPE: setType(TYPE_EDEFAULT); return; case SeleniumPackage.ELEMENT__NUMBER: setNumber(NUMBER_EDEFAULT); return; case SeleniumPackage.ELEMENT__SELECTOR: setSelector((By)null); return; case SeleniumPackage.ELEMENT__TARGET: setTarget(TARGET_EDEFAULT); return; case SeleniumPackage.ELEMENT__VAR: setVar((Variable)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SeleniumPackage.ELEMENT__TYPE: return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type); case SeleniumPackage.ELEMENT__NUMBER: return number != NUMBER_EDEFAULT; case SeleniumPackage.ELEMENT__SELECTOR: return selector != null; case SeleniumPackage.ELEMENT__TARGET: return TARGET_EDEFAULT == null ? target != null : !TARGET_EDEFAULT.equals(target); case SeleniumPackage.ELEMENT__VAR: return var != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (type: "); result.append(type); result.append(", number: "); result.append(number); result.append(", target: "); result.append(target); result.append(')'); return result.toString(); } } //ElementImpl
true
2761272cc97b17f3f32793995935c2c7b8cb46ed
Java
JeromeMillot/AgoroleREST
/src/main/java/fr/agrorole/dnd/dao/CharacterDAOImpl.java
UTF-8
3,518
2.5
2
[]
no_license
package fr.agrorole.dnd.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Query; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import fr.agrorole.dnd.dto.PJ; import fr.agrorole.dnd.interfaces.ICharacterDAO; public class CharacterDAOImpl implements ICharacterDAO { private EntityManager entityManager; private static Logger logger = LogManager.getLogger(CharacterDAOImpl.class); @Override public void addCharacter(PJ pj) { // Debut de transaction EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { entityManager.persist(pj); transaction.commit(); } catch (Exception e) { transaction.rollback(); if (logger.isErrorEnabled()) { logger.debug(e); } } } @Override public PJ getCharacter(String name, String userId) { // Debut de transaction EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { PJ pj = entityManager.find(PJ.class, name+userId); return pj; } catch (Exception e) { transaction.rollback(); if (logger.isErrorEnabled()) { logger.debug(e); } } return null; } @Override public List<PJ> getAllCharacterList() { // Debut de transaction EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { Query query = entityManager.createQuery("select p from PJ p"); return query.getResultList(); } catch (Exception e) { transaction.rollback(); if (logger.isErrorEnabled()) { logger.debug(e); } } return null; } @Override public List<PJ> getCharacterListByKW(String keyWord) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { Query query = entityManager.createQuery("select p from PJ p where p.name like :x"); query.setParameter("x", "%"+keyWord+"%"); return query.getResultList(); } catch (Exception e) { transaction.rollback(); if (logger.isErrorEnabled()) { logger.debug(e); } } return null; } @Override public List<PJ> getCharacterListByUserName(String userName) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { Query query = entityManager.createQuery("select p from PJ p where p.joueur = :j"); query.setParameter("j", userName); return query.getResultList(); } catch (Exception e) { transaction.rollback(); if (logger.isErrorEnabled()) { logger.debug(e); } } return null; } @Override public void updateCharacter(PJ pj) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { entityManager.merge(pj); } catch (Exception e) { transaction.rollback(); if (logger.isErrorEnabled()) { logger.debug(e); } } } @Override public void deleteCharacter(String charName, String userId) { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { Query query = entityManager.createQuery("DELETE FROM PJ p WHERE p.name = :n AND p.user = :u"); query.setParameter("n", charName); query.setParameter("u", userId); query.executeUpdate(); } catch (Exception e) { transaction.rollback(); if (logger.isErrorEnabled()) { logger.debug(e); } } } }
true
7bc44c61f43b2307404b855d7f18f855ff9176c6
Java
geegloirco/geeglo-store
/store-orm/src/main/java/ir/geeglo/dev/store/data/dao/QueryConditionStruct.java
UTF-8
1,115
2.3125
2
[ "Apache-2.0" ]
permissive
package ir.geeglo.dev.store.data.dao; import java.util.List; public class QueryConditionStruct<T> { private String field; private List<T> filters; private FilterType filterType; public QueryConditionStruct() { } public QueryConditionStruct(String field, List<T> filters) { this(field, filters, FilterType.IN_LIST); } public QueryConditionStruct( String field, List<T> filters, FilterType filterType) { this.field = field; this.filters = filters; this.filterType = filterType; } public String getField() { return field; } public void setField(String field) { this.field = field; } public List<T> getFilters() { return filters; } public void setFilters(List<T> filters) { this.filters = filters; } public FilterType getFilterType() { return filterType; } public void setFilterType(FilterType filterType) { this.filterType = filterType; } public enum FilterType { IN_LIST, LIKE } }
true
4bce93ef8dbe66fe71e4733a8dbda83997bb20fa
Java
ranass/ReqCycle
/plugins/org.eclipse.reqcycle.traceability.cache/src/org/eclipse/reqcycle/traceability/cache/AbstractCachedTraceabilityEngine.java
UTF-8
12,687
1.765625
2
[]
no_license
package org.eclipse.reqcycle.traceability.cache; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.inject.Inject; import org.eclipse.reqcycle.core.ILogger; import org.eclipse.reqcycle.traceability.builder.IBuildingTraceabilityEngine; import org.eclipse.reqcycle.traceability.builder.ITraceabilityBuilder; import org.eclipse.reqcycle.traceability.builder.exceptions.BuilderException; import org.eclipse.reqcycle.traceability.cache.predicates.FilterPredicate; import org.eclipse.reqcycle.traceability.engine.Request; import org.eclipse.reqcycle.traceability.engine.Request.Couple; import org.eclipse.reqcycle.traceability.engine.Request.DEPTH; import org.eclipse.reqcycle.traceability.exceptions.EngineException; import org.eclipse.reqcycle.traceability.model.Link; import org.eclipse.reqcycle.traceability.model.Pair; import org.eclipse.reqcycle.traceability.model.StopCondition; import org.eclipse.reqcycle.traceability.model.TType; import org.eclipse.reqcycle.traceability.model.scopes.CompositeScope; import org.eclipse.reqcycle.traceability.model.scopes.IScope; import org.eclipse.reqcycle.traceability.predicates.TraceabilityPredicates; import org.eclipse.reqcycle.uri.IReachableManager; import org.eclipse.reqcycle.uri.functions.URIFunctions; import org.eclipse.reqcycle.uri.model.Reachable; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchListener; import org.eclipse.ui.PlatformUI; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Sets; public abstract class AbstractCachedTraceabilityEngine implements IBuildingTraceabilityEngine { private String cachePath = determineDataBasePath(); public static String HIDDEN_PROJET_NAME = "reqCycleHiddenProject"; @Inject ITraceabilityBuilder builder; @Inject protected IReachableManager manager; @Inject ILogger logger; private Set<Reachable> allTraceabilities = new HashSet<Reachable>(); public AbstractCachedTraceabilityEngine() { PlatformUI.getWorkbench().addWorkbenchListener( new IWorkbenchListener() { @Override public boolean preShutdown(IWorkbench workbench, boolean forced) { return true; } @Override public void postShutdown(IWorkbench workbench) { environmentClosed(); } }); } /** * This method returns a database path, in case of non Eclipse usage a * temporary folder is created * * @nu * @return */ private String determineDataBasePath() { // Activator activator = Activator.getDefault(); // if (activator != null){ // if (activator.getStateLocation() != null && // activator.getStateLocation().toString().length() > 0){ // return // activator.getStateLocation().toString()+"/"+HIDDEN_PROJET_NAME; // } // } File f = new File(Activator.getDefault().getStateLocation().toString()); File f2 = new File(f.getAbsolutePath() + "/" + HIDDEN_PROJET_NAME + "/"); f2.mkdirs(); return f2.getAbsolutePath(); } protected String getCachePath() { return cachePath; } protected abstract void environmentClosed(); protected void cacheCheck(Reachable traceable) { boolean debug = logger.isDebug(Activator.OPTIONS_DEBUG, Activator.getDefault()); if (!isCacheOk(traceable)) { if (debug) { logger.trace(String.format( "cache default for %s build starting", traceable .trimFragment().toString())); } build(traceable); if (debug) { logger.trace(String.format("build for %s ended", traceable .trimFragment().toString())); } } else { if (debug) { logger.trace(String.format("cache for %s ok", traceable .trimFragment().toString())); } } } @Override public Iterator<Pair<Link, Reachable>> getTraceability(Request... requests) throws EngineException { long timeInNanos = 0; boolean debug = logger.isDebug(Activator.OPTIONS_DEBUG, Activator.getDefault()); if (debug) { timeInNanos = System.nanoTime(); } if (requests == null) { throw new EngineException("request can not be null"); } boolean checkCache = isCacheCheckNeeded(requests); if (checkCache) { checkScope(getScope(requests)); } if (debug) { if (checkCache) { long timeInMsc = (System.nanoTime() - timeInNanos) / 1000000; logger.trace(String.format("Cache checked in %d ms", timeInMsc)); } else { logger.trace(String .format("Cache checked disabled via request")); } } Iterator<Pair<Link, Reachable>> result = Iterators.emptyIterator(); for (Request request : requests) { // Scope and Filter are used to validate or invalidate paths so // they can be combined Predicate<Pair<Link, Reachable>> requestPredicate = TraceabilityPredicates .newIsInScopePredicate(request.getScope()); if (request.getFilter() != null) { requestPredicate = Predicates.and( new FilterPredicate(request.getFilter()), requestPredicate); } Iterable<Couple> couples = request.getCouples(); if (!couples.iterator().hasNext()) { if (request.getDepth() == DEPTH.ONE) { throw new EngineException( "for a couple with source equals to null the request shall be infinite"); } else { result = Iterators.concat( result, doGetAllTraceability(request.getDirection(), requestPredicate)); } } // for each couple an traceability iterable is computed for (Couple c : couples) { // if the source is null it means the engine needs to return all // the traceability and the request depth shall be equals to // INFINITE if (c.getSource() == null) { if (request.getDepth() == DEPTH.ONE) { throw new EngineException( "for a couple with source equals to null the request shall be infinite"); } else { result = Iterators.concat( result, doGetAllTraceability(request.getDirection(), requestPredicate)); } } else { // when the target is equals to null it is a prospective // analysis if (c.getStopCondition() == null) { // for a depth equals to infinite the traceability shall // be // complete if (request.getDepth() == DEPTH.INFINITE) { result = Iterators.concat( result, doGetTraceability(c.getSource(), request.getDirection(), requestPredicate)); // otherwise just the first level shall be complete } else if (request.getDepth() == DEPTH.ONE) { result = Iterators.concat( result, doGetOneLevelTraceability(c.getSource(), request.getDirection(), requestPredicate)); } // when the target is different to null a search shall // be // performed } else { if (request.getDepth() == DEPTH.INFINITE) { result = Iterators.concat( result, doGetTraceability(c.getSource(), c.getStopCondition(), request.getDirection(), requestPredicate)); } else { // except when the depth is equals to one in this // case // it can be computed using a filter result = Iterators.concat( result, doGetTraceability(c.getSource(), c .getStopCondition(), request .getDirection(), Predicates.and( requestPredicate, new TargetEqualsPredicate(c .getStopCondition())))); } } } } } if (debug) { timeInNanos = System.nanoTime() - timeInNanos; long timeInMsc = timeInNanos / 1000000; logger.trace(String.format( "Traceability computed in %d ms (including cache check)", timeInMsc)); } return result; } public boolean isCacheCheckNeeded(Request... requests) { // all the request shall say NO to not check the cache int nbFalse = 0; int i = 0; for (Request r : requests) { Object property = r.getProperty(OPTION_CHECK_CACHE); boolean checkCache = true; if (property instanceof Boolean) { checkCache = (Boolean) property; } if (!checkCache) { nbFalse++; } i++; } return !(nbFalse == i); } protected IScope getScope(Request[] requests) { CompositeScope compo = new CompositeScope(Iterables.transform( Arrays.asList(requests), new Function<Request, IScope>() { public IScope apply(Request r) { return r.getScope(); } })); return compo; } protected void checkScope(IScope scope) { if (scope != null) { Iterator<Reachable> i = scope.getReachables(); while (i.hasNext()) { Reachable next = i.next(); cacheCheck(next); } } } protected abstract Iterator<Pair<Link, Reachable>> doGetAllTraceability( DIRECTION direction, Predicate<Pair<Link, Reachable>> requestPredicate); protected abstract Iterator<Pair<Link, Reachable>> doGetTraceability( Reachable source, DIRECTION direction, Predicate<Pair<Link, Reachable>> predicate); protected abstract Iterator<Pair<Link, Reachable>> doGetOneLevelTraceability( Reachable source, DIRECTION direction, Predicate<Pair<Link, Reachable>> predicate); protected abstract Iterator<Pair<Link, Reachable>> doGetTraceability( Reachable source, StopCondition stopCondition, DIRECTION direction, Predicate<Pair<Link, Reachable>> predicate); protected void build(Reachable traceable) { // TODO manage clean of the cache and transaction try { Iterable<Link> links = getLinksForTraceable(traceable); builder.build(traceable, this, false); Iterable<Link> newLinks = getLinksForTraceable(traceable); Iterable<Link> linksToTag = getLinksToTag(links, newLinks); tagDeletedRelationShips(linksToTag); } catch (BuilderException e) { // TODO error management } } protected abstract Iterable<Reachable> getEntriesFor(Reachable reachable); protected Iterable<Link> getLinksToTag(Iterable<Link> oldLinks, Iterable<Link> newLinks) { if (newLinks == null) { newLinks = Sets.newHashSet(); } if (oldLinks == null) { oldLinks = Sets.newHashSet(); } final Set<Link> newLinkSet = Sets.newHashSet(); return Iterables.filter(oldLinks, new Predicate<Link>() { @Override public boolean apply(Link l) { return !newLinkSet.contains(l); } }); } protected abstract void tagDeletedRelationShips(Iterable<Link> linksToTag); public abstract Iterable<Link> getLinksForTraceable(Reachable reachable); protected abstract boolean isCacheOk(Reachable reachable); @Override public void newUpwardRelation(Object traceabilityObject, Object resource, Object source, List<? extends Object> targets, TType kind) { Function<Object, Reachable> obj2RO = URIFunctions .newObject2ReachableFunction(); Reachable resourceReachable = obj2RO.apply(resource); Reachable sourceR = obj2RO.apply(source); Reachable traceaReachable = obj2RO.apply(traceabilityObject); List<Reachable> targetsR = Lists.newArrayList(Iterables.transform( targets, obj2RO)); if (sourceR != null && Iterables.filter(targetsR, Predicates.notNull()).iterator() .hasNext()) { allTraceabilities.remove(traceaReachable); newUpwardRelation(traceaReachable, resourceReachable, sourceR, targetsR, kind); } } public abstract void newUpwardRelation(Reachable traceaReachable, Reachable container, Reachable source, List<Reachable> targets, TType kind); @Override public void startBuild(Reachable reachable) { // the build is starting it is the moment to remove the corresponding // entries allTraceabilities = Sets.newHashSet(getEntriesFor(reachable)); } @Override public void endBuild(Reachable reachable) { // for each new upward relation ship the existing one is removed from // the list // it remains the deleted/moved one for (Reachable r : allTraceabilities) { removeTraceabilityLink(r); } allTraceabilities.clear(); } protected abstract void removeTraceabilityLink(Reachable r); @Override public void errorOccurs(Reachable reachable, Throwable t) { logger.error(t.getMessage()); t.printStackTrace(); // DO NOTHING } @Override public boolean needsBuild(Reachable reachable) { return !isCacheOk(reachable); } private class TargetEqualsPredicate implements Predicate<Pair<Link, Reachable>> { private StopCondition condition; public TargetEqualsPredicate(StopCondition condition) { this.condition = condition; } public boolean apply(Pair<Link, Reachable> pair) { return condition.apply(pair); } } }
true
3a0df2eb63135f012f89ddaefd90a9fc6cd7aabc
Java
xyy112121/TbeaCloudBusinessNew
/app/src/main/java/com/example/programmer/tbeacloudbusiness/activity/my/set/model/NotifyInfoResponseModel.java
UTF-8
523
1.796875
2
[]
no_license
package com.example.programmer.tbeacloudbusiness.activity.my.set.model; import com.example.programmer.tbeacloudbusiness.http.BaseResponseModel; import com.google.gson.annotations.SerializedName; /** * Created by programmer on 2017/8/17. */ public class NotifyInfoResponseModel extends BaseResponseModel { public DataBean data; public static class DataBean { public SettinginfoBean settinginfo; public static class SettinginfoBean { public String notifyonoroff; } } }
true
a94868cd862c7c5fc03a4ad7cc6f4808bcac2b89
Java
ehabibov/jagger
/chassis/core/src/main/java/com/griddynamics/jagger/storage/rdb/HibernateKeyValueStorage.java
UTF-8
7,660
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2010-2012 Grid Dynamics Consulting Services, Inc, All Rights Reserved * http://www.griddynamics.com * * This library is free software; you can redistribute it and/or modify it under the terms of * the Apache License; either * version 2.0 of the License, or any later version. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.griddynamics.jagger.storage.rdb; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.griddynamics.jagger.storage.KeyValueStorage; import com.griddynamics.jagger.storage.Namespace; import com.griddynamics.jagger.util.SerializationUtils; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import java.sql.SQLException; import java.util.*; public class HibernateKeyValueStorage extends HibernateDaoSupport implements KeyValueStorage { private static final Logger log = LoggerFactory.getLogger(HibernateKeyValueStorage.class); private int hibernateBatchSize; private int sessionTempDataCount=50; private String sessionId; public int getHibernateBatchSize() { return hibernateBatchSize; } public int getSessionTempDataCount() { return sessionTempDataCount; } @Required public void setSessionTempDataCount(int sessionTempDataCount) { if (sessionTempDataCount < 0) { log.warn("Session count can't be < 0; chassis.storage.temporary.data.session.count is equal {}.", sessionTempDataCount); return; } this.sessionTempDataCount = sessionTempDataCount; } @Required public void setHibernateBatchSize(int hibernateBatchSize) { this.hibernateBatchSize = hibernateBatchSize; } @Override public boolean isAvailable() { return false; } @Override public void initialize() { } @Override public void setSessionId(String sessionId) { this.sessionId=sessionId; } @Override public void put(Namespace namespace, String key, Object value) { getHibernateTemplate().persist(createKeyValue(namespace, key, value)); } @Override public void putAll(Namespace namespace, Multimap<String, Object> valuesMap) { Session session = null; int count = 0; try { session = getHibernateTemplate().getSessionFactory().openSession(); session.beginTransaction(); for (String key : valuesMap.keySet()) { Collection<Object> values = valuesMap.get(key); for (Object val : values) { session.save(createKeyValue(namespace, key, val)); count++; if (count % getHibernateBatchSize() == 0) { session.flush(); session.clear(); } } } session.getTransaction().commit(); } finally { if (session != null) { session.close(); } } } @Override public void deleteAll() { ArrayList<String> sessions = (ArrayList) getHibernateTemplate().find( "Select distinct k.sessionId from KeyValue k ORDER by k.sessionId"); if (sessions.size() == 0) return; if (sessionTempDataCount == 0) { log.warn("Session count limit is equal '0', all temporary data about sessions in KeyValue will be delete"); getHibernateTemplate().bulkUpdate("delete from KeyValue"); return; } final List<String> sessionsToDelete = Lists.newArrayList(); sessionsToDelete.add(sessionId); if (sessions.size() > sessionTempDataCount) { sessionsToDelete.addAll(sessions.subList(0, (sessions.size() - 1) - sessionTempDataCount)); } getHibernateTemplate().execute(new HibernateCallback<Void>() { @Override public Void doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery("delete from KeyValue where sessionId in (:sessionIds)"); query.setParameterList("sessionIds", sessionsToDelete); query.executeUpdate(); session.flush(); return null; } }); } @SuppressWarnings("unchecked") @Override public Object fetch(Namespace namespace, String key) { List<KeyValue> values = (List<KeyValue>) getHibernateTemplate() .find("from KeyValue kv where kv.namespace = ? and kv.key = ?", namespace.toString(), key); if (values.isEmpty()) { return null; } if (values.size() > 1) { throw new IllegalStateException("Use fetchAll"); } return SerializationUtils.deserialize(values.get(0).getData()); } @SuppressWarnings("unchecked") @Override public Collection<Object> fetchAll(Namespace namespace, String key) { List<KeyValue> entities = (List<KeyValue>) getHibernateTemplate().find( "from KeyValue kv where kv.namespace = ? and kv.key = ?", namespace.toString(), key); Collection<Object> result = Lists.newLinkedList(); for (KeyValue entity : entities) { result.add(SerializationUtils.deserialize(entity.getData())); } return result; } @SuppressWarnings("unchecked") @Override public Multimap<String, Object> fetchAll(Namespace namespace) { List<KeyValue> entities = (List<KeyValue>) getHibernateTemplate().find( "from KeyValue kv where kv.namespace = ?", namespace.toString()); Multimap<String, Object> result = ArrayListMultimap.create(); for (KeyValue entity : entities) { result.put(entity.getKey(), SerializationUtils.deserialize(entity.getData())); } return result; } @Override public Object fetchNotNull(Namespace namespace, String key) { Object result = fetch(namespace, key); if (result == null) { throw new IllegalStateException("Cannot find value for namespace " + namespace + " and key " + key); } return result; } private KeyValue createKeyValue(Namespace namespace, String key, Object value) { KeyValue keyvalue = new KeyValue(); keyvalue.setNamespace(namespace.toString()); keyvalue.setKey(key); keyvalue.setData(SerializationUtils.serialize(value)); keyvalue.setSessionId(sessionId); return keyvalue; } }
true
20e4ee865e26e43eca6854cf2546f06273442f33
Java
colinclarke/sandbox
/projectalgo/src/main/java/com/hcl/java8/FilterForEach.java
UTF-8
840
3.6875
4
[]
no_license
package com.hcl.java8; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class FilterForEach { public static void main(String[] args) { List<Employee> list = new ArrayList<Employee>(); list.add(new Employee(10, "Arun", 3010f, 'E')); list.add(new Employee(20, "Babu", 2020f, 'M')); list.add(new Employee(30, "Carol", 3030f, 'M')); list.add(new Employee(40, "Danny", 4040f, 'C')); list.add(new Employee(50, "Anthony", 5050f, 'M')); list.stream() .sorted((e1, e2) -> e1.getSalary().compareTo(e2.getSalary())) .forEach(System.out::println); System.out.println("Sort by name"); list.stream() .sorted((e1, e2) -> e1.getEmpName().compareTo(e2.getEmpName())) .forEach(System.out::println); //.forEach((emp) -> System.out.printf("name is %s%n", emp.getEmpName())); } }
true
f404819843ccae5ee2d114ca1cea59bae7680ce7
Java
jakubs21/testBalony
/src/main/java/pl/jakub/myWebsite/pages/ballonPage/BallonPageTest.java
UTF-8
923
2.28125
2
[]
no_license
package pl.jakub.myWebsite.pages.ballonPage; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import pl.jakub.myWebsite.cfg.WebDriverConfig; public class BallonPageTest { private boolean init = true; private BallonPageMethods ballonPageMethods; @BeforeMethod public void init(){ if(init){ WebDriverConfig.Initialize(); ballonPageMethods = PageFactory.initElements(WebDriverConfig.getWebDriverInstance(), BallonPageMethods.class); } } @Test public void startBalloonGame(){ ballonPageMethods.clickStartGame(); Assert.assertEquals(ballonPageMethods.getBalloon(),"12"); } @Test public void ballonGameEnd(){ Assert.assertEquals(ballonPageMethods.gameOver(),true); } }
true
6b570d009079b01cc41fea6ac254e5c4007aa2db
Java
ChoiSJ/spring_study
/spring-final/src/main/java/kr/co/jhta/controller/argumentResolver/LoginStudArgumentResolver.java
UTF-8
1,359
2.265625
2
[]
no_license
package kr.co.jhta.controller.argumentResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; import kr.co.jhta.service.user.StudentService; import kr.co.jhta.vo.stu.Student; public class LoginStudArgumentResolver implements HandlerMethodArgumentResolver { @Autowired StudentService stuService; @Override public boolean supportsParameter(MethodParameter parameter) { return Student.class.isAssignableFrom(parameter.getParameterType()); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); HttpSession session = request.getSession(true); Student student = (Student) session.getAttribute("LOGIN_USER"); if(student == null) { return new Student(); } return student; } }
true
efc55d6b4e217fe3d2775e78d11d9c15b792a9c0
Java
ccflyy/NVPlayer
/nvplayer/src/main/java/com/nesp/nvplayer/widget/NVPlayerBatteryView.java
UTF-8
9,141
1.976563
2
[ "Apache-2.0" ]
permissive
/* * * Copyright (c) 2019 NESP Technology Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * Unless required by applicable law or agreed to in writing, software * distributed under the License.See the License for the specific language governing permission and * limitations under the License. * * If you have any questions or if you find a bug, * please contact the author by email or ask for Issues. * * Author:JinZhaolu <1756404649@qq.com> */ package com.nesp.nvplayer.widget; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.os.BatteryManager; import android.util.AttributeSet; import android.view.View; import com.nesp.nvplayer.R; /** * @Team: NESP Technology * @Author: 靳兆鲁 * Email: 1756404649@qq.com * @Time: Created 2018/11/28 8:55 * @Project software_android_assistant **/ public class NVPlayerBatteryView extends View { private final PowerReceiver powerReceiver; private final Context context; private Matrix matrixLighting; private Bitmap bitmapLighting; private int height, width, lightingWidth, lightingHeight; private int mColor; private int orientation; private int mPower; private boolean isCharging = false; private float offsetElectricity; private float fullPowerWidth; private float strokeWidth; private Bitmap bitmapNewLighting; private boolean chargingAnimorEnable = false; public NVPlayerBatteryView(Context context) { this(context, null); } public NVPlayerBatteryView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public NVPlayerBatteryView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NVPlayerBatteryView); mColor = typedArray.getColor(R.styleable.NVPlayerBatteryView_NVPlayerBatteryColor, 0xFFFFFFFF); orientation = typedArray.getInt(R.styleable.NVPlayerBatteryView_NVPlayerBatteryOrientation, 0); mPower = typedArray.getInt(R.styleable.NVPlayerBatteryView_NVPlayerBatteryPower, 100); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_BATTERY_CHANGED); powerReceiver = new PowerReceiver(); context.registerReceiver(powerReceiver, filter); typedArray.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //对View上的內容进行测量后得到的View內容占据的宽度 width = getMeasuredWidth(); //对View上的內容进行测量后得到的View內容占据的高度 height = getMeasuredHeight(); strokeWidth = width / 20.f; matrixLighting = new Matrix(); bitmapLighting = BitmapFactory.decodeResource(getResources(), R.drawable.ic_nvplayer_lighting); lightingWidth = bitmapLighting.getWidth(); lightingHeight = bitmapLighting.getHeight(); matrixLighting.postScale(2 * height / (3f * lightingHeight), 2 * height / (3f * lightingHeight)); bitmapNewLighting = Bitmap.createBitmap(bitmapLighting, 0, 0, lightingWidth, lightingHeight, matrixLighting, true); fullPowerWidth = width - strokeWidth * 2; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //判断电池方向 horizontal: 0 vertical: 1 if (orientation == 0) { drawHorizontalBattery(canvas); } else { drawVerticalBattery(canvas); } } /** * 绘制水平电池 * * @param canvas */ private void drawHorizontalBattery(Canvas canvas) { Paint paint = new Paint(); paint.setColor(mColor); paint.setStyle(Paint.Style.STROKE); float strokeWidth_2 = strokeWidth / 2; paint.setStrokeWidth(strokeWidth); RectF r1 = new RectF(strokeWidth_2, strokeWidth_2, width - strokeWidth - strokeWidth_2, height - strokeWidth_2); //设置外边框颜色为黑色 paint.setColor(Color.WHITE); canvas.drawRect(r1, paint); paint.setStrokeWidth(0); paint.setStyle(Paint.Style.FILL); //画电池内矩形电量 if (!chargingAnimorEnable) offsetElectricity = (width - strokeWidth * 2) * mPower / 100.f; RectF r2 = new RectF(strokeWidth, strokeWidth, offsetElectricity, height - strokeWidth); //根据电池电量决定电池内矩形电量颜色 if (mPower < 30) { paint.setColor(Color.RED); } if (mPower >= 30 && mPower < 50) { paint.setColor(Color.BLUE); } if (mPower >= 50) { paint.setColor(Color.GREEN); } if (isCharging) paint.setColor(Color.GREEN); canvas.drawRect(r2, paint); //画电池头 RectF r3 = new RectF(width - strokeWidth, height * 0.25f, width, height * 0.75f); //设置电池头颜色为黑色 paint.setColor(Color.WHITE); canvas.drawRect(r3, paint); // 绘制文字 if (!isCharging) { paint.setColor(Color.WHITE); paint.setTextSize(width / 3f); canvas.drawText(String.valueOf(mPower), width / 2 - paint.measureText(String.valueOf(mPower)) / 2, height / 2 + 1.5f * paint.getFontMetrics().bottom, paint); } else { canvas.drawBitmap(bitmapNewLighting, (width - bitmapNewLighting.getWidth()) / 2.0f, (height - bitmapNewLighting.getHeight()) / 2.0f, paint); if (chargingAnimorEnable) { //充电动画 if (offsetElectricity <= fullPowerWidth - strokeWidth) { offsetElectricity = offsetElectricity + fullPowerWidth / 10; } else { offsetElectricity = (width - strokeWidth * 2) * mPower / 100.f; } } } } /** * 绘制垂直电池 * * @param canvas */ private void drawVerticalBattery(Canvas canvas) { Paint paint = new Paint(); paint.setColor(mColor); paint.setStyle(Paint.Style.STROKE); float strokeWidth = height / 20.0f; float strokeWidth2 = strokeWidth / 2; paint.setStrokeWidth(strokeWidth); int headHeight = (int) (strokeWidth + 0.5f); RectF rect = new RectF(strokeWidth2, headHeight + strokeWidth2, width - strokeWidth2, height - strokeWidth2); canvas.drawRect(rect, paint); paint.setStrokeWidth(0); float topOffset = (height - headHeight - strokeWidth) * (100 - mPower) / 100.0f; RectF rect2 = new RectF(strokeWidth, headHeight + strokeWidth + topOffset, width - strokeWidth, height - strokeWidth); paint.setStyle(Paint.Style.FILL); canvas.drawRect(rect2, paint); RectF headRect = new RectF(width / 4.0f, 0, width * 0.75f, headHeight); canvas.drawRect(headRect, paint); } /** * 设置电池电量 * * @param power */ public void setPower(int power, Boolean isCharging) { this.isCharging = isCharging; this.mPower = power; if (mPower < 0) { mPower = 100; } invalidate();//刷新VIEW } /** * 设置电池颜色 * * @param color */ public void setColor(int color) { this.mColor = color; invalidate(); } public void onDestroy() { context.unregisterReceiver(powerReceiver); } /** * 获取电池电量 * * @return */ public int getPower() { return mPower; } private static final String TAG = "BatteryView"; private class PowerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN); if (status == BatteryManager.BATTERY_STATUS_CHARGING) { setPower(intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1), true); } else { setPower(intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1), false); } } else { setPower(intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1), false); } } } }
true
1fd82cfcc225d554dc411921ed83d25f91738de5
Java
BanyLee/QYZ_Server
/xdb/src/xio/security/HmacMd5Hash.java
UTF-8
1,434
2.53125
3
[]
no_license
package xio.security; import com.goldhuman.Common.Octets; public final class HmacMd5Hash extends Security { private Octets k_opad = new Octets(64); private MD5Hash md5hash = new MD5Hash(); //protected HMAC_MD5Hash() { } public HmacMd5Hash() { } public Object clone() { try { HmacMd5Hash o = (HmacMd5Hash) super.clone(); o.k_opad = (Octets) (k_opad.clone()); o.k_opad.reserve(64); o.md5hash = (MD5Hash) md5hash.clone(); return o; } catch (Exception e) { e.printStackTrace(); } return null; } public void setParameter(Octets param) { Octets ipad = new Octets(64); int keylen = param.size(); if (keylen > 64) { Octets key = MD5Hash.doDigest(param); ipad.replace(key); k_opad.replace(key); keylen = key.size(); } else { ipad.replace(param); k_opad.replace(param); } int i = 0; for (; i < keylen; i++) { ipad.setByte(i, (byte) (ipad.getByte(i) ^ 0x36)); k_opad.setByte(i, (byte) (k_opad.getByte(i) ^ 0x5c)); } for (; i < 64; i++) { ipad.setByte(i, (byte) 0x36); k_opad.setByte(i, (byte) 0x5c); } ipad.resize(64); k_opad.resize(64); md5hash.doUpdate(ipad); } public Octets doUpdate(Octets o) { md5hash.doUpdate(o); return o; } public Octets doFinal(Octets digest) { md5hash.doFinal(digest); MD5Hash ctx = new MD5Hash(); ctx.doUpdate(k_opad); ctx.doUpdate(digest); return ctx.doFinal(digest); } }
true
799e65eccabaec0efbe544338e5aa971e90401e5
Java
leoleegit/jcommon-jutils
/src/main/java/org/jcommon/com/util/http/HttpRequest.java
UTF-8
15,936
1.875
2
[]
no_license
// ======================================================================== // Copyright 2012 leolee<workspaceleo@gmail.com> // 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.jcommon.com.util.http; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.security.KeyStore; import java.security.MessageDigest; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.log4j.Logger; import sun.misc.BASE64Encoder; public class HttpRequest implements Runnable { protected static Logger logger = Logger.getLogger(HttpRequest.class); public static SSLSocketFactory factory; public static Map<String, Integer> trust_host = new HashMap<String, Integer>(); public static final String GET = "GET"; public static final String POST = "POST"; public static final String DELETE = "DELETE"; protected String url_; protected HttpListener listener_; private String content_; private String charset_ = "UTF-8"; protected String method_; private String passphrase = "changeit"; private String user; private String password; private Properties properties = new Properties(); private Map<Object, Object> attributes = new HashMap<Object, Object>(); private boolean trusted = false; private Object handler; protected StringBuilder sResult = new StringBuilder(); private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); public HttpRequest(String url, String content, String charset, String method, HttpListener listener) { this.url_ = url; this.charset_ = charset; this.content_ = content; this.method_ = method; this.listener_ = listener; } public HttpRequest(String url, String content, String method, HttpListener listener) { this(url, content, "utf-8", method, listener); } public HttpRequest(String url, String content, String method, HttpListener listener, boolean trusted) { this(url, content, "utf-8", method, listener); this.trusted = trusted; } public HttpRequest(String url, String charset, HttpListener listener) { this(url, null, charset, "GET", listener); } public HttpRequest(String url, HttpListener listener) { this(url, null, "utf-8", "GET", listener); } public HttpRequest(String url, HttpListener listener, boolean trusted) { this(url, null, "utf-8", "GET", listener); this.trusted = trusted; } public void run() { String charsetName = this.charset_; URL url = null; HttpURLConnection httpConnection = null; InputStream httpIS = null; BufferedReader http_reader = null; try { url = new URL(this.url_); if ((this.url_ != null) && (this.url_.startsWith("https"))) { if(!this.trusted){ try { factory = verifyCert(); } catch (Exception e) { logger.error("verifyCert:", e); if (this.listener_ != null) this.listener_.onException(this, e); return; } } httpConnection = (HttpsURLConnection)url.openConnection(); if (factory != null) ((HttpsURLConnection)httpConnection).setSSLSocketFactory(factory); ((HttpsURLConnection)httpConnection).setHostnameVerifier(new NullHostnameVerifier()); } else { httpConnection = (HttpURLConnection)url.openConnection(); } httpConnection.setConnectTimeout(10000); httpConnection.setReadTimeout(10000); httpConnection.setRequestMethod(this.method_); if ((this.user != null) && (this.password != null)) { String userpass = new StringBuilder().append(this.user).append(":").append(this.password).toString(); String encoding = new BASE64Encoder().encode(userpass.getBytes()); String basicAuth = new StringBuilder().append("Basic ").append(encoding).toString(); httpConnection.setRequestProperty("Authorization", basicAuth); } if ("GET".equalsIgnoreCase(this.method_)) { httpConnection.setRequestProperty("Accept", "*/*"); } else if ("POST".equalsIgnoreCase(this.method_)) { httpConnection.setDoOutput(true); if(properties.getProperty("Content-Type")==null) httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); else httpConnection.setRequestProperty("Content-Type", properties.getProperty("Content-Type")); httpConnection.setRequestProperty("Content-Length", String.valueOf(this.content_.getBytes().length)); PrintWriter out = null; out = new PrintWriter(new OutputStreamWriter(httpConnection.getOutputStream(), charsetName)); out.print(this.content_); out.flush(); out.close(); } int responseCode = httpConnection.getResponseCode(); if (responseCode == 200) { httpIS = httpConnection.getInputStream(); http_reader = new BufferedReader(new InputStreamReader(httpIS, charsetName)); String line = null; while ((line = http_reader.readLine()) != null) { this.sResult.append(line); } if (this.listener_ != null) this.listener_.onSuccessful(this, this.sResult); } else if (responseCode >= 400) { httpIS = httpConnection.getErrorStream(); http_reader = new BufferedReader(new InputStreamReader(httpIS, charsetName)); String line = null; while ((line = http_reader.readLine()) != null) { this.sResult.append(line); } logger.info(new StringBuilder().append("[URL][response][failure]").append(this.sResult).append("\n").append(this.url_).toString()); if (this.listener_ != null) this.listener_.onFailure(this, this.sResult); } else { this.sResult.append(new StringBuilder().append("[URL][response][failure][code : ").append(responseCode).append(" ]").toString()); if (this.listener_ != null) this.listener_.onFailure(this, this.sResult); logger.info(new StringBuilder().append("[URL][response][failure][code : ").append(responseCode).append(" ]").append("\n").append(this.url_).toString()); } } catch (SocketTimeoutException e) { if (this.listener_ != null) this.listener_.onTimeout(this); logger.warn(new StringBuilder().append("[HttpReqeust]TimeOut:").append(this.url_).toString()); } catch (IOException e) { if (this.listener_ != null) this.listener_.onException(this, e); logger.warn(new StringBuilder().append("[HttpReqeust] error:").append(this.url_).append("\n").append(e).toString()); }catch (Exception e) { if (this.listener_ != null) this.listener_.onException(this, e); logger.warn(new StringBuilder().append("[HttpReqeust] error:").append(this.url_).append("\n").append(e).toString()); } finally { try { if (http_reader != null) http_reader.close(); if (httpIS != null) httpIS.close(); if (httpConnection != null) httpConnection.disconnect(); } catch (IOException e) { logger.error(new StringBuilder().append("[HttpReqeust]finally error:").append(this.url_).append("\n").append(e).toString()); if (this.listener_ != null) this.listener_.onException(this, e); } } } //https://10.193.32.57:8043/donut/do/servChat.do public SSLSocketFactory verifyCert() throws Exception { if ((this.url_ != null) && (this.url_.startsWith("https"))) { String host = this.url_.substring(this.url_.indexOf("/", 7) + 1, this.url_.indexOf("/", 9)); String[] c = host.split(":"); host = c[0]; int port = c.length == 1 ? 443 : Integer.parseInt(c[1]); if ((trust_host.containsKey(host)) && (factory != null) && (((Integer)trust_host.get(host)).intValue() == port)) { return factory; } char[] passphrase = this.passphrase.toCharArray(); char SEP = File.separatorChar; File dir = new File(new StringBuilder().append(System.getProperty("java.home")).append(SEP).append("lib").append(SEP).append("security").toString()); File file = new File(dir, "cacerts"); logger.info(new StringBuilder().append("Loading KeyStore ").append(file).append("...").toString()); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); factory = factory == null ? context.getSocketFactory() : factory; logger.info(new StringBuilder().append("factory:").append(factory).toString()); logger.info(new StringBuilder().append("Opening connection to ").append(host).append(":").append(port).append("...").toString()); SSLSocket socket = (SSLSocket)factory.createSocket(host, port); socket.setSoTimeout(10000); try { logger.info("Starting SSL handshake..."); socket.startHandshake(); socket.close(); trust_host.put(host, Integer.valueOf(port)); logger.info("certificate is already trusted"); return factory; } catch (SSLException e) { logger.warn("no certificate trusted"); X509Certificate[] chain = tm.chain; if (chain == null) { logger.warn("Could not obtain server certificate chain"); return null; } logger.info(new StringBuilder().append("Server sent ").append(chain.length).append(" certificate(s):").toString()); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; logger.info(new StringBuilder().append(" ").append(i + 1).append(" Subject ").append(cert.getSubjectDN()).toString()); logger.info(new StringBuilder().append(" Issuer ").append(cert.getIssuerDN()).toString()); sha1.update(cert.getEncoded()); logger.info(new StringBuilder().append(" sha1 ").append(toHexString(sha1.digest())).toString()); md5.update(cert.getEncoded()); logger.info(new StringBuilder().append(" md5 ").append(toHexString(md5.digest())).toString()); } logger.info("certificate to add to trusted keystore"); X509Certificate cert = chain[0]; String alias = new StringBuilder().append(host).append("-").append(1).toString(); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); trust_host.put(host, Integer.valueOf(port)); logger.info(cert); logger.info(new StringBuilder().append("Added certificate to keystore using alias '").append(alias).append("'").toString()); return factory; } } return null; } public void setPassphrase(String passphrase) { this.passphrase = passphrase; } public String getPassphrase() { return this.passphrase; } private static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 3); for (int b : bytes) { b &= 255; sb.append(HEXDIGITS[(b >> 4)]); sb.append(HEXDIGITS[(b & 0xF)]); sb.append(' '); } return sb.toString(); } public void setResult(StringBuilder sResult) { this.sResult = sResult; } public String getResult() { return this.sResult.toString(); } public String getContent() { return this.content_; } public void setContent(String content) { this.content_ = content; } public String getUrl() { return this.url_; } public void setUrl(String url) { this.url_ = url; } public void setProperties(Properties properties) { this.properties = properties; } public Properties getProperties() { return this.properties; } public Object getHandler() { return this.handler; } public void setHandler(Object handler) { this.handler = handler; } public void setProperty(String key, String value) { this.properties.put(key, value); } public void setAttribute(Object key, Object value){ this.attributes.put(key, value); } public Object getAttibute(Object key){ if(attributes.containsKey(key)) return attributes.get(key); return null; } public String getProperty(String key) { if (this.properties.containsKey(key)) return this.properties.getProperty(key); return null; } public HttpListener getListener(){ return listener_; } public void setAuthorization(String user, String password) { this.user = user; this.password = password; } public String getCharset() { return charset_; } public void setCharset(String charset_) { this.charset_ = charset_; } private static class SavingTrustManager implements X509TrustManager { private final X509TrustManager tm; private X509Certificate[] chain; SavingTrustManager(X509TrustManager tm) { this.tm = tm; } public X509Certificate[] getAcceptedIssuers() { //throw new UnsupportedOperationException(); return null; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { //throw new UnsupportedOperationException(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { //this.chain = chain; //this.tm.checkServerTrusted(chain, authType); } } private static class NullHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } }
true
34c3d9bbf4b825105e43abacc48a8057f498db70
Java
nickel-fang/study
/algorithm/src/main/java/com/jetsen/algorithm/other/A796_RotateString.java
UTF-8
658
3.46875
3
[]
no_license
package com.jetsen.algorithm.other; public class A796_RotateString { public static boolean rotateString(String s, String goal) { if (s == null || goal == null || s.length() != goal.length()) return false; if (s.equals(goal)) return true; for (int i = 1; i < s.length(); i++) { if (s.substring(0, i).equals(goal.substring(s.length() - i, s.length())) && s.substring(i, s.length()).equals(goal.substring(0, s.length() - i))) return true; } return false; } public static void main(String[] args) { System.out.println(rotateString("abcde", "cdeab")); } }
true
8f1ffbeb5fbb771ce812bd1bcf2f6bf7f450330f
Java
Raitoforce/libreria
/src/main/java/com/work/backendlibrary/controller/EscuelaController.java
UTF-8
3,149
2.09375
2
[]
no_license
package com.work.backendlibrary.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.work.backendlibrary.entity.Escuela; import com.work.backendlibrary.model.EscuelaModel; import com.work.backendlibrary.service.EscuelaService; @RestController @RequestMapping("/escuelas") public class EscuelaController { @Autowired @Qualifier("escuelaServiceImpl") EscuelaService service; @GetMapping("") public ResponseEntity<List<Escuela>> devolverEscuelas(){ List<Escuela> escuelas = service.listAllEscuelas(); return new ResponseEntity<List<Escuela>>(escuelas,HttpStatus.OK); } @GetMapping("/pagina") public ResponseEntity<List<EscuelaModel>> listAllpage(Pageable pageable) { List<EscuelaModel> escuelas = service.listpage(pageable); return new ResponseEntity<>(escuelas, HttpStatus.OK); } @GetMapping("/{clave}") public ResponseEntity<Escuela> consultaEscuela(@PathVariable("clave") String clave){ Escuela escuela=service.consultarEscuela(clave); return new ResponseEntity<Escuela>(escuela,HttpStatus.OK); } @GetMapping("/director/{id}") public ResponseEntity<List<Escuela>> consultaDirector(@PathVariable("id") int id){ List<Escuela> escuelas=service.consultarDirector(id); return new ResponseEntity<List<Escuela>>(escuelas,HttpStatus.OK); } @GetMapping("/zona={zona}") public ResponseEntity<List<Escuela>> consultaByZona(@PathVariable("zona")String zona){ List<Escuela> escuelas=service.findByZona(zona); return new ResponseEntity<List<Escuela>>(escuelas,HttpStatus.OK); } @PostMapping(value = "/nuevo") public ResponseEntity<String> insertar(@RequestBody Escuela escuela){ service.addEscuela(escuela); return new ResponseEntity<String>(HttpStatus.CREATED); } @DeleteMapping(path="/{clave}") public ResponseEntity<String> eliminarLibro(@PathVariable("clave") String clave){ service.removeEscuela(clave); return new ResponseEntity<String>(HttpStatus.OK); } @PutMapping(path="",consumes="application/json") public ResponseEntity<String> actualizarLibro(@RequestBody Escuela escuela){ service.updateEscuela(escuela); return new ResponseEntity<String>(HttpStatus.OK); } @GetMapping(value = "/search/clave={clave}") public ResponseEntity<Boolean> buscarXClave(@PathVariable String clave) { Boolean exist = service.EscuelaIsOnDB(clave); return new ResponseEntity<>(exist, HttpStatus.OK); } }
true
926354a9f351ae2a20279fa145955b10fda42734
Java
gnueyTc/one
/app/src/main/java/com/gnuey/one/ui/activity/read/ReadActivity.java
UTF-8
6,132
1.828125
2
[ "MIT" ]
permissive
package com.gnuey.one.ui.activity.read; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.gnuey.one.InitApp; import com.gnuey.one.R; import com.gnuey.one.Register; import com.gnuey.one.bean.activity.read.PlayAudioBean; import com.gnuey.one.bean.activity.read.ReadActivityBean; import com.gnuey.one.binder.activity.ReadActivityWebViewBinder; import com.gnuey.one.component.DaggerActivityComponent; import com.gnuey.one.ui.base.BaseActivity; import com.gnuey.one.utils.RxBus; import com.gnuey.one.utils.ToastUtils; import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter; import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.functions.Consumer; import me.drakeet.multitype.Items; import me.drakeet.multitype.MultiTypeAdapter; /** * Created by gnuey on 2018/11/26/026 */ public class ReadActivity extends BaseActivity implements ReadContract.View{ @Inject ReadPresenter mPresenter; @BindView(R.id.ly_twinkling) TwinklingRefreshLayout twinklingRefreshLayout; @BindView(R.id.recycle_view) RecyclerView recyclerView; @BindView(R.id.iv_play) ImageView imageView; private final static String TAG = ReadActivity.class.getSimpleName(); private MultiTypeAdapter adapter; private Items oldItems = new Items(); private String[] array; private Flowable<String> playAudioBeanObservable; private AnimationDrawable animationDrawable; @SuppressLint("AutoDispose") @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setAppComponent(); mPresenter.attachView(this); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)); twinklingRefreshLayout.setEnableRefresh(false); twinklingRefreshLayout.setEnableLoadmore(true); twinklingRefreshLayout.setTargetView(recyclerView); twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() { @Override public void onLoadMore(TwinklingRefreshLayout refreshLayout) { super.onLoadMore(refreshLayout); mPresenter.getCommontData(array[0],array[1]); } }); adapter = new MultiTypeAdapter(); Register.registerReadActivityItem(adapter); recyclerView.setAdapter(adapter); animationDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.anim_audio_loading); initData(); playAudioBeanObservable = RxBus.getInstance().register(ReadActivityWebViewBinder.TAG,String.class); playAudioBeanObservable.subscribe(new Consumer<String>() { @Override public void accept(String url){ if(url.equals(ReadActivityWebViewBinder.STOP_PLAYING)){ playService.stop(); playImage(false); }else { playService.play(url); playImage(true); } Log.e(TAG, "accept: "+ url); } }); } private void playImage(boolean isPlaying){ if(isPlaying){ imageView.setImageDrawable(animationDrawable); animationDrawable.start(); }else { imageView.setImageResource(R.drawable.float_player_pause); animationDrawable.stop(); } } private void initData(){ Bundle bundle = getIntent().getExtras(); array = bundle.getStringArray(TAG); if(array != null && array.length == 4){ mPresenter.getReadData(array[0],array[1],array[2],array[3]); mPresenter.getCommontData(array[0],array[1]); } } @Override protected int getLayoutId() { return R.layout.activity_read; } @Override protected void onResume() { super.onResume(); } private void setAppComponent(){ DaggerActivityComponent.builder() .appComponent(InitApp.getApplication().getAppComponent()) .build() .inject(this); } public static void startReadDetailActivity(Context context,String[] content){ Intent intent = new Intent(context,ReadActivity.class); Bundle bundle = new Bundle(); bundle.putStringArray(TAG,content); intent.putExtras(bundle); context.startActivity(intent); } @Override public void doSetCommontAdapter(List<?> list) { oldItems.addAll(list); Items items = new Items(oldItems); adapter.setItems(items); adapter.notifyDataSetChanged(); twinklingRefreshLayout.finishLoadmore(); } @Override public void doSetReadData(ReadActivityBean data) { oldItems.add(0,data.getWebBean()); if(data.getAuthorDataBean()!=null){ oldItems.add(1,data.getAuthorDataBean()); } adapter.setItems(oldItems); adapter.notifyDataSetChanged(); } @Override public void onShowLoading() { } @Override public void onHideLoading() { twinklingRefreshLayout.finishLoadmore(); } @Override public void onShowNetError() { twinklingRefreshLayout.finishLoadmore(); } @Override public void onShowNoMore() { twinklingRefreshLayout.finishLoadmore(); ToastUtils.showSingleToast(R.string.no_more_content); } @Override protected void onDestroy() { super.onDestroy(); RxBus.getInstance().unRegisterEach(ReadActivityWebViewBinder.TAG); mPresenter.detachView(); } }
true
d4df2496a71e51ca5fdfc9a8817c1305df04dc50
Java
nmfernandes/avanade
/src/test/java/CareersTest.java
UTF-8
3,464
2.4375
2
[]
no_license
import helpers.MessageFileToUser; import helpers.Utils; import org.junit.After; import org.junit.Assert; import org.junit.Test; import pageObjects.CareersPage; import pageObjects.ExploreCareersPage; import pageObjects.HomePage; import static helpers.Drivers.destroyLastDriver; /** * Test the search in the Explore Careers page. */ public class CareersTest { private static final String SESSION = "session1"; private static final String CITY1_KEY = "KRAKOW"; private static final String CITY2_KEY = "WARSAW"; private static final String CITY3_KEY = "RALEIGH"; private static final String COUNTRY1_KEY = "POLAND"; private static final String COUNTRY2_KEY = "ALL_LOCATIONS"; private static final String ROLE_KEY = "SOFTWARE_QA_ANALYST"; private static final String QUALIFICATION_KEY = "QUALIFICATION"; private static final int N_RESULTS_CITY1 = 5; private static final int N_RESULTS_CITY2 = 1; private static final int N_RESULTS_CITY3 = 1; public CareersTest() throws Exception { } private ExploreCareersPage support(String city, String country) throws Exception { String browser = Utils.getBrowser(); HomePage home = new HomePage(SESSION, browser); home.clickOnExploreCareersBtn(); CareersPage careersPage = new CareersPage(SESSION, browser); careersPage.clickOnExploreCareersBtn(); ExploreCareersPage exploreCareersPage = new ExploreCareersPage(SESSION, browser); exploreCareersPage.writeSearchBoxFilter(Utils.getResourceBundle().getString(city)); exploreCareersPage.selectCountry(Utils.getResourceBundle().getString(country)); return exploreCareersPage; } /** * Test if there is a total of 5 results for location Krakow */ @Test public void resultsLocation1Test() throws Exception { ExploreCareersPage exploreCareersPage = support(CITY1_KEY, COUNTRY1_KEY); exploreCareersPage.clickJobSearchBtn(); Assert.assertEquals(String.format(MessageFileToUser.WRONG_NUMBER_RESULTS), N_RESULTS_CITY1, exploreCareersPage.getNumberResults()); } /** * Test if there is at least 1 result for location Warsaw */ @Test public void resultsLocation2Test() throws Exception { ExploreCareersPage exploreCareersPage = support(CITY2_KEY, COUNTRY1_KEY); exploreCareersPage.clickJobSearchBtn(); Assert.assertTrue(String.format(MessageFileToUser.WRONG_NUMBER_RESULTS), exploreCareersPage.getNumberResults() >= N_RESULTS_CITY2); } /** * Test if one of the qualifications for job offer: Location: Raleigh/ Software QA Analyst is: Experience creating and implementing testing framework for web applications such as Selenium */ @Test public void resultsLocation3Test() throws Exception { ExploreCareersPage exploreCareersPage = support(CITY3_KEY, COUNTRY2_KEY); exploreCareersPage.selectRole(ROLE_KEY); exploreCareersPage.clickJobSearchBtn(); Assert.assertTrue(String.format(MessageFileToUser.WRONG_NUMBER_RESULTS), exploreCareersPage.getNumberResults() >= N_RESULTS_CITY3); exploreCareersPage.clickFirstResult(); exploreCareersPage.findByText(QUALIFICATION_KEY); } /** * After each test, quit driver */ @After public void tearDown() throws Exception { destroyLastDriver(); } }
true
6cdff01020c17dfdffb99e25ca675a630541fb64
Java
mennetorelli/The-Council-of-Four
/src/test/java/notifyTests/MarketNotifyTest.java
UTF-8
875
2.421875
2
[]
no_license
package notifyTests; import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Test; import clientUpdates.MarketUpdate; import server.model.Game; import server.model.player.Player; import server.serverNotifies.MarketServerNotify; public class MarketNotifyTest { @Test public void test() throws IOException { Game game= new Game(); List<Player> players = new ArrayList<>(); Player a = new Player("Andre"); players.add(a); game.start(players); List<Player> interestedPlayers= new ArrayList<>(); boolean startMarket= true; boolean closeMarket= false; MarketServerNotify notify= new MarketServerNotify(game, interestedPlayers, startMarket, closeMarket); assertEquals(MarketUpdate.class,notify.toClientNotify().getClass()); assertTrue(notify.sendTo()==interestedPlayers); } }
true
2a28770b50ec5fa3d8e1285fcc2240d3986ac3ff
Java
SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
/Corpus/eclipse.jdt.core/4945.java
UTF-8
162
2.3125
2
[ "MIT" ]
permissive
public class SomeClass { public void foo() { if ((x.getSomeLongValue == 100) || (x.getSomeOtherValue == 200)) { y = 5; } } }
true
266e9b6c9c50c9cfa2002cea4fbec1036ac0466b
Java
selvavelu/UpskillProject1
/final-framework-testng/src/com/training/pom/PropertyPage.java
UTF-8
11,681
1.96875
2
[]
no_license
package com.training.pom; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; public class PropertyPage { private WebDriver driver; public PropertyPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } //Click property Menu @FindBy(xpath = "//*[@id=\"menu-posts-property\"]/a/div[3]") WebElement ClickProperty; public void clickPropertyAction() { this.ClickProperty.click(); } //Click All properties Sub Menu @FindBy(xpath = "//*[@id=\"menu-posts-property\"]/ul/li[2]/a") WebElement ClickAllProperties; public void clickAllProperties() { this.ClickAllProperties.click(); } //*[@id="menu-posts-property"]/ul/li[3]/a @FindBy(xpath = "//*[@id=\"menu-posts-property\"]/ul/li[3]/a") WebElement ClickAddNew; public void clickAddNewProperties() { this.ClickAddNew.click(); } //Select Date drop down // @FindBy(xpath = "//*[@id=\"filter-by-date\"]") // @FindBy(id="filter-by-date") @FindBy(xpath = "//select[@name='m']") WebElement allDateDropDown; public void dateSelect(String month) { Select option = new Select(allDateDropDown); // option.selectByIndex(index); option.selectByValue(month); // this.deletebutton.click(); } //Apply Date filter button @FindBy(id = "post-query-submit") WebElement dateFilterButton; public void applyDateFilterButton() { this.dateFilterButton.click(); } //Click on Trash Link @FindBy(xpath = "//*[@id=\"wpbody-content\"]/div[3]/ul/li[4]/a") WebElement trashlink; public void trashlinkclick() { this.trashlink.click(); } //Mouse over trash row Link @FindBy(name = "post[]") // @FindBy(xpath="//*[@id=\"post-667\"]/td[1]") WebElement trashrow; public void rowMouseOver() { // WebElement element = driver.findElement(By.linkText("Product // Category")); Actions action = new Actions(driver); action.moveToElement(trashrow).build().perform(); } //restore click on MouseOver element // @FindBy(xpath="//*[@id=\"post[]\"]/td[1]/div[2]/span[1]/a") @FindBy(xpath = "//table//tbody//tr//td//span//a[contains(text(),'Restore')]") WebElement restorelink; public void restoreMouseOver() { Actions action = new Actions(driver); action.moveToElement(restorelink).click().build().perform(); } //Hidden Trash link Mouse over @FindBy(xpath = "//table//tbody//tr//td//span//a[contains(text(),'Trash')]") public WebElement trashHlink; public void trashHlinkMouseOver() { Actions action = new Actions(driver); action.moveToElement(trashHlink).click().build().perform(); } //Display Message @FindBy(xpath = "//*[@id=\"message\"]/p") public WebElement messageDisplay; public String displayMessage() { String CT = messageDisplay.getText(); return CT; } // ALL LINK CLICK @FindBy(xpath = "//*[@id=\"wpbody-content\"]/div[3]/ul/li[1]/a") WebElement allLink; public void allLinkClick() { this.allLink.click(); } //Restore click // @FindBy(xpath="//table//tbody//tr//td//strong[contains(text(),'Man')]") @FindBy(xpath = "//table/tbody//tr[1]//td[1]//strong") public WebElement displayRestore; public void displayRestore() { this.displayRestore.click(); } // launch home page in New window public void mouseNewLaunch() throws AWTException, InterruptedException { WebElement gmailtab = driver.findElement(By.xpath("//*[@id=\"wp-admin-bar-site-name\"]/a")); Actions act = new Actions(driver); act.contextClick(gmailtab).perform(); Thread.sleep(1000); Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_DOWN); robot.keyPress(KeyEvent.VK_DOWN); robot.keyPress(KeyEvent.VK_ENTER); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_TAB); Thread.sleep(3000); ArrayList<String> googletabs = new ArrayList<>(driver.getWindowHandles()); System.out.println("number of tabs opened=" + googletabs.size()); System.out.println("current url before switching " + driver.getCurrentUrl()); driver.switchTo().window(googletabs.get(1)).getTitle(); System.out.println("current url after switching " + driver.getCurrentUrl()); // driver.findElement(By.xpath("//*[@id=\"ajaxsearchlite1\"]/div/div[3]/form/input[1]")).sendKeys("RETC_051_2"); // driver.findElement(By.xpath("//*[@id=\"ajaxsearchlite1\"]/div/div[1]/div/svg")).click(); } //New screen property input and confirm the display public void newScreenPropertyInput(String sText) { driver.findElement(By.xpath("//input[@placeholder='Search here for Properties..']")).sendKeys(sText); driver.findElement(By.xpath("//div[@class=\'promagnifier\']//*[@version='1.1']")).click(); driver.findElement(By.xpath("//div[@class=\'resdrg\']//div[1]//div[1]//h3[1]")).click(); } //input and search @FindBy(xpath = "//input[@id='post-search-input']") WebElement propertySearch; // public String sText="RETC_"; public String sText = "prestige"; public void propertySearchInput() { propertySearch.sendKeys(sText); WebElement searchbutton = driver.findElement(By.id("search-submit")); searchbutton.click(); } @FindBy(xpath = "//input[@id='post-search-input']") WebElement propertySearch1; // public String sText="RETC_"; // public String sText="prestige"; public void propertySearchInput1(String ss) { propertySearch1.sendKeys(ss); WebElement searchbutton = driver.findElement(By.id("search-submit")); searchbutton.click(); } // hidden trash permanently link click in Trash @FindBy(xpath = "//table[1]/tbody[1]/tr[1]/td[1]/div[2]/span[2]/a[1]") WebElement trashHPermanent; public void trashHPermanentClick() { this.trashHPermanent.click(); } public void mouseclick() { driver.get("http://automate-apps.com/"); System.out.println(driver.getTitle()); Actions action = new Actions(driver); // WebElement element = driver.findElement(By.partialLinkText("SELENIUM // QUESTIONS")); WebElement element = driver.findElement(By.xpath("//*[@id=\"menu-item-1284\"]/a")); action.contextClick(element).build().perform(); // sendKeys(Keys.ARROW_UP).sendKeys(Keys.ENTER); // action.build().perform(); // Set<String> winid = driver.getWindowHandles(); // Iterator<String> iter = winid.iterator(); // iter.next(); // String tab = iter.next(); // driver.switchTo().window(tab); // System.out.println(driver.getTitle()); } // ******Regions function added here*********** // click Regions Menu under Properties @FindBy(xpath = "//*[@id=\"menu-posts-property\"]/ul/li[5]/a") WebElement clickRegions; public void clickRegions() { this.clickRegions.click(); } // Regions-- Start ADD NEW REGION Regions Menu under Properties // Input NAME in AddNewRegion Menu under Properties-Regions @FindBy(id = "tag-name") WebElement inputNameAddNewRegion; public void NameAddNewRegion(String Name) { this.inputNameAddNewRegion.clear(); this.inputNameAddNewRegion.sendKeys(Name); } // Input SLUG in AddNewRegion Menu under Properties-Regions @FindBy(id = "tag-slug") WebElement inputSlugAddNewRegion; public void SlugAddNewRegion(String Slug) { this.inputSlugAddNewRegion.clear(); this.inputSlugAddNewRegion.sendKeys(Slug); } // select drop down in Parent Region Menu under Properties-Regions @FindBy(id = "parent") WebElement sParetRegionAddNewRegion; public void selectParetRegionAddNewRegion(String p_region) { Select option = new Select(sParetRegionAddNewRegion); // option.selectByIndex(index); // option.selectByValue(p_region); option.selectByVisibleText(p_region); } // INPUT DESCRIPTION in ADD NEW Region Menu under Properties-Regions @FindBy(id="tag-description") WebElement inputDescAddNewRegion; public void DescAddNewRegion(String desc) { this.inputDescAddNewRegion.clear(); this.inputDescAddNewRegion.sendKeys(desc); } // click button ADD NEW REGION Regions Menu under Properties @FindBy(id="submit") WebElement buttonAddNewRegions; public void buttonAddNewRegionsClick(){ this.buttonAddNewRegions.click(); } //Region search input AND click @FindBy(id="tag-search-input") WebElement regionSearch; public void regionSearchInput(String ss) { this.regionSearch.clear(); this.regionSearch.sendKeys(ss);//Search Regions // WebElement searchbutton = driver.findElement(By.id("search-submit")); // WebElement searchbutton = driver.findElement(By.name("Search Regions")); //*[@id="search-submit"] WebElement searchbutton = driver.findElement(By.xpath("//*[@id=\"search-submit\"]")); searchbutton.click(); } // END ADD NEW REGION Regions Menu under Properties // Regions-- DB Start ADD NEW REGION Regions Menu under Properties // Input NAME in AddNewRegion Menu under Properties-Regions @FindBy(id = "tag-name") WebElement inputNameAddNewRegion1; public String NameAddNewRegionDB(String Name) { this.inputNameAddNewRegion1.clear(); this.inputNameAddNewRegion1.sendKeys(Name); return inputNameAddNewRegion1.getAttribute("value"); } // Input SLUG in AddNewRegion Menu under Properties-Regions @FindBy(id = "tag-slug") WebElement inputSlugAddNewRegion1; public String SlugAddNewRegionDB(String Slug) { this.inputSlugAddNewRegion1.clear(); this.inputSlugAddNewRegion1.sendKeys(Slug); return inputSlugAddNewRegion1.getAttribute("value"); } // select drop down in Parent Region Menu under Properties-Regions @FindBy(id = "parent") WebElement sParetRegionAddNewRegion1; public String selectParetRegionAddNewRegionDB(String p_region) { Select option = new Select(sParetRegionAddNewRegion1); // option.selectByIndex(index); // option.selectByValue(p_region); option.selectByVisibleText(p_region); return p_region; } // INPUT DESCRIPTION in ADD NEW Region Menu under Properties-Regions @FindBy(id="tag-description") WebElement inputDescAddNewRegion1; public String DescAddNewRegionDB(String desc) { this.inputDescAddNewRegion1.clear(); this.inputDescAddNewRegion1.sendKeys(desc); return inputDescAddNewRegion1.getAttribute("value"); } // click button ADD NEW REGION Regions Menu under Properties //id="tag-description"/ /* * Actions action = new Actions(driver); WebElement link * =driver.findElement(By.xpath( * "//button[text()='Double-Click Me To See Alert']")); * action.doubleClick(link).perform() */; /* * WebElement rightclickelement = driver.findElement(By.xpath( * "/html/body/div[1]/div[1]/div/section/div[5]/div[2]/div[2]/ul/li[1]/div/div[2]/h2/a" * )); Actions action = new Actions(driver); * action.moveToElement(rightclickelement); * action.contextClick(rightclickelement).sendKeys(Keys.ARROW_DOWN).sendKeys( * Keys.ENTER).build().perform(); * * Actions action = new Actions(driver); * action.contextClick(WebElement).build().perform(); Robot robot = new Robot(); * robot.keyPress(KeyEvent.VK_DOWN); robot.keyRelease(KeyEvent.VK_DOWN); * robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); */ }
true
eca12a9af88fb6e34d00e6715f692b2bdd161d3b
Java
yunwow/lyRespository
/tfkc_shop/src/com/koala/core/annotation/Log.java
UTF-8
983
2.1875
2
[]
no_license
package com.koala.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.koala.foundation.domain.LogType; /** * * <p> * Title: Log.java * </p> * * <p> * Description: 系统日志记录注解,该注解用在需要记录操作日志的action中,使用Spring AOP结合该注解完成操作日志记录 * </p> */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface Log { /** * * @return */ public String title() default ""; /** * * @return */ public String entityName() default ""; /** * * @return */ public LogType type(); /** * 方法描述 * * @return */ public String description() default ""; /** * * @return */ public String ip() default ""; }
true
937821f9074dc3c0d64270e2585ced5e437a3356
Java
fnevesprogram/submarine-navigation
/submarine_navigation/src/main/java/br/com/submarine/proccess/FactoryNavigation.java
UTF-8
2,356
2.640625
3
[]
no_license
package br.com.submarine.proccess; import br.com.submarine.exception.InvalidNavigationException; import br.com.submarine.model.SubmarineNavigation; import br.com.submarine.operation.NavigationEnum; public class FactoryNavigation implements IFactoryNavigation<SubmarineNavigation>{ private IMove<SubmarineNavigation> navigation; public IMove<SubmarineNavigation> processValueNavigationForMoviment(SubmarineNavigation submarineNavigation) throws InvalidNavigationException { try { if ( NavigationEnum.L.toString().equals(submarineNavigation.getNavigationPoint()) ) { return moveToOeste(submarineNavigation); } else if ( NavigationEnum.R.toString().equals(submarineNavigation.getNavigationPoint()) ) { return moveToLeste(submarineNavigation); } else if ( NavigationEnum.D.toString().equals(submarineNavigation.getNavigationPoint()) ) { return moveToSul(submarineNavigation); } else if ( NavigationEnum.U.toString().equals(submarineNavigation.getNavigationPoint()) ) { return moveToNorte(submarineNavigation); } else if ( NavigationEnum.M.toString().equals(submarineNavigation.getNavigationPoint()) ) { return move(submarineNavigation); } } catch (Exception e) { throw new InvalidNavigationException(e); } return navigation; } private IMove<SubmarineNavigation> moveToNorte(SubmarineNavigation submarineNavigation) throws InvalidNavigationException { return new SubmarineMoveToNorte().move(submarineNavigation); } private IMove<SubmarineNavigation> moveToLeste(SubmarineNavigation submarineNavigation) throws InvalidNavigationException { return new SubmarineMoveToLeste().move(submarineNavigation); } private IMove<SubmarineNavigation> moveToSul(SubmarineNavigation submarineNavigation) throws InvalidNavigationException { return new SubmarineMoveToSul().move(submarineNavigation); } private IMove<SubmarineNavigation> moveToOeste(SubmarineNavigation submarineNavigation) throws InvalidNavigationException { return new SubmarineMoveToOeste().move(submarineNavigation); } private IMove<SubmarineNavigation> move(SubmarineNavigation submarineNavigation) throws InvalidNavigationException { return new SubmarineMove().move(submarineNavigation); } }
true
f3a687d6bbf4fd9c1e29c8b115f3e125f69fcf35
Java
Asong27/test-demo
/spring-test/src/main/java/com/idea/spring/test/springtest/service/UserService.java
UTF-8
419
1.710938
2
[]
no_license
package com.idea.spring.test.springtest.service; import com.idea.spring.test.springtest.common.PageInfoTest; import com.idea.spring.test.springtest.pojo.User; public interface UserService { public User selectUserById(Integer id); public void deleteUserById(Integer id); public void updateUser(User user); public void insertUser(User user); public PageInfoTest getPage(Integer pageNo, Integer size); }
true
ed6ae743ab6a9100516f4ccbb4c8972fc9f66fee
Java
dangkhoaph/LAB221-J3LP0003
/src/khoaphd/models/UserDAO.java
UTF-8
2,485
2.734375
3
[]
no_license
package khoaphd.models; import java.io.Serializable; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import khoaphd.dtos.UserDTO; import khoaphd.utils.DBConnection; /** * * @author KhoaPHD */ public class UserDAO implements Serializable { private Connection con; private PreparedStatement stm; private ResultSet rs; private final boolean ACTIVE = true; private void closeConnection() throws SQLException { if (rs != null) rs.close(); if (stm != null) stm.close(); if (con != null) con.close(); } public UserDTO checkLogin(String userID, String password) throws SQLException, ClassNotFoundException { UserDTO dto = null; String sql = "SELECT UserName, Role " + "FROM [User] " + "WHERE UserID = ? AND Password = ? AND Status = ?"; try { con = DBConnection.getConnection(); stm = con.prepareStatement(sql); stm.setString(1, userID); stm.setString(2, password); stm.setBoolean(3, ACTIVE); rs = stm.executeQuery(); if (rs.next()) { String userName = rs.getString("UserName"); String role = rs.getString("Role"); dto = new UserDTO(userID, userName, role); } } finally { closeConnection(); } return dto; } public boolean insertNewUser(UserDTO dto) throws SQLException, ClassNotFoundException { boolean result = false; String sql = "INSERT INTO [User](UserID, Password, UserName, Phone, Address, Role, Status, CreateDate) " + "VALUES(?,?,?,?,?,?,?,?)"; try { con = DBConnection.getConnection(); stm = con.prepareStatement(sql); stm.setString(1, dto.getUserID()); stm.setString(2, dto.getPassword()); stm.setString(3, dto.getUserName()); stm.setString(4, dto.getPhone()); stm.setString(5, dto.getAddress()); stm.setString(6, dto.getRole()); stm.setBoolean(7, ACTIVE); stm.setDate(8, new Date(System.currentTimeMillis())); result = stm.executeUpdate() > 0; } finally { closeConnection(); } return result; } }
true
89209a539df5b091a0365e698262d1c3febaf8b3
Java
ashokp123/MobipugSource
/app/src/main/java/com/o3sa/mobipugapp/uicomponents/BasicComponents.java
UTF-8
23,643
2.21875
2
[]
no_license
package com.o3sa.mobipugapp.uicomponents; import android.app.Activity; import android.graphics.Typeface; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.text.InputType; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.o3sa.mobipugapp.storedobjects.StoredObjects; /** * Created by Kiran on 22-09-2018. */ public class BasicComponents extends AppCompatActivity { Activity activity; LinearLayout.LayoutParams params; FrameLayout.LayoutParams paramss; String bold_fonttype1="Roboto-Bold.ttf",regular_fonttype1="Roboto-Regular.ttf",semibold_fonttype1="Roboto-Medium.ttf"; // String bold_fonttype1="Gibson-SemiBold.otf",regular_fonttype1="Gibson-Regular.ttf",semibold_fonttype1="Gibson-SemiBold.otf"; String bold_fonttype2="OpenSans-Semibold.ttf",regular_fonttype2="OpenSans-Semibold.ttf"; String regular_fonttype3="SFUIText-Regular.ttf"; public BasicComponents(Activity m_activity) { activity=m_activity; } //Customization of text view public void CustomizeTextview(TextView textView, float textsize, int textcolor, String title, String contenttype, int[] marginsarray) { //Assigning text to text view textView.setText(title); //Assigning text size to text view textView.setTextSize(textsize); //Assigning text color to text view textView.setTextColor(activity.getResources().getColor(textcolor)); //Assigning content values to text view //View width @ view gravity @view font type String[] contentvalues=contenttype.split("@"); if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(bold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(regular_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("SemiBold")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(semibold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("2")){ textView.setTypeface(GetFont(bold_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("2")){ textView.setTypeface(GetFont(regular_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("3")){ textView.setTypeface(GetFont(regular_fonttype3,activity)); }else{ textView.setTypeface(GetFont(regular_fonttype1,activity)); } if(contentvalues[0].equalsIgnoreCase("Match")){ params = new LinearLayout.LayoutParams(Constants.matchParent, Constants.wrapContent); }else{ params = new LinearLayout.LayoutParams(Constants.wrapContent, Constants.wrapContent); } if(contentvalues[1].equalsIgnoreCase("Center")){ params.gravity = Constants.center; }else if(contentvalues[1].equalsIgnoreCase("Right")){ params.gravity = Constants.right; }else if(contentvalues[1].equalsIgnoreCase("Top")){ params.gravity = Constants.top; }else if(contentvalues[1].equalsIgnoreCase("Left")){ params.gravity = Constants.left; }else if(contentvalues[1].equalsIgnoreCase("Bottom")){ params.gravity = Constants.bottom; }else{ params.gravity = Constants.left; } //left,top,right,bottom //Assigning margins to textview params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); textView.setLayoutParams(params); } //Customization of text view public void CustomizeTextviewFrameLay(TextView textView, float textsize, int textcolor, String title, String contenttype, int[] marginsarray) { //Assigning text to text view textView.setText(title); //Assigning text size to text view textView.setTextSize(textsize); //Assigning text color to text view textView.setTextColor(activity.getResources().getColor(textcolor)); //Assigning content values to text view //View width @ view gravity @view font type String[] contentvalues=contenttype.split("@"); if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(bold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(regular_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("SemiBold")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(semibold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("2")){ textView.setTypeface(GetFont(bold_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("2")){ textView.setTypeface(GetFont(regular_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("3")){ textView.setTypeface(GetFont(regular_fonttype3,activity)); }else{ textView.setTypeface(GetFont(regular_fonttype1,activity)); } if(contentvalues[0].equalsIgnoreCase("Match")){ paramss = new FrameLayout.LayoutParams(Constants.matchParent, Constants.wrapContent); }else{ paramss = new FrameLayout.LayoutParams(Constants.wrapContent, Constants.wrapContent); } if(contentvalues[1].equalsIgnoreCase("Center")){ paramss.gravity = Constants.center; }else if(contentvalues[1].equalsIgnoreCase("Right")){ paramss.gravity = Constants.right; }else if(contentvalues[1].equalsIgnoreCase("Top")){ paramss.gravity = Constants.top; }else if(contentvalues[1].equalsIgnoreCase("Left")){ paramss.gravity = Constants.left; }else if(contentvalues[1].equalsIgnoreCase("Bottom")){ paramss.gravity = Constants.bottom; }else{ paramss.gravity = Constants.left; } //left,top,right,bottom //Assigning margins to textview paramss.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); textView.setLayoutParams(paramss); } //Customization of text view with background public void CustomizeWithBgTextview(TextView textView, float textsize, int textcolor, String title, int drawable, String contenttype, int[] marginsarray) { //Assigning text to text view textView.setText(title); //Assigning text size to text view textView.setTextSize(textsize); //Assigning text color to text view textView.setTextColor(activity.getResources().getColor(textcolor)); //Assigning background to text view textView.setBackgroundDrawable(activity.getResources().getDrawable(drawable)); //Assigning content values to text view //View width @ view gravity @view font type String[] contentvalues=contenttype.split("@"); if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(bold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(regular_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("SemiBold")&&contentvalues[3].equalsIgnoreCase("1")){ textView.setTypeface(GetFont(semibold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("2")){ textView.setTypeface(GetFont(bold_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("2")){ textView.setTypeface(GetFont(regular_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("3")){ textView.setTypeface(GetFont(regular_fonttype3,activity)); }else{ textView.setTypeface(GetFont(regular_fonttype1,activity)); } if(contentvalues[0].equalsIgnoreCase("Match")){ params = new LinearLayout.LayoutParams(Constants.matchParent, Constants.wrapContent); }else{ params = new LinearLayout.LayoutParams(Constants.wrapContent, Constants.wrapContent); } if(contentvalues[1].equalsIgnoreCase("Center")){ params.gravity = Constants.center; }else if(contentvalues[1].equalsIgnoreCase("Right")){ params.gravity = Constants.right; }else if(contentvalues[1].equalsIgnoreCase("Top")){ params.gravity = Constants.top; }else if(contentvalues[1].equalsIgnoreCase("Left")){ params.gravity = Constants.left; }else if(contentvalues[1].equalsIgnoreCase("Bottom")){ params.gravity = Constants.bottom; }else{ params.gravity = Constants.left; } //left,top,right,bottom //Assigning margins to textview params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); textView.setLayoutParams(params); textView.requestLayout(); } //Customization of Button view public void CustomizeButton(Button button, float buttontextsize, int buttontextcolor, String title, int button_bg, String contenttype,int[] sizesarray, int[] marginsarray) { //Assigning size to button button.setTextSize(buttontextsize); //Assigning text color to button button.setTextColor(activity.getResources().getColor(buttontextcolor)); //Assigning text to button button.setText(title); //Assigning background to button button.setBackgroundDrawable(activity.getResources().getDrawable(button_bg)); //Assigning content values to button //View width @ view gravity @view font type String[] contentvalues=contenttype.split("@"); if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("1")){ button.setTypeface(GetFont(bold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("1")){ button.setTypeface(GetFont(regular_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("SemiBold")&&contentvalues[3].equalsIgnoreCase("1")){ button.setTypeface(GetFont(semibold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("2")){ button.setTypeface(GetFont(bold_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("2")){ button.setTypeface(GetFont(regular_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("3")){ button.setTypeface(GetFont(regular_fonttype3,activity)); }else{ button.setTypeface(GetFont(regular_fonttype1,activity)); } if(contentvalues[0].equalsIgnoreCase("Match")){ params = new LinearLayout.LayoutParams(Constants.matchParent, StoredObjects.pxFromDp(activity,sizesarray[1])); }else{ params = new LinearLayout.LayoutParams(StoredObjects.pxFromDp(activity,sizesarray[0]), StoredObjects.pxFromDp(activity,sizesarray[1])); } if(contentvalues[1].equalsIgnoreCase("Center")){ params.gravity = Constants.center; }else if(contentvalues[1].equalsIgnoreCase("Right")){ params.gravity = Constants.right; }else if(contentvalues[1].equalsIgnoreCase("Top")){ params.gravity = Constants.top; }else if(contentvalues[1].equalsIgnoreCase("Left")){ params.gravity = Constants.left; }else if(contentvalues[1].equalsIgnoreCase("Bottom")){ params.gravity = Constants.bottom; }else{ params.gravity = Constants.left; } //left,top,right,bottom //Assigning margins to button params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); button.setLayoutParams(params); button.requestLayout(); } //Customization of Edittext view public void CustomizeEditview(EditText editText, float editviewtextsize,String title, int background_bg, boolean editstatus, String contenttype, int[] marginsarray) { //Assigning size to edit view editText.setTextSize(editviewtextsize); //Assigning hint to edit view editText.setHint(title); //Assigning background to edit view if(background_bg==0){ }else{ editText.setBackgroundDrawable(activity.getResources().getDrawable(background_bg)); } editText.setEnabled(editstatus); //Assigning content values to edit view //View width @ view gravity @view font type String[] contentvalues=contenttype.split("@"); if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("1")){ editText.setTypeface(GetFont(bold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("1")){ editText.setTypeface(GetFont(regular_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("SemiBold")&&contentvalues[3].equalsIgnoreCase("1")){ editText.setTypeface(GetFont(semibold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("2")){ editText.setTypeface(GetFont(bold_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("2")){ editText.setTypeface(GetFont(regular_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("3")){ editText.setTypeface(GetFont(regular_fonttype3,activity)); }else{ editText.setTypeface(GetFont(regular_fonttype1,activity)); } if(contentvalues[0].equalsIgnoreCase("Match")){ params = new LinearLayout.LayoutParams(Constants.matchParent, Constants.wrapContent); //paramss = new FrameLayout.LayoutParams(Constants.matchParent, Constants.wrapContent); }else{ params = new LinearLayout.LayoutParams(Constants.wrapContent, Constants.wrapContent); //paramss = new FrameLayout.LayoutParams(Constants.wrapContent, Constants.wrapContent); } if(contentvalues[1].equalsIgnoreCase("Center")){ params.gravity = Constants.center; }else if(contentvalues[1].equalsIgnoreCase("Right")){ params.gravity = Constants.right; }else if(contentvalues[1].equalsIgnoreCase("Top")){ params.gravity = Constants.top; }else if(contentvalues[1].equalsIgnoreCase("Left")){ params.gravity = Constants.left; }else if(contentvalues[1].equalsIgnoreCase("Bottom")){ params.gravity = Constants.bottom; }else{ params.gravity = Constants.left; } //left,top,right,bottom //Assigning margins to edit view params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); editText.setLayoutParams(params); editText.requestLayout(); } //Customization of Edittext view public void CustomizeMultilineEditview(EditText editText, float editviewtextsize, String title, int background_bg, boolean editstatus, boolean single_line, String contenttype, int[] marginsarray,int numoflines) { //Assigning size to edit view editText.setTextSize(editviewtextsize); //Assigning hint to edit view editText.setHint(title); //Assigning background to edit view editText.setBackgroundDrawable(activity.getResources().getDrawable(background_bg)); editText.setSingleLine(single_line); if(editstatus==false){ editText.setFocusable(editstatus); editText.setFocusableInTouchMode(editstatus); } editText.setEnabled(editstatus); //Assigning content values to edit view //View width @ view gravity @view font type String[] contentvalues=contenttype.split("@"); if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("1")){ editText.setTypeface(GetFont(bold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("1")){ editText.setTypeface(GetFont(regular_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("SemiBold")&&contentvalues[3].equalsIgnoreCase("1")){ editText.setTypeface(GetFont(semibold_fonttype1,activity)); }else if(contentvalues[2].equalsIgnoreCase("Bold")&&contentvalues[3].equalsIgnoreCase("2")){ editText.setTypeface(GetFont(bold_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("2")){ editText.setTypeface(GetFont(regular_fonttype2,activity)); }else if(contentvalues[2].equalsIgnoreCase("Normal")&&contentvalues[3].equalsIgnoreCase("3")){ editText.setTypeface(GetFont(regular_fonttype3,activity)); }else{ editText.setTypeface(GetFont(regular_fonttype1,activity)); } if(contentvalues[0].equalsIgnoreCase("Match")){ params = new LinearLayout.LayoutParams(Constants.matchParent, Constants.wrapContent); }else{ params = new LinearLayout.LayoutParams(Constants.wrapContent, Constants.wrapContent); } editText.setLines(numoflines); //left,top,right,bottom //Assigning margins to edit view params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); editText.setLayoutParams(params); editText.requestLayout(); } //Customization of Image view public void CustomizeImageview(ImageView imageView, int[] sizesarray, int background_bg, int[] marginsarray) { //Assigning size to image view //Assigning background to image view imageView.setImageResource(background_bg); //left,top,right,bottom //Assigning margins to imageview if(sizesarray[0]==Constants.matchParent||sizesarray[0]==Constants.wrapContent){ params= new LinearLayout.LayoutParams(sizesarray[0], StoredObjects.pxFromDp(activity,sizesarray[1])); }else{ params= new LinearLayout.LayoutParams(StoredObjects.pxFromDp(activity,sizesarray[0]), StoredObjects.pxFromDp(activity,sizesarray[1])); } params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); imageView.setLayoutParams(params); } //Customization of Image view public void CustomizeImageviewBackground(ImageView imageView, int[] sizesarray, int background_bg, int[] marginsarray) { //Assigning size to image view //Assigning margins to imageview if(sizesarray[0]==Constants.matchParent||sizesarray[0]==Constants.wrapContent){ params= new LinearLayout.LayoutParams(sizesarray[0], StoredObjects.pxFromDp(activity,sizesarray[1])); }else{ params= new LinearLayout.LayoutParams(StoredObjects.pxFromDp(activity,sizesarray[0]), StoredObjects.pxFromDp(activity,sizesarray[1])); } //Assigning background to image view imageView.setBackgroundDrawable(activity.getResources().getDrawable(background_bg)); //left,top,right,bottom //Assigning margins to imageview params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); imageView.setLayoutParams(params); } //Customization of Image view public void CustomizeBottomImageview(ImageView imageView, int[] sizesarray, int[] marginsarray) { //Assigning size to image view //Assigning background to image view //imageView.setImageResource(background_bg); //left,top,right,bottom //Assigning margins to imageview if(sizesarray[0]==Constants.matchParent||sizesarray[0]==Constants.wrapContent){ params= new LinearLayout.LayoutParams(sizesarray[0], StoredObjects.pxFromDp(activity,sizesarray[1])); }else{ params= new LinearLayout.LayoutParams(StoredObjects.pxFromDp(activity,sizesarray[0]), StoredObjects.pxFromDp(activity,sizesarray[1])); } params.setMargins(StoredObjects.pxFromDp(activity,marginsarray[0]),StoredObjects.pxFromDp(activity,marginsarray[1]),StoredObjects.pxFromDp(activity,marginsarray[2]),StoredObjects.pxFromDp(activity,marginsarray[3])); imageView.setLayoutParams(params); } //Get Font public Typeface GetFont(String font_type,Activity activity){ Typeface fonttype= Typeface.createFromAsset(activity.getAssets(), font_type); return fonttype; } //Apply Tint public void ApplyTint(ImageView imageView,int tintcolor){ imageView.setColorFilter(ContextCompat.getColor(activity, tintcolor), android.graphics.PorterDuff.Mode.SRC_IN); } //Apply Tint public void SetPasswordHint(EditText editText){ editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } public void SetHeight(RecyclerView recyclerView,int numberofitems,int itemHeight){ ViewGroup.LayoutParams params = recyclerView.getLayoutParams(); params.height = itemHeight * numberofitems; recyclerView.requestLayout(); } }
true
f20f7d53b00e5768dc5fc01bd620957c1985c780
Java
prietojulen/Programacion
/Capitulo 4/REPASO_CAP4/Tema4_ej8/src/tema4_ej8/Tema4_ej8.java
UTF-8
2,606
3.46875
3
[]
no_license
package tema4_ej8; import javax.swing.JOptionPane; public class Tema4_ej8 { private static int fila = 0; private static int columna = 0; private static int numero = 0; public static void main(String[] args) { // TODO code application logic here int [][] tabla = new int [5][5]; pedirFila(); pedirColumna(); rellenarArray(tabla); mostrarResultado(tabla); char resp; pedirFila(); pedirColumna(); rellenarArray(tabla); /* String respuesta = JOptionPane.showInputDialog("¿Desea continuar? S/N"); respuesta = respuesta.toLowerCase(); resp = respuesta.charAt(0); boolean comprobar = false; */ } public static void pedirFila(){ try{ do{ fila = Integer.parseInt(JOptionPane.showInputDialog("Introduce una fila del 1 al 5")); fila = fila -1; } while(fila < 0 || fila > 4); } catch(Exception e){ JOptionPane.showMessageDialog(null, "No has introducido un valor lógico para la fina " + e.getMessage()); } } public static void pedirColumna(){ try{ do{ columna = Integer.parseInt(JOptionPane.showInputDialog("Introduce una columna del 1 al 5")); columna = columna -1; } while(columna < 0 || columna > 4); } catch(Exception e){ JOptionPane.showMessageDialog(null, "No has introducido un valor lógico para la columna " + e.getMessage()); } } public static void rellenarArray(int [][] tabla){ try{ numero = Integer.parseInt(JOptionPane.showInputDialog("Introduce un numero")); } catch(Exception e){ JOptionPane.showMessageDialog(null, "No has introducido un valor lógico para rellenar el array " + e.getMessage()); } tabla[fila][columna] = numero; } public static void mostrarResultado(int [][] tabla){ String salida=""; for(int x=0; x < 5; x++){ int total = 0; for(int y=0; y < 5; y++){ total += tabla[x][y]; } salida+= ("FILA "+ (x+1) + " " + total ); } JOptionPane.showMessageDialog(null, salida); } }
true
74dba85cd412a99247829cb23a2d2faceb226cf7
Java
trrying/Translation
/app/src/main/java/com/owm/translation/presenter/TranslationPresenter.java
UTF-8
4,775
2.15625
2
[]
no_license
package com.owm.translation.presenter; import com.owm.biubiuboom.net.retrofit.ApiClient; import com.owm.biubiuboom.net.retrofit.ApiHelper; import com.owm.biubiuboom.net.retrofit.ICallBack; import com.owm.biubiuboom.presenter.BasePresenter; import com.owm.translation.model.BaiduTranslationBean; import com.owm.translation.model.MovieResult; import com.owm.translation.model.YoudaoTranslationBean; import com.owm.translation.net.retrofit.BaiduTranslationApi; import com.owm.translation.net.retrofit.DoubanMovieTop; import com.owm.translation.net.retrofit.YoudaoTranslationApi; import com.owm.translation.utils.GlobalProperty; import com.owm.translation.view.translation.ITranslationView; import java.util.HashMap; import java.util.Map; /** * 主界面控制器 * Created by ouweiming on 2016/10/31. */ public class TranslationPresenter extends BasePresenter<ITranslationView>{ private BaiduTranslationApi mBaiduTranslationApi; private YoudaoTranslationApi mYoudaoTranslationApi; private DoubanMovieTop mDoubanMovieTop; public TranslationPresenter(ITranslationView view) { super(view); mBaiduTranslationApi = ApiClient.getBaiduFanYiRetrofit().create(BaiduTranslationApi.class); mYoudaoTranslationApi = ApiClient.getYouDaoFanYiRetrofit().create(YoudaoTranslationApi.class); // mDoubanMovieTop = ApiClient.getBaiduFanYiRetrofit().create(DoubanMovieTop.class); } public void translation(String query) { translation(query, GlobalProperty.TRANSLATION_TYPE_BAIDU); } public void translation(String query, int type) { mView.showLoading(); switch (type) { case GlobalProperty.TRANSLATION_TYPE_YOUDAO: translation4Youdao(query); break; case GlobalProperty.TRANSLATION_TYPE_BAIDU: default: translation4Baidu(query); break; } } private void translation4Baidu(String query) { String salt = System.currentTimeMillis()+""; addSubscription(mBaiduTranslationApi.translation4Baidu(query, "auto", "auto", ApiHelper.APP_ID, salt , ApiHelper.getSign(query, salt)), translation); } private void translation4Youdao(String query) { Map<String, String> params = new HashMap<>(); params.put("keyfrom","AnyHelpers"); params.put("key","1757159193"); params.put("type","data"); params.put("doctype","json"); params.put("version","1.1"); addSubscription(mYoudaoTranslationApi.translation4Youdao(query, params), youdaoResult); } public void getTopMovie() { mView.showLoading(); addSubscription(mDoubanMovieTop.getTopMovie(1, 10), mMovieResultApiCallBack); } private ICallBack<BaiduTranslationBean> translation = new ICallBack<BaiduTranslationBean>() { @Override public void onSuccess(BaiduTranslationBean model) { if (model == null) { mView.showMessageDialog("访问出错"); return; } if (model.getError_code() != null && !BaiduTranslationBean.SUCCESS_CODE.equals(model.getError_code())) { mView.showMessageDialog(BaiduTranslationBean.getErrorCodes().get(model.getError_code())); return; } mView.showResult(model); } @Override public void onFailure(String msg) { mView.showMessageDialog(msg); } @Override public void onFinish() { mView.hideLoading(); } }; private ICallBack<YoudaoTranslationBean> youdaoResult = new ICallBack<YoudaoTranslationBean>() { @Override public void onSuccess(YoudaoTranslationBean model) { if (model == null) { mView.showMessageDialog("访问出错"); return; } if (model.getErrorCode() != null && !YoudaoTranslationBean.SUCCESS_CODE.equals(model.getErrorCode())) { mView.showMessageDialog(YoudaoTranslationBean.getErrorCodes().get(model.getErrorCode())); return; } mView.showResult(model); } @Override public void onFailure(String msg) { mView.showMessageDialog(msg); } @Override public void onFinish() { mView.hideLoading(); } }; private ICallBack<MovieResult> mMovieResultApiCallBack = new ICallBack<MovieResult>() { @Override public void onSuccess(MovieResult model) { } @Override public void onFailure(String msg) { } @Override public void onFinish() { mView.hideLoading(); } }; }
true
3a5182215369b294ee1f2c02bb1e1444411aab32
Java
Patriotic-Robotics-6372/SkyStone
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Subsystemv2/tests/DrivetrainTest.java
UTF-8
1,369
2.46875
2
[ "BSD-3-Clause" ]
permissive
package org.firstinspires.ftc.teamcode.Subsystemv2.tests; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.teamcode.Subsystemv2.subsys.drivetrain.Drivetrain; import org.firstinspires.ftc.teamcode.Subsystemv2.subsys.telemetry.Telem; /** * Date: 2/14/20 * Author: Jacob Marinas * Test program to check drivetrain functionality and data */ @Disabled @TeleOp (name = "DrivetrainTest", group = "Test") public class DrivetrainTest extends LinearOpMode { @Override public void runOpMode() throws InterruptedException { Drivetrain drive = new Drivetrain(hardwareMap.dcMotor.get("frontLeft"), hardwareMap.dcMotor.get("frontRight"), hardwareMap.dcMotor.get("backLeft"), hardwareMap.dcMotor.get("backRight")); Telem telem = new Telem(drive, telemetry); drive.setMaxPower(1); waitForStart(); while (opModeIsActive()) { if (Math.abs(gamepad1.left_stick_y) > .1 || Math.abs(gamepad1.right_stick_y) > .1) { drive.setLeftSide(gamepad1.left_stick_y); drive.setRightSide(gamepad1.right_stick_y); } else { drive.stop(); } telem.addDrivetrain(); telem.update(); } } }
true
7ffd1a774c4f3cca6541be3a0022819ca2cd6912
Java
liuchenwei2000/Hibernate
/Basic/src/main/java/hibernate/orm/model/PersonVO4.java
UTF-8
947
2.796875
3
[]
no_license
/** * */ package hibernate.orm.model; import java.util.Date; /** * 为了设计需要,将PersonVO的信息进行细分,把name相关的信息单独抽取出来。 * * @author 刘晨伟 * * 创建日期:2014年7月24日 */ public class PersonVO4 { private Long id; private NameVO name; private Date timestamp; private int sex; public PersonVO4() { super(); } public PersonVO4(String firstName, String lastName, int sex) { this.name = new NameVO(firstName, lastName); this.sex = sex; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public NameVO getName() { return name; } public void setName(NameVO name) { this.name = name; } }
true
b1782e3f96ffbf5517d277dd62f422ad9885b005
Java
Azael051101/Desing-Your-Anatomy
/Ventana.java
UTF-8
6,042
2.640625
3
[]
no_license
import javax.swing.*; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.Color; import java.awt.*; import java.awt.event.*; import javax.swing.JComboBox; import javax.swing.ImageIcon; import java.io.File; import java.util.*; import java.io.*; import javax.imageio.*; public class Ventana extends JFrame implements ActionListener{ JPanel panel; //JButton btncontinuar; JButton verDetalles; JMenuBar menuBar; JMenu menu; JMenuItem itemPaciente; JComboBox ciudades; JComboBox partesCuerpo; JComboBox genero; JTextField nombre; JTextField edad; JTextField correo; JLabel etnombre; JLabel etedad; JLabel etcorreo; JLabel etgenero; JLabel etciudad; JLabel etParte; JButton continuar; JTextArea detalles; ArrayList <String> contenido_1; public Ventana(){ String fondo = "fondo.png"; panel = new JPanelConFondo(fondo); panel.setLayout(null); panel.setBackground(Color.WHITE); /*btncontinuar = new JButton("Continuar"); btncontinuar.setBounds(750,500,150,60); ImageIcon imagencontinuar = new ImageIcon("btncontinuar.png"); btncontinuar.setIcon(new ImageIcon(imagencontinuar.getImage().getScaledInstance(btncontinuar.getWidth(), btncontinuar.getHeight(), Image.SCALE_SMOOTH))); btncontinuar.setBackground(Color.WHITE);*/ verDetalles = new JButton("Conocenos"); verDetalles.setBounds(900,550,200,30); // wellcome = new JLabel("Bienvenido a Disigner of Anatomy"); // wellcome.setBounds(250,50,800,50); // wellcome.setFont(new Font("cooper Black",0,40)); menuBar = new JMenuBar(); menu = new JMenu("Administrar"); itemPaciente = new JMenuItem("Paciente"); String [] partesDelCuerpo = {"Seleccionar...","Mano","Brazo","Dedos"}; partesCuerpo = new JComboBox(partesDelCuerpo); partesCuerpo.setBounds(450,300,100,30); etParte = new JLabel("Parte del Cuerpo Faltante: "); etParte.setBounds(400,270,300,30); etParte.setFont(new Font("cooper Black",0,20)); String url = "logobueno.png"; JLabel logo = new JLabel(new ImageIcon(url)); logo.setBounds(40,10,180,180); etnombre = new JLabel("Nombre: "); etnombre.setBounds(40,290,100,30); etnombre.setFont(new Font("Times New Roman",0,24)); etedad = new JLabel("Edad: "); etedad.setBounds(40,335,100,30); etedad.setFont(new Font("Times New Roman",0,24)); nombre = new JTextField(); nombre.setBounds(130,290,150,30); edad = new JTextField(); edad.setBounds(130,335,150,30); etgenero = new JLabel("Genero: "); etgenero.setBounds(40,375,100,30); etgenero.setFont(new Font("Times New Roman",0,24)); String [] generos = {"Seleccionar...","Masculino","Femenino"}; genero = new JComboBox(generos); genero.setBounds(130,375,100,30); etciudad = new JLabel("Cuidad: "); etciudad.setBounds(40,420,100,30); etciudad.setFont(new Font("Times New Roman",0,24)); String [] listaDeCiudades = {"Seleccionar...","Tijuana","Monterrey","Guadalajara"}; ciudades = new JComboBox(listaDeCiudades); ciudades.setBounds(130,420,100,30); etcorreo = new JLabel("Correo: "); etcorreo.setBounds(40,465,100,30); etcorreo.setFont(new Font("Times New Roman",0,24)); correo = new JTextField(); correo.setBounds(130,465,150,30); /*String prueba = correo.getText(); Archivo ar = new Archivo(); ar.guardarTodo(prueba,"Archivo de Prueba");*/ continuar = new JButton("Continuar"); continuar.setBounds(130,510,90,40); //panel.add(btncontinuar); panel.add(verDetalles); //panel.add(wellcome); panel.add(ciudades); panel.add(logo); panel.add(partesCuerpo); panel.add(nombre); panel.add(edad); panel.add(genero); panel.add(etnombre); panel.add(etedad); panel.add(etgenero); panel.add(etciudad); panel.add(etcorreo); panel.add(correo); panel.add(continuar); panel.add(etParte); menuBar.add(menu); menu.add(itemPaciente); this.setJMenuBar(menuBar); this.add(panel); this.setTitle("Desing Your Anatomy"); this.setSize(1200,680); this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); this.setVisible(true); this.setLocationRelativeTo(null); //Añadir los accionPerformed //btncontinuar.addActionListener(this); verDetalles.addActionListener(this); itemPaciente.addActionListener(this); ciudades.addActionListener(this); partesCuerpo.addActionListener(this); genero.addActionListener(this); continuar.addActionListener(this); } public void actionPerformed(ActionEvent event){ /*if(event.getSource() == this.btncontinuar){ System.out.println("btncontinuar pulsado"); }else*/ if(event.getSource()== this.verDetalles){ Detalles det = new Detalles(); }else if(event.getSource()== this.itemPaciente){ //System.out.println("itemPaciente precionado"); VentanaPrueba vp = new VentanaPrueba(); System.out.println("HOLA"); }else if(event.getSource()== this.ciudades){ }else if(event.getSource()== this.continuar){ String datosUsuario = "Nombre: "+nombre.getText()+"\n"+ "Edad: "+edad.getText()+"\n" +"Genero: " +genero.getSelectedItem()+"\n"+"Ciudad: "+ciudades.getSelectedItem()+"\n"+ "Correo: "+correo.getText(); String crear = "C:/Users/Hiram/Documents/java/Proyecto Poo 2do Sem//"+nombre.getText(); File c = new File(crear); c.mkdirs(); Archivo.guardarTodo(datosUsuario,"Datos.txt"); if(genero.getSelectedItem().equals("Masculino")){ // System.out.println("Macho"); } if(genero.getSelectedItem().equals("Femenino")){ // System.out.println("Vieja"); } if(partesCuerpo.getSelectedItem().equals("Mano")){ Mano mano = new Mano(); // System.out.println("Mano"); }else if (partesCuerpo.getSelectedItem().equals("Brazo")){ Brazo brazo = new Brazo(); }else if(partesCuerpo.getSelectedItem().equals("Dedos")){ Dedos dedos = new Dedos(); } } } }
true
417fec4290cb6dcad72d1cdd920c316c68d246ba
Java
Aurele3000/skoon_2_back
/src/main/java/fr/aurele/skoon_2/repository/AdresseRepo.java
UTF-8
494
1.859375
2
[]
no_license
package fr.aurele.skoon_2.repository; import fr.aurele.skoon_2.model.Adresse; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface AdresseRepo extends JpaRepository<Adresse, Integer> { public List<Adresse> findByVilleContaining(String ville); public List<Adresse> findByRueContaining(String rue); public List<Adresse> findByCodePostalContaining(String code_postal); }
true
0a443d29c4d539b9138fe1e8e5133fcbc55f2301
Java
8kosmo/kosmo52
/workspace_java/dev_java/src/com/address/JListTest.java
UTF-8
377
2.28125
2
[]
no_license
package com.address; import javax.swing.JFrame; import javax.swing.JList; public class JListTest extends JFrame { public static void main(String[] args) { JListTest jlt = new JListTest(); String[] data = {"DVD명", "감독", "배우"}; JList<String> myList = new JList<String>(data); jlt.add("Center",myList); jlt.setSize(400, 300); jlt.setVisible(true); } }
true
18776444d269dc47e94562af90e828f82a5d84e6
Java
fredou123/GedProj
/GEDProject/src/main/java/com/ged/controller/TypeMetadonneeController.java
UTF-8
2,441
2.125
2
[]
no_license
package com.ged.controller; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ged.dto.TypeMetadonneeDTO; import com.ged.dto.TypeMetadonneePostDTO; import com.ged.dto.service.TypeMetadonneeDtoService; @RestController public class TypeMetadonneeController { @Autowired private TypeMetadonneeDtoService metier; @RequestMapping( value = "/typeMetadonnees", method = RequestMethod.POST ) public TypeMetadonneePostDTO saveTypeMetadonnee( @RequestBody TypeMetadonneePostDTO tm ) { return metier.saveTypeMetadonnee( tm ); } @RequestMapping( value = "/typeMetadonnees/{id}", method = RequestMethod.GET ) public TypeMetadonneeDTO getTypeMetadonnee( @PathVariable Long id ) { return metier.getTypeMetadonnee( id ); } @RequestMapping( value = "/typeMetadonnees", method = RequestMethod.DELETE ) public TypeMetadonneeDTO deleteTypeMetadonnee( @RequestBody TypeMetadonneeDTO typeMetadonnee ) { return metier.deleteTypeMetadonnee(typeMetadonnee); } @RequestMapping( value = "/typeMetadonnees", method = RequestMethod.GET ) public List<TypeMetadonneeDTO> getAllTypeMetadonnee( ) { return metier.getAllTypeMetadonnees(); } @RequestMapping( value = "/typeMetadonnees", method = RequestMethod.PUT ) public void SetTypeMetadonneeById (@RequestParam String nom, @RequestParam String type,@RequestParam Long id){ metier.SetTypeMetadonneeById(nom, type, id); } @RequestMapping( value = "/typeMetadonnees/all", method = RequestMethod.DELETE ) public void deleteSelectedTypeMetadonnee(@RequestBody Collection<TypeMetadonneeDTO> c) { metier.deleteSelectedTypeMetadonnee(c); } @RequestMapping( value = "/typeMetadonnees/ids", method = RequestMethod.GET ) public Collection<TypeMetadonneeDTO> getListTypeMetadonneeById(@RequestBody Collection<Long> ids){ return metier.getListTypeMetadonneeById(ids); } }
true
a6015f09f6811899c76ad42e5e5e3552b8161226
Java
IlyaPeshko/TestTaskTransavia
/src/main/java/by/htp/task/ui/webDriver/DriverTypes.java
UTF-8
333
2.40625
2
[]
no_license
package by.htp.task.ui.webDriver; public enum DriverTypes { FIREFOX ("firefox"), IE ("internet explorer"), GC ("google chrome"); private String driverName; private DriverTypes(String driverName){ this.driverName = driverName; } public String getDriverName() { return this.driverName; } }
true
851a2d1bbabb4868d1ff94f8e930533f06667693
Java
jjodell123/CircleTag
/src/Map.java
UTF-8
1,763
3.203125
3
[]
no_license
import java.awt.Graphics2D; import java.util.ArrayList; public class Map { private ArrayList<Wall> w=new ArrayList<Wall>(); public Map() { //borders w.add(new Wall(9,38,25,450)); w.add(new Wall(9,541 ,25,450)); w.add(new Wall(34,38,425,25)); w.add(new Wall(541,38,450,25)); w.add(new Wall(966,38,25,450)); w.add(new Wall(966,541 ,25,450)); w.add(new Wall(34,966,425,25)); w.add(new Wall(541,966,450,25)); //layers count outside to inside //first layer w.add(new Wall(109,192,25,650)); w.add(new Wall(200,138,600,25)); w.add(new Wall(866,192,25,650)); w.add(new Wall(200,866,600,25)); //second layer (innerward sticking walls) w.add(new Wall(200,163,25,100)); w.add(new Wall(775,163,25,100)); w.add(new Wall(200,766,25,100)); w.add(new Wall(775,766,25,100)); //third layer(polygon) w.add(new Wall(300,238,400,25)); w.add(new Wall(200,339,200,25)); w.add(new Wall(600,339,200,25)); w.add(new Wall(200,364,25,300)); w.add(new Wall(775,364,25,300)); w.add(new Wall(300,766,400,25)); w.add(new Wall(200,664,200,25)); w.add(new Wall(600,664,200,25)); //fourth layer (equals shape) w.add(new Wall(300,438,400,25)); w.add(new Wall(300,566,400,25)); //fourth layer (connects third and fourth) w.add(new Wall(500,263,25,175)); w.add(new Wall(500,591,25,175)); } public void moveY(int y) { for(int i=0;i<w.size();i++) w.get(i).moveY(y); } public void moveX(int x) { for(int i=0;i<w.size();i++) w.get(i).moveX(x); } public ArrayList<Wall> getWalls() { return w; } public void draw(Graphics2D g) { for(int i=0;i<w.size();i++) w.get(i).draw(g); } }
true
a5d76f2deae847bc9dc450d2d9f441d9f1afd11f
Java
DimaPhil/ITMO
/Java & JavaScript/2 course/Hometasks/10/src/ru/ifmo/ctddev/filippov/bank/PersonType.java
UTF-8
84
1.75
2
[]
no_license
package ru.ifmo.ctddev.filippov.bank; public enum PersonType { LOCAL, REMOTE }
true
f0872825aa33f9584327c0e950f956c659a1033b
Java
Paladin1412/house
/java/classes3/com/ziroom/ziroomcustomer/sharedlife/c/c.java
UTF-8
2,028
1.90625
2
[ "Apache-2.0" ]
permissive
package com.ziroom.ziroomcustomer.sharedlife.c; import java.util.List; public class c { private List<a> a; public List<a> getTbDeviceList() { return this.a; } public void setTbDeviceList(List<a> paramList) { this.a = paramList; } public static class a { private String a; private String b; private String c; private String d; private String e; private int f; private String g; private String h; public String getDeviceNumber() { return this.b; } public String getDeviceType() { return this.c; } public String getDeviceTypeName() { return this.d; } public String getDeviceUsingStatus() { return this.e; } public int getDeviceUsingStatusCode() { return this.f; } public String getDeviceUuid() { return this.a; } public String getIsNotLock() { return this.h; } public String getPicUrl() { return this.g; } public void setDeviceNumber(String paramString) { this.b = paramString; } public void setDeviceType(String paramString) { this.c = paramString; } public void setDeviceTypeName(String paramString) { this.d = paramString; } public void setDeviceUsingStatus(String paramString) { this.e = paramString; } public void setDeviceUsingStatusCode(int paramInt) { this.f = paramInt; } public void setDeviceUuid(String paramString) { this.a = paramString; } public void setIsNotLock(String paramString) { this.h = paramString; } public void setPicUrl(String paramString) { this.g = paramString; } } } /* Location: /Users/gaoht/Downloads/zirom/classes3-dex2jar.jar!/com/ziroom/ziroomcustomer/sharedlife/c/c.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
f35f603d3501d8f84c8b6b967099d06d8ffe989b
Java
pechll/prueba_java
/src/java/Models/clsClasificador.java
UTF-8
3,643
2
2
[]
no_license
package Models; /** * * @author Ing. Percy Edward Chávez LLamoga <pechll@hotmail.com> */ import java.util.Calendar; import java.util.GregorianCalendar; public class clsClasificador { public int getAnos() { return anos; } public void setAnos(int anos) { this.anos = anos; } public int getIdClasificador() { return IdClasificador; } public void setIdClasificador(int IdClasificador) { this.IdClasificador = IdClasificador; } public int getIdTributo() { return IdTributo; } public void setIdTributo(int IdTributo) { this.IdTributo = IdTributo; } public String getConcepto() { return Concepto; } public void setConcepto(String Concepto) { this.Concepto = Concepto; } public String getConceCorto() { return ConceCorto; } public void setConceCorto(String ConceCorto) { this.ConceCorto = ConceCorto; } public String getIdPresupuestal() { return IdPresupuestal; } public void setIdPresupuestal(String IdPresupuestal) { this.IdPresupuestal = IdPresupuestal; } public String getIdFinanciero() { return IdFinanciero; } public void setIdFinanciero(String IdFinanciero) { this.IdFinanciero = IdFinanciero; } public double getImporte() { return importe; } public void setImporte(double importe) { this.importe = importe; } public double getTasa() { return Tasa; } public void setTasa(double Tasa) { this.Tasa = Tasa; } public String getCodEp() { return CodEp; } public void setCodEp(String CodEp) { this.CodEp = CodEp; } public String getLogin() { return Login; } public void setLogin(String Login) { this.Login = Login; } public Calendar getFecha() { return Fecha; } public void setFecha(Calendar Fecha) { this.Fecha = Fecha; } public char getEstado() { return Estado; } public void setEstado(char Estado) { this.Estado = Estado; } public clsTipoClasi getOb_clsTipo() { return obclsTipo; } public void setOb_clsTipo(clsTipoClasi ob_clsTipo) { this.obclsTipo = ob_clsTipo; } public clsSubTipoClasi getOb_clsSubTipoClasi() { return obclsSubTipoClasi; } public void setOb_clsSubTipoClasi(clsSubTipoClasi ob_clsSubTipoClasi) { this.obclsSubTipoClasi = ob_clsSubTipoClasi; } public int getInCodigo() { return inCodigo; } public void setInCodigo(int inCodigo) { this.inCodigo = inCodigo; } public clsTipoClasi getObclsTipo() { return obclsTipo; } public void setObclsTipo(clsTipoClasi obclsTipo) { this.obclsTipo = obclsTipo; } public clsSubTipoClasi getObclsSubTipoClasi() { return obclsSubTipoClasi; } public void setObclsSubTipoClasi(clsSubTipoClasi obclsSubTipoClasi) { this.obclsSubTipoClasi = obclsSubTipoClasi; } //Atributos o Propiedades public int inCodigo; public int anos; public int IdClasificador; public int IdTributo; public String Concepto; public String ConceCorto; public String IdPresupuestal; public String IdFinanciero; public double importe; public double Tasa; public String CodEp; public String Login; public Calendar Fecha = new GregorianCalendar(); public char Estado; public clsTipoClasi obclsTipo; public clsSubTipoClasi obclsSubTipoClasi; }
true
29c637c1edc92ec735939bd4060ba5e30a88f2a0
Java
erikknaake/ICSSImplementatie
/startcode/src/test/java/nl/han/ica/icss/transformer/TransformOptimiseIdAsDirectChildTest.java
UTF-8
764
2.125
2
[]
no_license
package nl.han.ica.icss.transformer; import nl.han.ica.icss.ast.AST; import nl.han.ica.icss.transforms.OptimiseIdAsDirectChild; import nl.han.ica.icss.transforms.Transform; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class TransformOptimiseIdAsDirectChildTest { private Transform transform; @BeforeEach public void beforeEach() { transform = new OptimiseIdAsDirectChild(); } @Test public void nothingToRemove() { AST sut = OptimisedIdAsDirectChildFixtures.directIdChild(); AST exp = OptimisedIdAsDirectChildFixtures.directIdChildExpected(); transform.apply(sut); assertEquals(exp, sut); } }
true
01b41925c43502184fb2c69cd3ebc026f54f7fb4
Java
franciscoww/mintic_UTP
/NetBeansProjects(UT)/Uni3/Layouts/src/layouts/VentanaEmpleado.java
UTF-8
730
2.78125
3
[]
no_license
package layouts; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public final class VentanaEmpleado extends JFrame{ private JPanel panel; VentanaEmpleado(){ setSize(700, 200); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); creaPanel(); getContentPane().add(panel); } void creaPanel(){ panel = new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.RIGHT,30,30)); panel.add(new JLabel("Cédula: ")); panel.add(new JTextField(15)); panel.add(new JButton("Click aquí")); } }
true
40cad2aa90a8875ddf6f5144dbda6d1cb56a654f
Java
kevin70/houge
/houge-server-rest/src/main/java/cool/houge/rest/main/RestMain.java
UTF-8
3,295
1.960938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019-2021 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cool.houge.rest.main; import com.google.inject.Guice; import com.google.inject.TypeLiteral; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import cool.houge.ConfigKeys; import cool.houge.rest.controller.Interceptors; import cool.houge.rest.controller.RoutingService; import cool.houge.rest.module.RestModule; import cool.houge.rest.server.RestServer; import cool.houge.service.module.GrpcServiceModule; import cool.houge.service.module.ServiceModule; import cool.houge.storage.module.StorageModule; import cool.houge.system.identifier.ApplicationIdentifier; import cool.houge.util.AppShutdownHelper; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * 主程序. * * @author KK (kzou227@qq.com) */ public class RestMain implements Runnable { private static final Logger log = LogManager.getLogger(); private static final String CONFIG_FILE = "houge-rest.conf"; private final AppShutdownHelper shutdownHelper = new AppShutdownHelper(); /** * 程序入口. * * @param args 启动参数 */ public static void main(String[] args) { new RestMain().run(); } @Override public void run() { // 初始化配置 final var config = loadConfig(); // 初始化 Guice final var injector = Guice.createInjector( new StorageModule(config), new ServiceModule(config), new GrpcServiceModule(config), new RestModule(config)); // 启动 IM 服务 var applicationIdentifier = injector.getInstance(ApplicationIdentifier.class); var restServer = new RestServer( config.getString(ConfigKeys.REST_SERVER_ADDR), injector.getInstance(Interceptors.class), injector.findBindingsByType(TypeLiteral.get(RoutingService.class)).stream() .map(b -> b.getProvider().get()) .collect(Collectors.toList())); restServer.start(); log.info( "{} 服务启动成功 fid={}", applicationIdentifier.applicationName(), applicationIdentifier.fid()); shutdownHelper .addCallback(restServer::stop) // 清理应用标识数据信息 .addCallback(applicationIdentifier::clean) .run(); log.info("REST 服务停止完成"); } private Config loadConfig() { var config = ConfigFactory.parseResources(CONFIG_FILE).resolve(); log.info( "已加载的应用配置 \n=========================================================>>>\n{}<<<=========================================================", config.root().render()); return config; } }
true
92927689ea9f15838694719f8a2412273a8194de
Java
MortalMachine/Tweeter
/shared/src/main/java/response/FollowPersonResponse.java
UTF-8
480
2.3125
2
[]
no_license
package response; import model.domain.AuthToken; public class FollowPersonResponse extends Response { private AuthToken authToken; public FollowPersonResponse(boolean success, AuthToken authToken, String message) { super(success, message); this.authToken = authToken; } public FollowPersonResponse(boolean success, String message) { super(success, message); } public AuthToken getAuthToken() { return authToken; } }
true
70ddb99e3bac176948e203784423f35783e6cb51
Java
massimo-nocentini/my-undergraduatethesis-java
/src/piping/PrinterPipeFilter.java
UTF-8
737
2.21875
2
[]
no_license
package piping; import model.OurModel; import dotInterface.DotExporter; import dotInterface.DotFileUtilHandler; import dotInterface.SimpleExporter; public class PrinterPipeFilter extends PipeFilter { @Override public boolean isYourTagEquals(AvailableFilters other) { return AvailableFilters.Printer.equals(other); } @Override protected OurModel doYourComputationOn(String pipelineName, OurModel inputModel, PipeFilterComputationListener computationListener) { DotExporter exporter = new SimpleExporter(); inputModel.acceptExporter(exporter); DotFileUtilHandler.makeHandler(formatPhaseIdentifier(pipelineName)) .writeDotRepresentationInTestFolder(exporter) .produceSvgOutput(); return inputModel; } }
true
23687e9d1a355ce4e495a94ab88aa51e0ac10727
Java
f297302354/GP
/gp/src/main/java/com/cf/gp/model/StockPriceHistoryResultCondition.java
UTF-8
485
2.171875
2
[]
no_license
package com.cf.gp.model; public class StockPriceHistoryResultCondition { private int count; private double val; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getVal() { return val; } public void setVal(double val) { this.val = val; } @Override public String toString() { return "StockPriceHistoryResultCondition [count=" + count + ", val=" + val + "]"; } }
true
53cb62c529af71c32923d1e4fd5068c34f4961ab
Java
alim-firejack/Firejack-Platform
/platform/src/main/java/net/firejack/platform/service/process/broker/TaskCaseProcessor.java
UTF-8
7,342
1.742188
2
[ "Apache-2.0" ]
permissive
/* * Firejack Open Flame - Copyright (c) 2012 Firejack Technologies * * This source code is the product of the Firejack Technologies * Core Technologies Team (Benjamin A. Miller, Oleg Marshalenko, and Timur * Asanov) and licensed only under valid, executed license agreements * between Firejack Technologies and its customers. Modification and / or * re-distribution of this source code is allowed only within the terms * of an executed license agreement. * * Any modification of this code voids any and all warranties and indemnifications * for the component in question and may interfere with upgrade path. Firejack Technologies * encourages you to extend the core framework and / or request modifications. You may * also submit and assign contributions to Firejack Technologies for consideration * as improvements or inclusions to the platform to restore modification * warranties and indemnifications upon official re-distributed in patch or release form. */ package net.firejack.platform.service.process.broker; import net.firejack.platform.api.OPFEngine; import net.firejack.platform.api.config.domain.Config; import net.firejack.platform.api.config.model.ConfigType; import net.firejack.platform.api.process.domain.Case; import net.firejack.platform.api.process.domain.Process; import net.firejack.platform.api.process.domain.Task; import net.firejack.platform.core.config.meta.utils.DiffUtils; import net.firejack.platform.core.model.registry.domain.PackageModel; import net.firejack.platform.core.response.ServiceResponse; import net.firejack.platform.core.store.registry.IPackageStore; import net.firejack.platform.core.utils.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.util.*; @Component public class TaskCaseProcessor { private static final String SMA_CONFIG_NAME = "processes-with-multi-activities"; @Autowired @Qualifier("packageStore") private IPackageStore packageStore; private static final Logger logger = Logger.getLogger(TaskCaseProcessor.class); public void saveProcessCaseStrategy(Process process) { boolean isNew = process.getId() == null; boolean supportMultiActivities = process.getSupportMultiActivities() != null && process.getSupportMultiActivities(); if ((isNew && supportMultiActivities) || !isNew) { String processLookup = DiffUtils.lookup(process.getPath(), process.getName()); String configLookup = getConfigLookup(process.getLookup()); ServiceResponse<Config> response = OPFEngine.ConfigService.findByLookup(configLookup, ConfigType.STRING); Config config = null; if (response.isSuccess() && ((config = response.getItem()) != null)) { String[] processLookupList = config.getValue().split(";"); if (processLookupList.length > 0) { Set<String> lookupList = new HashSet<String>(Arrays.asList(processLookupList)); if (supportMultiActivities) { lookupList.add(processLookup); } else { lookupList.remove(processLookup); } String configValue = lookupList.size() == 0 ? "" : lookupList.size() == 1 ? lookupList.iterator().next() : StringUtils.join(lookupList, ';'); config.setValue(configValue); } else if (supportMultiActivities) { config.setValue(processLookup); } else { config = null; } } else if (supportMultiActivities) { config = new Config(); config.setName(SMA_CONFIG_NAME); config.setPath(StringUtils.getPackageLookup(processLookup)); config.setLookup(configLookup); config.setValue(processLookup); PackageModel packageModel = packageStore.findByLookup( StringUtils.getPackageLookup(process.getPath())); config.setParentId(packageModel.getId()); } if (config != null) { saveConfig(config); } } } public void initializeCaseStrategy(Process process) { if (process != null) { Boolean multiActivitySupported = getMultiBranchStrategy(process.getLookup()); process.setSupportMultiActivities(multiActivitySupported); } } public Boolean getMultiBranchStrategy(String processLookup) { String configLookup = getConfigLookup(processLookup); ServiceResponse<Config> response = OPFEngine.ConfigService.findByLookup(configLookup, ConfigType.STRING); Boolean multiBranchStrategy = false; if (response.isSuccess()) { Config config = response.getItem(); if (config != null) { String configValue = config.getValue(); multiBranchStrategy = configValue.contains(processLookup); } } else { logger.warn("Failed to read config bu lookup [" + configLookup + "]. Reason: " + response.getMessage()); } return multiBranchStrategy; } public void initializeCaseStrategy(Map<String, List<Process>> processesMap) { for (Map.Entry<String, List<Process>> entry : processesMap.entrySet()) { List<Process> processList = entry.getValue(); initializeCaseStrategy(processList.get(0)); for (int i = 1; i < processList.size(); i++) { processList.get(i).setSupportMultiActivities(processList.get(0).getSupportMultiActivities()); } } } public void registerTaskProcess(Task task, Map<String, List<Process>> processesMap) { Process process = task.getProcessCase().getProcess(); List<Process> processes = processesMap.get(process.getLookup()); if (processes == null) { processes = new ArrayList<Process>(); processesMap.put(process.getLookup(), processes); } processes.add(process); } public void registerCaseProcess(Case processCase, Map<String, List<Process>> processesMap) { Process process = processCase.getProcess(); List<Process> processes = processesMap.get(process.getLookup()); if (processes == null) { processes = new ArrayList<Process>(); processesMap.put(process.getLookup(), processes); } processes.add(process); } private void saveConfig(Config config) { ServiceResponse<Config> response = config.getId() == null ? OPFEngine.ConfigService.createConfig(config) : OPFEngine.ConfigService.updateConfig(config.getId(), config); if (!response.isSuccess()) { logger.error("Failed to save Multi Activity mode configuration. Reason: " + response.getMessage()); } } private String getConfigLookup(String processLookup) { String processPackageLookup = StringUtils.getPackageLookup(processLookup); return processPackageLookup + '.' + SMA_CONFIG_NAME; } }
true
2d9f55d40f6084ff3d378cd8752ff365ab626a21
Java
manojjain126/Zipper
/src/main/ZipMerge.java
UTF-8
1,664
3.59375
4
[]
no_license
package main; import java.util.Collections; import java.util.List; /* ZipMerge class will first sort the list of Zip pairs and then loop over to find the overlapping zips to merge the zip pairs */ public class ZipMerge { Integer numLoop; public List<List<Integer>> ZipExtend(List<List<Integer>> listOfZipsIn) { //Sorting the zip pairs list Collections.sort(listOfZipsIn,((o1, o2) -> (o1.get(0).compareTo(o2.get(0))))); //Compare and merge zip list elements for(numLoop=0;numLoop<listOfZipsIn.size()-1;) { if((listOfZipsIn.get(numLoop).get(1) >= listOfZipsIn.get(numLoop+1).get(0)) && ((listOfZipsIn.get(numLoop).get(1) >= listOfZipsIn.get(numLoop+1).get(1)))){ listOfZipsIn.remove(numLoop+1); } else if ((listOfZipsIn.get(numLoop).get(1) >= listOfZipsIn.get(numLoop+1).get(0)) && (listOfZipsIn.get(numLoop).get(1) < listOfZipsIn.get(numLoop+1).get(1))){ listOfZipsIn.get(numLoop).set(1,listOfZipsIn.get(numLoop+1).get(1)); listOfZipsIn.remove(numLoop+1); } else if ((listOfZipsIn.get(numLoop).get(1) < listOfZipsIn.get(numLoop+1).get(0)) && (listOfZipsIn.get(numLoop).get(1) < listOfZipsIn.get(numLoop+1).get(1)) && ((listOfZipsIn.get(numLoop+1).get(0) - listOfZipsIn.get(numLoop).get(1)) <=1)){ listOfZipsIn.get(numLoop).set(1,listOfZipsIn.get(numLoop+1).get(1)); listOfZipsIn.remove(numLoop + 1); } else {numLoop++;}; } return listOfZipsIn; } }
true
7649696f9a89fc41da87b8aa8cee55b9aa714804
Java
qibin123/kengleju
/iotservice/src/main/java/com/kangleju/care/iotservice/repository/PositionDataRepository.java
UTF-8
259
1.515625
2
[]
no_license
package com.kangleju.care.iotservice.repository; import org.springframework.data.repository.CrudRepository; import com.kangleju.care.iotservice.model.PositionData; public interface PositionDataRepository extends CrudRepository<PositionData, String> { }
true
79ef8d8d482e49af1dee568e6022729039ae3be5
Java
durgeshtrivedi/Restrorent
/app/src/main/java/com/durgesh/restaurant/ui/home/HomeInteractor.java
UTF-8
4,504
2.265625
2
[]
no_license
package com.durgesh.restaurant.ui.home; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.support.annotation.NonNull; import android.util.Log; import com.durgesh.restaurant.models.googlePlaces.Hotel; import com.durgesh.restaurant.models.googlePlaces.Result; import com.durgesh.restaurant.models.googlePlaces.Place; import com.durgesh.restaurant.network.NetworkHelper; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import java.io.IOException; import java.util.List; import javax.inject.Inject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by durgeshtrivedi on 15/12/17. */ public class HomeInteractor extends Interactor { private HomeContract.Presenter presenter; private HomeContract.HomeView homeView; @Inject public HomeInteractor() { } public void setHomeView(HomeContract.HomeView homeView) { this.homeView = homeView; this.view = homeView; } public void setPresenter(HomeContract.Presenter presenter) { this.presenter = presenter; } public void getUserLocation() { context = homeView.activity().getApplicationContext(); service = NetworkHelper.getGoogleClient(context); if (NetworkHelper.checkPermission(context)) { NetworkHelper.requestPermission(homeView.activity()); } else { mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context); Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation(); locationResult.addOnCompleteListener(homeView.activity(), new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { if (task.isSuccessful()) { mLastKnownLocation = task.getResult(); presenter.setLocation(mLastKnownLocation); Geocoder geocoder = new Geocoder(context); try { Log.v("Lat", "" + mLastKnownLocation.getLatitude()); Log.v("Long", "" + mLastKnownLocation.getLongitude()); List<Address> addresses = geocoder.getFromLocation(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude(), 1); homeView.updateAddress(addresses); callPlaceAPI( mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()); } catch (IOException e) { e.printStackTrace(); } } } }); } } public void getPlaces(double lat, double lng) { context = homeView.activity().getApplicationContext(); callPlaceAPI(lat, lng); } private void callPlaceAPI(double lat, double lng) { final Call<Hotel> call = service.searchNearestPlaces(lat + "," + lng); homeView.showProgressDialog(); call.enqueue(new Callback<Hotel>() { @Override public void onResponse(Call<Hotel> call, Response<Hotel> response) { if (response.isSuccessful()) { if (response.body() != null) { homeView.dissmissDialog(); Log.v("Retrofit response", "" + response.body().toString()); //Place API call List<Result> resultArrayList = response.body().getResults(); populateResult(resultArrayList); } } homeView.dissmissDialog(); } @Override public void onFailure(Call<Hotel> call, Throwable t) { homeView.dissmissDialog(); } }); } private void populateResult( List<Result> resultArrayList) { List <Place> placeList = createPlaceList(resultArrayList); int count = placeList.size(); if (count > 0) { Log.v("Size", "" + count); homeView.updateRestaurantCount(count); homeView.loadHomeList(placeList); homeView.updateView(); } } }
true
88e3f1542ec06bc88a7f93020a50927112da8d4a
Java
zhengkaiw/Assignment6
/src/C/Cat.java
UTF-8
1,698
3.28125
3
[]
no_license
/** * Created by zhengkevin on 2/26/17. */ public class Cat extends Pet implements Boardable{ private String hairLength; protected int smonth; protected int emonth; protected int sday; protected int eday; protected int syear; protected int eyear; public String getHairLength(){ return hairLength; } Cat(String petName, String ownerName, String color, String hairLength){ super(petName, ownerName, color); this.hairLength = hairLength; } public String toString(){ return "CAT:"+System.getProperty("line.separator")+getPetName()+" owned by "+getOwnerName()+System.getProperty("line.separator") +"Color: "+getColor()+System.getProperty("line.separator")+"Sex: "+getSex()+System.getProperty("line.separator") +"Hair: "+ getHairLength(); } public void setBoardStart(int month, int day, int year){ if(month>=1&&month<=12&&day>=1&&day<=31&&year<=9999&year>=1000) { smonth = month; sday = day; syear = year; }else{ System.out.println("Invalid date"); } } public void setBoardEnd(int month, int day, int year){ if(month>=1&&month<=12&&day>=1&&day<=31&&year<=9999&year>=1000) { emonth = month; eday = day; eyear = year; }else{ System.out.println("Invalid date"); } } public boolean boarding(int month, int day, int year){ if (month >= smonth && month <= emonth&&day >= sday && day <= eday&&year >= syear && year<= eyear){ return true; }else{ return false; } } }
true
a8a92c5f04f412401ebf540782ea59bcd8578015
Java
sebaudracco/bubble
/com/vungle/publisher/zg.java
UTF-8
877
1.796875
2
[]
no_license
package com.vungle.publisher; import dagger.MembersInjector; import dagger.internal.Factory; import dagger.internal.MembersInjectors; /* compiled from: vungle */ public final class zg implements Factory<zf> { static final /* synthetic */ boolean f11386a = (!zg.class.desiredAssertionStatus()); private final MembersInjector<zf> f11387b; public /* synthetic */ Object get() { return m14200a(); } public zg(MembersInjector<zf> membersInjector) { if (f11386a || membersInjector != null) { this.f11387b = membersInjector; return; } throw new AssertionError(); } public zf m14200a() { return (zf) MembersInjectors.injectMembers(this.f11387b, new zf()); } public static Factory<zf> m14199a(MembersInjector<zf> membersInjector) { return new zg(membersInjector); } }
true
44209eca3df09dff77f7ef3e478b777058899bac
Java
SansonRoot/account_registration
/app/src/main/java/com/softmastersgroup/umo/umoagent/AddressActivity.java
UTF-8
15,323
1.5625
2
[]
no_license
package com.softmastersgroup.umo.umoagent; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Bundle; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import com.bumptech.glide.Glide; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.SettingsClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.softmastersgroup.umo.umoagent.models.IDCardModel; import com.softmastersgroup.umo.umoagent.models.RegisterBundle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import es.dmoral.toasty.Toasty; import nouri.in.goodprefslib.GoodPrefs; public class AddressActivity extends AppCompatActivity implements OnMapReadyCallback { private GoogleMap mMap; RelativeLayout rlAddress; TextInputLayout tiEmployer; TextInputEditText etUnitNo, etAddress, etEmployer, etHouseNumber; private FusedLocationProviderClient locationProviderClient; private LocationRequest mLocationRequest; private LocationCallback callback; private Location mLocation; private Context ctx; private int pos; private String[] addresses; Button btnNext, btnPrev; TextView tvText, tvLatLng,tvCountryCity; com.softmastersgroup.umo.umoagent.models.Location location; Marker marker; int locationCount = 0; RelativeLayout relDoc; IDCardModel proof_of_address; public static ImageView ivDoc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_address); ctx = AddressActivity.this; init(); createLocationRequest(); locationProviderClient = LocationServices.getFusedLocationProviderClient(this); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(mLocationRequest); SettingsClient client = LocationServices.getSettingsClient(this); Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build()); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } //mLocation = LocationServices.getFusedLocationProviderClient(ctx).getLastLocation().getResult(); //Toasty.success(ctx,mLocation.toString()).show(); task.addOnSuccessListener(AddressActivity.this, new OnSuccessListener<LocationSettingsResponse>() { @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { locationSettingsResponse.getLocationSettingsStates(); createLocationRequest(); } }); callback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { if (locationResult == null) { //Toasty.success(getApplicationContext(), "Location still null").show(); return; } mLocation = locationResult.getLastLocation(); locationCount++; //Toasty.success(getApplicationContext(), "Location Set").show(); Address addr = getAddress(mLocation); if (locationCount <= 1) { LatLng ll = new LatLng(mLocation.getLatitude(), mLocation.getLongitude()); if (marker != null) { marker.setPosition(ll); } else { marker = mMap.addMarker(new MarkerOptions().position(ll)); } mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); mMap.moveCamera(CameraUpdateFactory.newLatLng(ll)); mMap.setMinZoomPreference(18.0f); mMap.getUiSettings().setScrollGesturesEnabled(true); etUnitNo.setText(addr == null ? "" : addr.getFeatureName()); etAddress.setText(addr == null ? "" : addr.getAddressLine(0)); } tvLatLng.setText( String.valueOf(mLocation.getLatitude()) + " , " + String.valueOf(mLocation.getLongitude()) +" "+(addr == null ? "" : addr.getLocality()) +" - "+(addr == null ? "" : addr.getCountryName()) ); //tvCountryCity.setText(addr == null ? "" : addr.getLocality() + " , " + addr.getCountryName()); } }; RegisterBundle bundle = GoodPrefs.getInstance().getObject("register_bundle", RegisterBundle.class); if (bundle.getLocation() != null && bundle.getLocation().size() > 0) { bindData(bundle.getLocation().get(0)); } SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } private void init() { rlAddress = findViewById(R.id.rlAddress); //rlAddress.setVisibility(View.VISIBLE); relDoc = findViewById(R.id.relSupDoc); //relDoc.setVisibility(View.GONE); //etBuildingNo = findViewById(R.id.etBuildingNo); etUnitNo = findViewById(R.id.etUnitNo); etAddress = findViewById(R.id.etAddress); tvCountryCity = findViewById(R.id.tvTownRegion); etEmployer = findViewById(R.id.etEmployer); tiEmployer = findViewById(R.id.tIEmployerName); etHouseNumber = findViewById(R.id.etHouseNumber); btnNext = findViewById(R.id.btnNext); btnPrev = findViewById(R.id.btnPrev); tvText = findViewById(R.id.tvText); tvLatLng = findViewById(R.id.tvLatLng); ivDoc = findViewById(R.id.ivDoc); btnPrev.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(ctx, IDProofActivity.class)); finish(); } }); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setLocationData(); startActivity(new Intent(ctx, AuthActivity.class)); } }); bindAddress(); findViewById(R.id.ivDoc).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (((EditText)findViewById(R.id.etDocNumber)).getText().toString().isEmpty()){ ((EditText)findViewById(R.id.etDocNumber)).setError("Specified Document account required"); return; } proof_of_address.setId_type( ((Spinner) findViewById(R.id.spDocType)).getSelectedItem().toString() ); proof_of_address.setId_number( ((EditText)findViewById(R.id.etDocNumber)).getText().toString() ); GoodPrefs.getInstance().saveObject("proof_of_address",proof_of_address); captureAddress(); } }); } public void captureAddress() { GoodPrefs.getInstance().saveInt("img_type",3); Intent intent; if (proof_of_address != null && proof_of_address.isTaken()) { intent = new Intent(ctx, PreviewActivity.class); intent.putExtra("type", 2); intent.putExtra("session", 1); } else { intent = new Intent(ctx, CameraActivity.class); } intent.putExtra("id", 2); startActivity(intent); } private void bindAddress(){ proof_of_address = GoodPrefs.getInstance().getObject("proof_of_address",IDCardModel.class); if (proof_of_address == null){ proof_of_address = new IDCardModel(); } if (proof_of_address.getImage()!=null && !proof_of_address.getImage().isEmpty()){ Glide.with(getApplicationContext()).load(proof_of_address.getImage()).into((ImageView) findViewById(R.id.ivDoc)); } ((EditText) findViewById(R.id.etDocNumber)).setText(proof_of_address.getId_number()); if (!proof_of_address.getId_type().isEmpty()){ if (proof_of_address.getId_type().equalsIgnoreCase("Water Bill")){ ((Spinner) findViewById(R.id.spDocType)).setSelection(0); }else if (proof_of_address.getId_type().equalsIgnoreCase("Electricity Bill")){ ((Spinner) findViewById(R.id.spDocType)).setSelection(1); }else{ ((Spinner) findViewById(R.id.spDocType)).setSelection(2); } } } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(500); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } private void startLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationProviderClient.requestLocationUpdates(mLocationRequest, callback, null /* Looper */); } private void stopLocationUpdates() { if (locationProviderClient != null && callback != null) locationProviderClient.removeLocationUpdates(callback); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } mMap.setMyLocationEnabled(true); mMap.setMinZoomPreference(18.0f); mMap.getUiSettings().setScrollGesturesEnabled(true); mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); if (mLocation != null) { LatLng ll = new LatLng(mLocation.getLatitude(), mLocation.getLongitude()); if (marker == null) { marker = mMap.addMarker(new MarkerOptions().position(ll)); } else { marker.setPosition(ll); } mMap.moveCamera(CameraUpdateFactory.newLatLng(ll)); } } @Override protected void onPause() { super.onPause(); stopLocationUpdates(); } @Override protected void onResume() { super.onResume(); startLocationUpdates(); } private void setLocationData() { List<com.softmastersgroup.umo.umoagent.models.Location> locations = new ArrayList<>(); RegisterBundle bundle = GoodPrefs.getInstance().getObject("register_bundle", RegisterBundle.class); if (location == null) { location = new com.softmastersgroup.umo.umoagent.models.Location(); } if (pos != 0 && pos != 3) { Address addr = getAddress(mLocation); location.setType("Address"); location.setCountry(addr == null ? "" : addr.getAddressLine(0)); location.setCity(addr == null ? "" : addr.getLocality()); // location.setBuildingno(etBuildingNo.getText().toString()); location.setUnitno(etUnitNo.getText().toString()); location.setStreetaddress(etAddress.getText().toString()); location.setRegion(addr == null ? "" : addr.getLocality()); location.setHousenumber(etHouseNumber.getText().toString()); location.setLatitude(mLocation.getLatitude()); location.setLongitude(mLocation.getLongitude()); locations.add(location); } bundle.setLocation(locations); GoodPrefs.getInstance().saveObject("register_bundle", bundle); } private void bindData(com.softmastersgroup.umo.umoagent.models.Location location1) { if (location1 == null) return; etUnitNo.setText(location1.getUnitno()); //etBuildingNo.setText(location1.getBuildingno()); tvLatLng.setText( String.valueOf(location1.getLatitude()) + ", " + String.valueOf(location1.getLongitude()) +" "+location1.getCity()+" - "+location1.getCountry() ); etAddress.setText(location1.getStreetaddress()); } private Address getAddress(Location location) { List<Address> addresses = null; Geocoder geocoder = new Geocoder(this); try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); } catch (IOException e) { Log.d("IOException", "Not found", e); } catch (IllegalArgumentException e1) { Log.d("IllegalArgumentEx", "Not found", e1); } if (addresses == null || addresses.get(0) == null) { return null; } return addresses.get(0); } }
true
4e8ec04f4c9552d4d455d281283b71785f19febf
Java
xudong94611/first
/SpringMVC/springmvc-mybatis01/src/com/itheima/springmvc/service/ItemService.java
UTF-8
237
1.859375
2
[]
no_license
package com.itheima.springmvc.service; import java.util.List; import com.itheima.springmvc.pojo.Items; public interface ItemService { List<Items> selectItemList(); Items selectItemById(Integer id); void updateItem(Items item); }
true
fc898c250eff8e503bd0009f6cc4aa14c5e5b077
Java
rtybase/pmml-microservice
/src/test/java/com/rtybase/ml/service/phishingclassification/resource/PhishingClassificationResourceTest.java
UTF-8
2,133
2.0625
2
[ "Apache-2.0" ]
permissive
package com.rtybase.ml.service.phishingclassification.resource; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import java.util.HashMap; import java.util.Map; import javax.ws.rs.ClientErrorException; import javax.ws.rs.client.Entity; import javax.ws.rs.core.GenericType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.rtybase.ml.service.phishingclassification.core.UrlResource; import com.rtybase.ml.service.phishingclassification.core.pmml.ScoreCalculator; import com.rtybase.ml.service.phishingclassification.resource.PhishingClassificationResource; import io.dropwizard.testing.junit.ResourceTestRule; public class PhishingClassificationResourceTest { private static final Map<String, Object> RESULT = new HashMap<>(); static { RESULT.put("y", 1); RESULT.put("probability_0", 0.1); RESULT.put("probability_1", 0.9); } @SuppressWarnings("unchecked") private ScoreCalculator<UrlResource> phishingClassifier = mock(ScoreCalculator.class); @Rule public final ResourceTestRule resources = ResourceTestRule.builder() .addResource(new PhishingClassificationResource(phishingClassifier)).build(); @Before public void setup() throws Exception { doReturn(RESULT).when(phishingClassifier).calculate(any(UrlResource.class)); } @Test public void testEvaluation() { Map<String, Object> map = resources.target(PhishingClassificationResource.PATH).request() .post(Entity.json(new UrlResource()), new GenericType<Map<String, Object>>() { }); assertEquals(map, RESULT); } @Test public void testEvaluationWithInvalidInput() { UrlResource input = new UrlResource(); input.setUrlLength(-2); try { resources.target(PhishingClassificationResource.PATH).request().post(Entity.json(input), new GenericType<Map<String, Object>>() { }); fail("Should have not reached this line!"); } catch (ClientErrorException ex) { assertEquals(ex.getResponse().getStatus(), 422); } } }
true
0c6482dda64d2552d827374fbedfc5b129bb2c29
Java
yuhb14/PCshang
/src/com/PCshang/util/InsertDbUtil.java
UTF-8
1,426
2.625
3
[]
no_license
package com.PCshang.util; import java.sql.Connection; import javax.swing.JOptionPane; import com.PCshang.dao.EulerAngleDao; import com.PCshang.dao.MotorVelocityDao; import com.PCshang.model.EulerAngle; import com.PCshang.model.MotorVelocity; import com.PCshang.view.MainFrame; public class InsertDbUtil { private static DbUtil dbUtil =new DbUtil(); private static EulerAngleDao eulerangledao = new EulerAngleDao(); private static MotorVelocityDao motoreulerdao = new MotorVelocityDao(); public static MainFrame mainfrm; public InsertDbUtil(MainFrame mainfrm) { super(); this.mainfrm = mainfrm; } public static void insertDbPCshangUtil(float[] f) { Connection con = null; mainfrm.stopDbUtil=false; if (f.length >= 3) { EulerAngle euler = new EulerAngle(f[0], f[1], f[2]); try { con = DbUtil.getCon(); int n = eulerangledao .add(con, euler); //会得到一个返回值,返回值为1就是添加成功 System.out.println("连接上数据库"); if(f.length >= 6 ) { MotorVelocity velocity = new MotorVelocity(f[3], f[4], f[5]); int m = motoreulerdao.add(con, velocity); } } catch (Exception e) { e.printStackTrace(); } finally { try { dbUtil.closeCon(con); mainfrm.stopDbUtil = true; System.out.println("关闭数据库"); } catch (Exception e) { e.printStackTrace(); } } } } }
true
400605ffabeab15bacf92aed308d35956b917bf1
Java
jcqln/IF3111-Tugas-1-Android
/app/src/main/java/com/tomjerry/RefreshTrackJerryActivity.java
UTF-8
2,957
2.078125
2
[ "MIT" ]
permissive
package com.tomjerry; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; 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.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class RefreshTrackJerryActivity extends ActionBarActivity { private Double latitude; private Double longitude; private String valid_until; private long valid_until_long; private JSONHandler obj; private boolean lock; private String url1 = "http://167.205.32.46/pbd/api/track?nim=13512074"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_refresh_track_jerry); lock = true; new Task().execute(getApplicationContext()); Thread thread = new Thread() { @Override public void run() { try { super.run(); while(lock) { } } catch (Exception e) { e.printStackTrace(); } finally { Intent i = new Intent(RefreshTrackJerryActivity.this, LocateActivity.class); i.putExtra("latitude",latitude); i.putExtra("longitude",longitude); i.putExtra("valid_until",valid_until); i.putExtra("valid_until_long",valid_until_long); startActivity(i); finish(); } } }; thread.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_refresh_track_jerry, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement /*if (id == R.id.action_settings) { return true; }*/ return super.onOptionsItemSelected(item); } public class Task extends AsyncTask<Context, Void, Void> { @Override protected Void doInBackground(Context... params) { Context context = params[0]; System.out.println(context.toString()); obj = new JSONHandler(url1); obj.fetchJSON(); while(obj.parsingComplete); String lat = obj.getLat(); latitude = Double.parseDouble(lat); String lon = obj.getLon(); longitude = Double.parseDouble(lon); valid_until = obj.getValid_until(); valid_until_long = Long.parseLong(obj.getValid_until()); long epoch = Long.parseLong(valid_until); Date valid = new Date(epoch*1000); Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); valid_until = formatter.format(valid); lock = false; return null; } } }
true
ae823faa8f4fb2251aaf0e4e76bd835454a7dbe2
Java
shivtest/epibook.github.io
/solutions/java/src/main/java/com/epi/FindingMinMax.java
UTF-8
1,851
3.25
3
[]
no_license
package com.epi; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import com.epi.utils.Pair; /** * @author translated from c++ by Blazheev Alexander */ public class FindingMinMax { // @include // Return (min, max) pair of elements in A. public static Pair<Integer, Integer> findMinMax(List<Integer> A) { if (A.size() <= 1) { return new Pair<Integer, Integer>(A.get(0), A.get(0)); } // Initialize the min and max pair. Pair<Integer, Integer> minMaxPair = Pair.minmax(A.get(0), A.get(1)); for (int i = 2; i + 1 < A.size(); i += 2) { Pair<Integer, Integer> localPair = Pair.minmax(A.get(i), A.get(i + 1)); minMaxPair = new Pair<Integer, Integer>(Math.min(minMaxPair.getFirst(), localPair.getFirst()), Math.max(minMaxPair.getSecond(), localPair.getSecond())); } // Special case: if there is odd number of elements in the array, we still // need to compare the last element with the existing answer. if ((A.size() & 1) != 0) { minMaxPair = new Pair<Integer, Integer>(Math.min(minMaxPair.getFirst(), A.get(A.size() - 1)), Math.max(minMaxPair.getSecond(), A.get(A.size() - 1))); } return minMaxPair; } // @exclude public static void main(String[] args) { Random r = new Random(); for (int times = 0; times < 10000; ++times) { int n; if (args.length == 1) { n = Integer.parseInt(args[0]); } else { n = r.nextInt(10000) + 1; } ArrayList<Integer> A = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) { A.add(r.nextInt(1000000)); } Pair<Integer, Integer> res = findMinMax(A); assert (res.getFirst().equals(Collections.min(A)) && res.getSecond() .equals(Collections.max(A))); } } }
true