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
435fe1883bca7c80af91eb5eb8a3f1b0ab94a605
Java
AsherAngelo/springbootelastic
/src/main/java/cn/pomxl/springbootelastic/SpringbootelasticApplication.java
UTF-8
693
1.859375
2
[]
no_license
package cn.pomxl.springbootelastic; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * springboot默认支持俩中方式跟es进行交互 * 1、Jest(默认不生效缺少相应的包)(io.searchbox.client.JestClient) * 2、springDate Elasticsearch * 1)client节点信息clustnodes;clusterName * 2)ElashsearchTemplate才做es * 3)编写一个ElasticsearchRepository的子接口进行较好相当于jdbc */ @SpringBootApplication public class SpringbootelasticApplication { public static void main(String[] args) { SpringApplication.run(SpringbootelasticApplication.class, args); } }
true
7553a2a201852249da6dc788e9330360e1357c27
Java
TimePath/ffonline
/src/com/timepath/ffonline/MyApplication.java
UTF-8
2,760
2.5
2
[]
no_license
package com.timepath.ffonline; import com.jme3.app.SimpleApplication; import com.jme3.app.state.AppState; import com.jme3.math.FastMath; import com.jme3.network.AbstractMessage; import com.jme3.network.serializing.Serializable; import com.jme3.network.serializing.Serializer; import com.jme3.texture.Image; import com.jme3.texture.Texture; import com.jme3.texture.Texture2D; import com.jme3.texture.plugins.AWTLoader; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; /** * * @author TimePath */ public abstract class MyApplication extends SimpleApplication { public MyApplication(AppState... states) { super(states); Serializer.registerClass(PingMessage.class); Serializer.registerClass(PongMessage.class); Serializer.registerClass(MovementMessage.class); } public MyApplication() { this((AppState) null); } protected void zoom(float frustumSize) { float aspect = cam.getWidth() / cam.getHeight(); cam.setFrustum(-1000, 1000, -aspect * frustumSize, aspect * frustumSize, frustumSize, -frustumSize); } protected float getFov() { float h = cam.getFrustumTop(); float near = cam.getFrustumNear(); float fovY = FastMath.atan(h / near) / (FastMath.DEG_TO_RAD * .5f); return fovY; } protected void setFov(float fovY) { float near = cam.getFrustumNear(); float h = FastMath.tan(fovY * .5f * FastMath.DEG_TO_RAD) * near; float w = h * (cam.getFrustumRight() / cam.getFrustumTop()); cam.setFrustumTop(h); cam.setFrustumBottom(-h); cam.setFrustumLeft(-w); cam.setFrustumRight(w); } protected Texture2D convert(BufferedImage src) { BufferedImage i = src; boolean scale = false; if (scale) { int newWidth = src.getWidth() * 2; int newHeight = src.getWidth() * 2; i = new BufferedImage(newWidth, newHeight, src.getType()); Graphics2D g = i.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g.drawImage(src, 0, 0, newWidth, newHeight, 0, 0, src.getWidth(), src.getHeight(), null); g.dispose(); } Image textureImage = new AWTLoader().load(i, true); Texture2D tex = new Texture2D(textureImage); tex.setMagFilter(Texture.MagFilter.Nearest); tex.setMinFilter(Texture.MinFilter.NearestNoMipMaps); return tex; } @Serializable public static class PingMessage extends AbstractMessage { } @Serializable public static class PongMessage extends AbstractMessage { } }
true
0fba697611181b83cfe5fe460dd224939fd03ced
Java
brown0503/MathExercisesJavaAppletBase
/VTLine.java
UTF-8
513
2.484375
2
[]
no_license
/* * MathExercisesJavaAppletBase * * by Albert Zeyer / developed for Lehrstuhl A für Mathematik at the RWTH Aachen University * code under GPLv3+ */ package applets.Termumformungen$in$der$Technik_08_Ethanolloesungen; public class VTLine extends VTLabel { public VTLine(int stepX, int stepY, int width) { super("", stepX, stepY, "monospace"); while(getWidth() < width) { this.setText(getText() + "―"); } } public static int height = 10; public int getHeight() { return height; } }
true
012b16e9d60d75cbf66a257b7073bee798b0b437
Java
gtwave1/ruanchuang
/JavaOJSystem/src/main/java/cn/superman/web/vo/request/ProblemAnswerVO.java
UTF-8
1,000
2.125
2
[]
no_license
package cn.superman.web.vo.request; import java.math.BigInteger; import javax.validation.constraints.NotNull; public class ProblemAnswerVO { @NotNull(message = "代码语言不能为空") private String codeLanguage; @NotNull(message = "题目编号不能为空") private BigInteger submitProblemId; @NotNull(message = "不能提交空代码") private String code; @NotNull(message = "题目价值不能为空") private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getCodeLanguage() { return codeLanguage; } public void setCodeLanguage(String codeLanguage) { this.codeLanguage = codeLanguage; } public BigInteger getSubmitProblemId() { return submitProblemId; } public void setSubmitProblemId(BigInteger submitProblemId) { this.submitProblemId = submitProblemId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
true
aadbadaf0a63f968b23c1e97c9221569484762a9
Java
lmmmowi/byte-code-inspect
/src/main/java/com/lmmmowi/bci/enums/ClassAccessFlag.java
UTF-8
518
2.65625
3
[]
no_license
package com.lmmmowi.bci.enums; /** * @Author: lmmmowi * @Date: 2020/1/15 * @Description: */ public enum ClassAccessFlag { ACC_PUBLIC(0x0001), ACC_FINAL(0x0010), ACC_SUPER(0x0020), ACC_INTERFACE(0x0200), ACC_ABSTRACT(0x0400), ACC_SYNTHETIC(0x1000), ACC_ANOTATION(0x2000), ACC_ENUM(0x4000); private int value; ClassAccessFlag(int value) { this.value = value; } public boolean match(int accessFlag) { return (value & accessFlag) >0; } }
true
fc680ae9dd3e42815f53978f1b8d0a447bbe0412
Java
zhilien-tech/zhiliren-we
/we-web-parent/web-linyun-airline/src/test/java/com/xiaoka/test/TestPnr.java
UTF-8
1,527
2.5625
3
[]
no_license
/** * TestPnr.java * com.xiaoka.test * Copyright (c) 2017, 北京科技有限公司版权所有. */ package com.xiaoka.test; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * TODO(这里用一句话描述这个类的作用) * <p> * TODO(这里描述这个类补充说明 – 可选) * * @author 朱晓川 * @Date 2017年2月16日 */ public class TestPnr { public static void main(String[] args) throws Exception { String input = "128FEBAKLSYD/D¥VA<<\n" + " 28FEB TUB AKL/Z¥13 SYD/-2\n" + "1VA/NZ 7419 Y4 B4 H4 K4 L4 E4 AKLSYD 100P 235P 320 0 DCA /E\n" + " N4 V4 Q0 T0 M0 U0\n" + "2VA/NZ 7405 J4 C4 D4 I4 Y4 B4*AKLSYD 405P 540P 763 0 DCA /E\n" + " H4 K4 L4 E4 N4 V4 Q4 T0\n" + "3VA/NZ 7405 J4 C4 D4 I4 Y4 B4*AKLSYD 405P 540P 763 0 DCA /E\n" + " H4 K4 L4 E4 N4 V4 Q4 T0\n" + "4VA/** 7405 J4 C4 D4 I4 Y4 B4*AKLSYD 405P 540P 76H M 0 DCA /E\n" + " H4 K4 L4 E4 N4 V4 Q4 T0\n" + "5VA/NZ 7405 J4 C4 D4 I4 Y4 B4*AKLSYD 405P 540P 763 0 DCA /E\n" + " H4 K4 L4 E4 N4 V4 Q4 T0\n"; //(?s)表示开启跨行匹配,\\d{1}一位数字,[A-Za-z]{2}两位字母,/斜线,\\s空白字符,.+任意字符出现1到多次,最后以\n换行结束 String regex = "(?s)\\d{1}[A-Za-z]{2}/.{2}\\s.+?\\d\n"; Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(input); while (m.find()) { System.out.println(m.group() + "|||"); } } }
true
4efda2736bd599bece49c84a943596c48dc52dfd
Java
SaidaBuewendt/Java_OOP
/2021_02_16_CocktailSort_CombSort/src/Excersice.java
UTF-8
468
3.0625
3
[]
no_license
public class Excersice { public static void main(String[] args) { int[] newArray = CocktailSort.createArray(10); int[] secondArray = new int[] {100, 5, 36, 56, 90, 3, 5, 68}; int [] defaultArray = new int[10]; int [] idealArray = new int[]{1,2,3,4,5,6,7,8,9,10}; unsortArray(idealArray); } private static void unsortArray(int[] idealArray) { for (int i = 0; i < idealArray.length; i++) { } } }
true
32ead57c6bb0a448ce283a413a9942634aae928c
Java
Faylixe/jammy
/fr.faylixe.jammy.addons.java/src/fr/faylixe/jammy/addons/java/JavaSolverRunner.java
UTF-8
1,642
2.421875
2
[]
no_license
package fr.faylixe.jammy.addons.java; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import fr.faylixe.jammy.core.ProblemSolver; import fr.faylixe.jammy.core.addons.AbstractLaunchSolverRunner; import fr.faylixe.jammy.core.addons.ISolverRunner; /** * {@link ISolverRunner} implementation for Java language. * * @author fv */ public final class JavaSolverRunner extends AbstractLaunchSolverRunner { /** * Default constructor. * * @param solver Solver which aims to be ran. * @param monitor Monitor instance used for Java execution. */ public JavaSolverRunner(final ProblemSolver solver, final IProgressMonitor monitor) { super(solver, monitor); } /** {@inheritDoc} **/ @Override protected String getLaunchConfigurationType() { return IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION; } /** {@inheritDoc} **/ @Override protected Map<String, String> createAttributesMap(final String arguments, final String output) { final Map<String, String> attributes = createBaseMap(output); final IFile file = getSolver().getFile(); final String filename = file.getName(); final String name = filename.substring(0, filename.length() - 5); // Note : -5 for .java extension. attributes.put(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, name); attributes.put(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, getSolver().getProject().getName()); attributes.put(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, arguments); return attributes; } }
true
a8f8cc09dc3da35152fba82ffe7ac90d4e29400e
Java
leegreiner/baseProject
/src/main/java/edu/duke/rs/baseProject/user/passwordReset/PasswordResetService.java
UTF-8
482
1.953125
2
[]
no_license
package edu.duke.rs.baseProject.user.passwordReset; import org.springframework.validation.annotation.Validated; import edu.duke.rs.baseProject.user.User; import jakarta.validation.Valid; @Validated public interface PasswordResetService { void initiatePasswordReset(@Valid InitiatePasswordResetDto passwordResetDto); void initiatePasswordReset(User user); void processPasswordReset(@Valid PasswordResetDto passwordResetDto); void expirePasswordResetIds(); }
true
5c2bb72382ac748e295a781c810e941251b05cc2
Java
simon-xu-ss/Java-Basic-Day-2
/assignment3.java
UTF-8
1,065
4.1875
4
[]
no_license
interface Shape { // Create a Shape Interface with the methods "calculateArea" and "display". // Create a Rectangle, Circle, and Triangle class to implement that interface. public void calculateArea(); public void display(); } class Rectangle implements Shape { public void calculateArea() { System.out.println("Rectangle area"); } public void display() { System.out.println("display reactangle"); } } class Circle implements Shape { public void calculateArea() { System.out.println("Circle area"); } public void display() { System.out.println("display circle"); } } class Triangle implements Shape { public void calculateArea() { System.out.println("Triangle area"); } public void display() { System.out.println("Display triangle"); } } class Main { public static void main(String[] args) { Rectangle rec = new Rectangle(); rec.calculateArea(); rec.display(); Circle cir = new Circle(); cir.calculateArea(); cir.display(); Triangle tri = new Triangle(); tri.calculateArea(); tri.display(); } }
true
750137875b3eec5339a0b8392bad1694b42a71a7
Java
nevershow/ProgrammingTraining
/GridWorld/stage2/Part4/RockHound/RockHound.java
UTF-8
670
3.046875
3
[]
no_license
import info.gridworld.actor.Actor; import info.gridworld.actor.Critter; import info.gridworld.actor.Rock; import info.gridworld.grid.Location; import java.util.ArrayList; import java.awt.Color; public class RockHound extends Critter { private static final double DARKENING_FACTOR = 0.2; /** * Randomly selects a neighbor that is a rock and remove it. */ public void processActors(ArrayList<Actor> actors) { int n = actors.size(); if (n == 0) { return; } else { for (Actor actor : actors) if (actor instanceof Rock) actor.removeSelfFromGrid(); } } }
true
ab632cc5d30f1fa52e087e894656914ef3185aa8
Java
ChaoLingW/Code
/Java/homework0713/src/com/hpe/java2/Student.java
UTF-8
2,325
4.21875
4
[]
no_license
package com.hpe.java2; /** * * @author chaoling * @date 2018年7月13日下午6:00:02 * @Description */ /* * 定义一个表示学生信息的类Student,要求如下: (1)类Student的成员变量: sNO * 表示学号;sName表示姓名;sSex表示性别;sAge表示年龄;sJava:表示Java课程成绩。 (2)类Student带参数的构造方法: * 在构造方法中通过形参完成对成员变量的赋值操作。 (3)类Student的方法成员: getNo():获得学号; getName():获得姓名; * getSex():获得性别; getAge()获得年龄; getJava():获得Java 课程成绩 * 根据类Student的定义,创建五个该类的对象,输出每个学生的信息,计算并输出这五个学生Java语言成绩的平均值, * 以及计算并输出他们Java语言成绩的最大值和最小值。(思路:对象数组) */ public class Student { private String sNO; private String sName; private String sSex; private int sAge; private int sJava; // 通过形参完成对成员变量的赋值操作 public Student(String sNO, String sName, String sSex, int sAge, int sJava) { super(); this.sNO = sNO; this.sName = sName; this.sSex = sSex; this.sAge = sAge; this.sJava = sJava; } public Student() { super(); } public String getsNO() { return sNO; } public String getsName() { return sName; } public String getsSex() { return sSex; } public int getsAge() { return sAge; } public int getsJava() { return sJava; } @Override public String toString() { return "Student [sNO=" + sNO + ", sName=" + sName + ", sSex=" + sSex + ", sAge=" + sAge + ", sJava=" + sJava + "]"; } //计算并输出最大值和最小值与平均值 public static void value(Student[] student) { double avg = 0.0; int sum = 0; int min; int max; min = max = student[0].getsJava(); for (Student s : student) { // 比较获取最大值 if (s.getsJava() > max) max = s.getsJava(); // 比较获取最小值 if (s.getsJava() < min) min = s.getsJava(); // 求和 sum += s.getsJava(); } // 求平均分 avg = sum /student.length; // 输出平均分,最大值,最小值 System.out.println("平均分:" + avg + " 最大值:" + max + " 最小值" + min); } }
true
95f8c66be87e99245f54e71264b1220b54b5d024
Java
gdming123/deflfsd
/USBDemo/app/src/main/java/com/example/admin/usbdemo/MainActivity.java
UTF-8
4,311
2.328125
2
[]
no_license
package com.example.admin.usbdemo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.ServerSocket; import java.net.Socket; import cn.gavinliu.android_pc_socket_connection.R; public class MainActivity extends AppCompatActivity { private Button btn_action; private TextView TV; private EditText ET; private String lolo = new String(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ET = (EditText) findViewById(R.id.ET); btn_action = (Button) findViewById(R.id.btn_action); TV = (TextView) findViewById(R.id.TV); serverThread = new ServerThread(); serverThread.start(); btn_action.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // boolean enableAdb = (Settings.Secure.getInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0); /* if (!enableAdb) { Toast.makeText(MainActivity.this, "请授权USB调试...", Toast.LENGTH_SHORT).show(); //Settings.Secure.putInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 1); // Settings.Global.putInt(MainActivity.this.getContentResolver(), Settings.Global.ADB_ENABLED, 1); ComponentName componentName = new ComponentName("com.android.settings", "com.android.settings.DevelopmentSettings"); Intent intent = new Intent(); intent.setComponent(componentName); intent.setAction("android.intent.action.View"); MainActivity.this.startActivity(intent); } else { Toast.makeText(MainActivity.this, "USB已经打开,无需重复打开", Toast.LENGTH_SHORT).show(); }*/ } }); } private static final String TAG = "ServerThread"; ServerThread serverThread; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Toast.makeText(getApplicationContext(), msg.getData().getString("MSG", "Toast"), Toast.LENGTH_SHORT).show(); TV.setText(lolo+ msg.getData().getString("MSG", "Toast")); } }; @Override protected void onDestroy() { super.onDestroy(); serverThread.setIsLoop(false); } class ServerThread extends Thread { boolean isLoop = true; public void setIsLoop(boolean isLoop) { this.isLoop = isLoop; } @Override public void run() { Log.d(TAG, "running"); ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(9000); while (isLoop) { Socket socket = serverSocket.accept(); Log.d(TAG, "accept"); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); String msg = inputStream.readUTF(); Message message = Message.obtain(); Bundle bundle = new Bundle(); bundle.putString("MSG", msg); message.setData(bundle); handler.sendMessage(message); socket.close(); } } catch (Exception e) { e.printStackTrace(); } finally { Log.d(TAG, "destory"); if (serverSocket != null) { try { serverSocket.close(); } catch (Exception e) { e.printStackTrace(); } } } } } }
true
6b1a6b5ca09b8abb5d0283dc341360fa538666df
Java
riqmariz/Projeto-Introducao-Programacao
/PIP/src/excecoes/AtualizacaoIncompativelException.java
UTF-8
211
2.328125
2
[]
no_license
package excecoes; public class AtualizacaoIncompativelException extends Exception { public AtualizacaoIncompativelException() { super("Voce tentou atualizar o produto com um tipo diferente do dele"); } }
true
88b03082601ec3c37f7625ff8c7154d733228c0d
Java
manocormen/music-library
/app/src/main/java/com/example/android/musiclibrary/ArethaFranklinActivity.java
UTF-8
1,137
2.890625
3
[]
no_license
package com.example.android.musiclibrary; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; public class ArethaFranklinActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.music_list); // Create music array list String [] musicNames = {"Respect", "Think", "A Natural Woman"}; String [] albumNames = {"I Never Loved a Man the Way I Love You", "Aretha Now", "Lady Soul"}; ArrayList<Music> music = new ArrayList<Music>(); for (int i = 0; i < musicNames.length; i++) { music.add(new Music(musicNames[i], albumNames[i])); } // Create music adapter --- interface between grid view and music objects MusicAdapter musicAdapter = new MusicAdapter(this, music); // Get music list ListView musicListView = findViewById(R.id.music_list_view); // Link list and adapter musicListView.setAdapter(musicAdapter); } }
true
15b3b22eeaf34a371b807917d82bb864b39e6c21
Java
flame123flame/backend-springboot-ims
/src/main/java/th/go/excise/ims/ia/vo/Int091305Vo.java
UTF-8
801
1.945313
2
[]
no_license
package th.go.excise.ims.ia.vo; import java.util.List; public class Int091305Vo { private String budgetYear; private String ubillTypeStr; private String ubillType; List<Int091305QuarterVo> quarter; public String getUbillTypeStr() { return ubillTypeStr; } public void setUbillTypeStr(String ubillTypeStr) { this.ubillTypeStr = ubillTypeStr; } public String getUbillType() { return ubillType; } public void setUbillType(String ubillType) { this.ubillType = ubillType; } public List<Int091305QuarterVo> getQuarter() { return quarter; } public void setQuarter(List<Int091305QuarterVo> quarter) { this.quarter = quarter; } public String getBudgetYear() { return budgetYear; } public void setBudgetYear(String budgetYear) { this.budgetYear = budgetYear; } }
true
62f024667999a0b3de057f22f497519199324427
Java
axpert1/Motanad
/app/src/main/java/com/motanad/motanad/modelTemp/NetworkTemp.java
UTF-8
422
1.976563
2
[]
no_license
package com.motanad.motanad.modelTemp; import com.motanad.motanad.models.NetworkModel; import java.util.ArrayList; import java.util.List; /** * Created by Admin on 11-12-17. */ public class NetworkTemp { /** * data : [{"level":"LEVEL1","total":0}] * status : 1 * message : Network Level List */ public int status; public String message; public ArrayList<NetworkModel> data; }
true
f9adbcfebbb8e27b29ee71534a597b79dd7fa58c
Java
Eduard-Davletshin/Yandex.Translate
/app/src/main/java/com/example/eddy/yandextranslate/Models/Dictionary/Mean.java
UTF-8
867
2.59375
3
[]
no_license
package com.example.eddy.yandextranslate.Models.Dictionary; import android.os.Parcel; import android.os.Parcelable; public class Mean implements Parcelable { public static final Creator<Mean> CREATOR = new Creator<Mean>() { @Override public Mean createFromParcel(Parcel in) { return new Mean(in); } @Override public Mean[] newArray(int size) { return new Mean[size]; } }; private String text; protected Mean(Parcel in) { text = in.readString(); } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(text); } }
true
512ab5a35dc1280dbaad877496c96e57809fcd14
Java
FScaccheri/Algo3TP2-clone-
/src/modelo/excepciones/ConstruccionImposible.java
UTF-8
94
1.554688
2
[]
no_license
package modelo.excepciones; public class ConstruccionImposible extends RuntimeException { }
true
2c3aa93fadd33683e472f0ee2d56100a40befb72
Java
watger/L3Project
/NetBeansProjects/scrabble/src/PackageView/GameOptionJPanel.java
UTF-8
1,809
2.671875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package PackageView; import PackageController.ChangeCardActionListener; import PackageController.NewPartyActionListener; import PackageModel.Party; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; /** * * @author pardojeremie */ public class GameOptionJPanel extends JPanel{ private JPanel jpanelBoutton, cards; private JButton menuButton, gameStartButton; private NameSelectionJPanel tabOfNameSelectionJPanel[] = new NameSelectionJPanel [4]; public GameOptionJPanel(Party party) { super(); this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); for(int i = 0 ;i < tabOfNameSelectionJPanel.length; i++) { tabOfNameSelectionJPanel[i] = new NameSelectionJPanel(); this.add(tabOfNameSelectionJPanel[i]); } menuButton = new JButton("MENU"); menuButton.addActionListener(new ChangeCardActionListener(party.getMainJFrame(),"MenuJPanel")); gameStartButton = new JButton("START"); gameStartButton.addActionListener(new ChangeCardActionListener(party.getMainJFrame(),"GameMainJPanel")); gameStartButton.addActionListener(new NewPartyActionListener(this,party)); jpanelBoutton = new JPanel(); jpanelBoutton.setLayout(new BoxLayout(jpanelBoutton, BoxLayout.X_AXIS)); jpanelBoutton.add( menuButton); jpanelBoutton.add( gameStartButton); this.add(jpanelBoutton); } public NameSelectionJPanel[] getTabOfNameSelectionJPanel() { return tabOfNameSelectionJPanel; } }
true
add4e06795b01a216741f311cccd25c2ac92b6d3
Java
TheoCavinato/bgee_apps
/bgee-core/src/main/java/org/bgee/model/expressiondata/ConditionService.java
UTF-8
2,846
2.328125
2
[]
no_license
package org.bgee.model.expressiondata; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bgee.model.CommonService; import org.bgee.model.Service; import org.bgee.model.ServiceFactory; /** * A {@link Service} to obtain {@link Condition} objects. * Users should use the {@link org.bgee.model.ServiceFactory} to obtain {@code ConditionService}s. * * @author Valentine Rech de Laval * @version Bgee 14, Feb. 2017 * @since Bgee 13, Oct. 2016 */ //FIXME: there shouldn't be any ConditionService for now public class ConditionService extends CommonService { // // private static final Logger log = LogManager.getLogger(ConditionService.class.getName()); // // public static enum Attribute implements Service.Attribute { // ANAT_ENTITY_ID, DEV_STAGE_ID, SPECIES_ID; // } /** * @param serviceFactory The {@code ServiceFactory} to be used to obtain * {@code Service}s and {@code DAOManager}. * @throws IllegalArgumentException If {@code serviceFactory} is {@code null}. */ public ConditionService(ServiceFactory serviceFactory) { super(serviceFactory); } // // /** // * Retrieve {@code Condition}s for the requested species IDs. If several species IDs // * are provided, the {@code Condition}s existing in any of them are retrieved. // * // * @param speciesIds A {@code Collection} of {@code Integer}s that are IDs of species // * for which to return the {@code Condition}s. // * @param attributes A {@code Collection} of {@code Attribute}s defining the // * attributes to populate in the returned {@code Condition}s. // * If {@code null} or empty, all attributes are populated. // * @return A {@code Stream} of {@code Condition}s retrieved for // * the requested species IDs. // */ // public Stream<Condition> loadConditionsBySpeciesId(Collection<Integer> speciesIds, // Collection<Attribute> attributes) { // log.entry(speciesIds, attributes); // log.warn("Retrieval of conditions by species ID not yet implemented."); // Set<Integer> clonedSpeciesIds = speciesIds == null? new HashSet<>(): new HashSet<>(speciesIds); // Set<Attribute> clonedAttributes = attributes == null? new HashSet<>(): new HashSet<>(attributes); // // return log.exit(getDaoManager().getConditionDAO().getConditionsBySpeciesIds( // clonedSpeciesIds, convertConditionServiceAttrsToConditionDAOAttrs(clonedAttributes)).stream() // .map(cTO-> mapConditionTOToCondition(cTO))); // } }
true
fad1d9cee96591d22af82298dfc8cb34f5341c46
Java
sergio-gimenez/spreadsheet_arqsoft_2021
/spreadsheet/src/main/java/edu/upc/etsetb/arqsoft/spreadsheet/entities/content/Range.java
UTF-8
2,091
2.8125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.upc.etsetb.arqsoft.spreadsheet.entities.content; import edu.upc.etsetb.arqsoft.spreadsheet.entities.BadCoordinateException; import edu.upc.etsetb.arqsoft.spreadsheet.entities.Cell; import edu.upc.etsetb.arqsoft.spreadsheet.entities.Coordinate; import edu.upc.etsetb.arqsoft.spreadsheet.entities.Spreadsheet; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author osboxes */ public class Range { private Set<Cell> range = new HashSet<Cell>(); private static final Pattern RANGE_PATTERN = Pattern.compile("([a-zA-Z]+\\d+):([a-zA-Z]+\\d+)"); public Range(String range, Spreadsheet spreadsheet) throws BadCoordinateException { Matcher m = getMatcher(range); if (!m.matches()) { throw new IllegalArgumentException("Invalid range argument"); } Coordinate initCoord, finalCoord; initCoord = new Coordinate(m.group(1)); finalCoord = new Coordinate(m.group(2)); if (initCoord.getRow() > finalCoord.getRow() || initCoord.getColumnAsInt() > finalCoord.getColumnAsInt()) { throw new IllegalArgumentException("Invalid range argument"); } this.range.add(spreadsheet.getCell(initCoord)); for (int r = initCoord.getRow(); r <= finalCoord.getRow(); r++) { for (int c = initCoord.getColumnAsInt(); c <= finalCoord.getColumnAsInt(); c++) { Coordinate coord = new Coordinate(c, r); Cell cell = spreadsheet.getCell(initCoord); this.range.add(spreadsheet.getCell(new Coordinate(c, r))); } } this.range.add(spreadsheet.getCell(finalCoord)); } private Matcher getMatcher(String coordinate) { return RANGE_PATTERN.matcher(coordinate); } public Set<Cell> getCells(){ return this.range; } }
true
1b8813240d4ff3f8b46f0d1d90bb7acd03831183
Java
MaiKurakiTT/yiyao
/app/src/main/java/com/lxkj/yiyao/adapter/JieYeZhengShuAdapter.java
UTF-8
2,176
2.046875
2
[]
no_license
package com.lxkj.yiyao.adapter; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.lxkj.yiyao.R; import com.lxkj.yiyao.activity.MuBanActivity; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by liqinpeng on 2017/3/12 0012. */ public class JieYeZhengShuAdapter extends BaseAdapter { JSONArray objects; JSONObject object; public JieYeZhengShuAdapter(String result) { //objects = JSONArray.parseArray(result); object = JSONObject.parseObject(result); } @Override public int getCount() { return 1; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder; if (view == null) { view = View.inflate(viewGroup.getContext(), R.layout.jieyezhengshu_item, null); holder = new ViewHolder(view); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } //JSONObject object = objects.getJSONObject(i); if (object != null) { holder.name.setText("" + object.get("zsname").toString()); } holder.rootLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), MuBanActivity.class); intent.putExtra("imagePath", object.get("imageurl").toString()); v.getContext().startActivity(intent); } }); return view; } static class ViewHolder { @BindView(R.id.name) TextView name; @BindView(R.id.root_layout) LinearLayout rootLayout; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
true
4bd0b7c8e632bd1c4c0cbba33baa4e3ca0b8cdbb
Java
League-Level0-Student/level-0-module-0-Pixel-Hue
/src/_02_output_dialog/_1_morning_zombie/MorningZombie.java
UTF-8
335
2.0625
2
[]
no_license
package _02_output_dialog._1_morning_zombie; import javax.swing.JOptionPane; public class MorningZombie { public static void main(String[] args) { JOptionPane.showMessageDialog(null,"Have Breakfeast!"); JOptionPane.showMessageDialog(null,"Brush Your Teeth!"); JOptionPane.showMessageDialog(null,"Go to School/Online School"); } }
true
a728f2def5af92481ddce45c12e5bc3459a2ee34
Java
Karla-Ortiz/guiasReport
/src/main/java/com/guatex/sacod_reporteguias/entities/PuntoLiquidacion.java
UTF-8
737
2.53125
3
[]
no_license
/** * */ package com.guatex.sacod_reporteguias.entities; /** * @author DYOOL * */ public class PuntoLiquidacion { private String codigo, nombre; public String notNull(String var) { return var != null ? var.trim() : ""; } // --------------------- GETTERS AND SETTERS ----------------------/ /** * @return the codigo */ public String getCodigo() { return notNull(codigo); } /** * @return the nombre */ public String getNombre() { return notNull(nombre); } /** * @param codigo the codigo to set */ public void setCodigo(String codigo) { this.codigo = notNull(codigo); } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = notNull(nombre); } }
true
5fdcc23b501e1815e3e20ad3b1d8524c4227cc3c
Java
osvid/Tarea3-Almacenamiento
/app/src/androidTest/java/uv/edu/tarea3/ApplicationTest.java
UTF-8
8,698
2.140625
2
[]
no_license
package uv.edu.tarea3; import android.app.Instrumentation; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.test.uiautomator.UiDevice; import android.test.suitebuilder.annotation.LargeTest; import android.widget.CheckBox; import android.widget.EditText; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.StringReader; import java.util.ArrayList; import uv.edu.customlog.InfoLog; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.matcher.ViewMatchers.withId; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ class Datos { private String nombre; private int dobles; private int ganadores; private double porcentaje_primeros; private int errores_no_forzados; private double porcenctaje_breakpoints_ganados; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getDobles() { return dobles; } public void setDobles(int dobles) { this.dobles = dobles; } public int getGanadores() { return ganadores; } public void setGanadores(int ganadores) { this.ganadores = ganadores; } public double getPorcentaje_primeros() { return porcentaje_primeros; } public void setPorcentaje_primeros(double porcentaje_primeros) { this.porcentaje_primeros = porcentaje_primeros; } public int getErrores_no_forzados() { return errores_no_forzados; } public void setErrores_no_forzados(int errores_no_forzados) { this.errores_no_forzados = errores_no_forzados; } public double getPorcenctaje_breakpoints_ganados() { return porcenctaje_breakpoints_ganados; } public void setPorcenctaje_breakpoints_ganados(double porcenctaje_breakpoints_ganados) { this.porcenctaje_breakpoints_ganados = porcenctaje_breakpoints_ganados; } @Override public String toString() { return "Datos{" + "nombre='" + nombre + '\'' + ", dobles=" + dobles + ", ganadores=" + ganadores + ", porcentaje_primeros=" + porcentaje_primeros + ", errores_no_forzados=" + errores_no_forzados + ", porcenctaje_breakpoints_ganados=" + porcenctaje_breakpoints_ganados + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Datos datos = (Datos) o; if (getDobles() != datos.getDobles()) return false; if (getGanadores() != datos.getGanadores()) return false; if (Double.compare(datos.getPorcentaje_primeros(), getPorcentaje_primeros()) != 0) return false; if (getErrores_no_forzados() != datos.getErrores_no_forzados()) return false; if (Double.compare(datos.getPorcenctaje_breakpoints_ganados(), getPorcenctaje_breakpoints_ganados()) != 0) return false; return getNombre().equals(datos.getNombre()); } @Override public int hashCode() { int result; long temp; result = getNombre().hashCode(); result = 31 * result + getDobles(); result = 31 * result + getGanadores(); temp = Double.doubleToLongBits(getPorcentaje_primeros()); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + getErrores_no_forzados(); temp = Double.doubleToLongBits(getPorcenctaje_breakpoints_ganados()); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } } @RunWith(AndroidJUnit4.class) @LargeTest public class ApplicationTest { private static long PAUSE = 1000; public static void pause(long millis) { try { Thread.sleep(millis); } catch (Exception ex) { } } @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class); @Rule public ActivityTestRule<PreferencesActivity> mPrefsRule = new ActivityTestRule(PreferencesActivity.class); private UiDevice mDevice; private String name; private String numero_sets = "3"; private String numero_juegos_set = "4"; private boolean punto_oro = true; @Before public void setUp() throws Exception { Instrumentation ins = InstrumentationRegistry.getInstrumentation(); mDevice = UiDevice.getInstance(ins); name = mActivityRule.getActivity().getBaseContext().getResources().getString(R.string.app_name); } @Test public void test1() throws Exception { MainActivity ma = (MainActivity) mActivityRule.getActivity(); ArrayList<String> estadisticas = new ArrayList<String>(); Datos d1 = new Datos(); d1.setNombre("Antonio"); d1.setDobles(10); d1.setErrores_no_forzados(20); d1.setGanadores(5); d1.setPorcenctaje_breakpoints_ganados(20.5); d1.setPorcentaje_primeros(52.6); Datos d2 = new Datos(); d2.setNombre("Pedro"); d2.setDobles(5); d2.setErrores_no_forzados(10); d2.setGanadores(15); d2.setPorcenctaje_breakpoints_ganados(80.3); d2.setPorcentaje_primeros(70.6); GsonBuilder gb = new GsonBuilder(); Gson g = gb.create(); String est1 = g.toJson(d1, Datos.class); String est2 = g.toJson(d2, Datos.class); estadisticas.add(est1); estadisticas.add(est2); ma.setEstadisticas(estadisticas); ApplicationTest.pause(PAUSE); onView(withId(R.id.boton1)).perform(click()); ApplicationTest.pause(PAUSE); File f = mActivityRule.getActivity().getExternalFilesDir(null); String file = f.getAbsolutePath() + "/" + MainActivity.fileName; try { BufferedReader br = new BufferedReader(new FileReader(file)); String cad; cad = br.readLine(); Datos aux = g.fromJson(new StringReader(cad), Datos.class); InfoLog.log(name, "Test 1: " + aux.equals(d1) + ", " + aux.toString()); cad = br.readLine(); aux = g.fromJson(new StringReader(cad), Datos.class); InfoLog.log(name, "Test 1: " + aux.equals(d2) + ", " + aux.toString()); br.close(); } catch (Exception ex) { } } @Test public void test2() throws Exception { onView(withId(R.id.action_settings)).perform(click()); ApplicationTest.pause(PAUSE); onView(withId(R.id.et_num_sets)).perform(clearText()); onView(withId(R.id.et_num_sets)).perform(typeText(numero_sets)); ApplicationTest.pause(PAUSE); onView(withId(R.id.et_juegos_set)).perform(clearText()); onView(withId(R.id.et_juegos_set)).perform(typeText(numero_juegos_set), closeSoftKeyboard()); ApplicationTest.pause(PAUSE); CheckBox cb = (CheckBox) mPrefsRule.getActivity().findViewById(R.id.cb_punto_oro); if (!(cb.isChecked() == punto_oro)) onView(withId(R.id.cb_punto_oro)).perform(click()); onView(withId(R.id.boton2)).perform(click()); InfoLog.log(name, "Test2: Preferencias almacenadas"); ApplicationTest.pause(100); mDevice.pressBack(); } @Test public void test3() throws Exception { onView(withId(R.id.action_settings)).perform(click()); ApplicationTest.pause(PAUSE); EditText t1 = (EditText) mPrefsRule.getActivity().findViewById(R.id.et_num_sets); EditText t2 = (EditText) mPrefsRule.getActivity().findViewById(R.id.et_juegos_set); CheckBox cb = (CheckBox) mPrefsRule.getActivity().findViewById(R.id.cb_punto_oro); InfoLog.log(name, "Test3: " + t1.getText().toString() + ", " + t2.getText().toString() + ", " + cb.isChecked()); ApplicationTest.pause(100); mDevice.pressHome(); } }
true
baf9203afa9449c1ec304db84628e111e7400378
Java
poojaprakas/assignment
/UsnPrinter.java
UTF-8
349
2.21875
2
[]
no_license
class UsnPrinter{ public static void main(String args[]){ byte usn; usn = 30; System.out.println(" "); System.out.println(" my roll number in class is " +usn ); usn = 36; System.out.println(" "); System.out.println(" according to vtu my usn is 1cg16ee036"+usn+" is my usn"); } }
true
ee444458b832971c86e6cfc963b4b1c2c64f2869
Java
CDE20IJ012-Ruksar/Test
/loan/src/main/java/com/cognizant/controller/LoanController.java
UTF-8
663
2.125
2
[]
no_license
package com.cognizant.controller; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.cognizant.model.Loan; @RestController public class LoanController { ApplicationContext context=new ClassPathXmlApplicationContext("loan.xml"); Loan loan=(Loan) context.getBean("loan",Loan.class); @GetMapping("loan/{number}") public Loan getAccount(@PathVariable String number) { return loan; } }
true
3d18d25a8a2d4c847849aea2946a2255b0e038ef
Java
zzl0815/greatness
/src/main/java/com/zzl/service/TitleService.java
UTF-8
333
1.851563
2
[]
no_license
package com.zzl.service; import java.util.List; import org.springframework.data.domain.Pageable; import com.zzl.bean.Title; public interface TitleService { String saveTitle(Title title); List<Title> queryTile(Pageable pageable); Title findTitleById(Long id); Title updateReadPersonById(Title title,Long id ); }
true
04595d2df316829d3379a10918fb1bfb9aca9dee
Java
thenoen/nikeloader
/src/test/java/sk/thenoen/nikeloader/NikeLoaderApplicationTests.java
UTF-8
925
2.234375
2
[]
no_license
package sk.thenoen.nikeloader; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import sk.thenoen.nikeloader.domain.model.Race; import sk.thenoen.nikeloader.domain.repository.RaceRepository; import sk.thenoen.nikeloader.service.RaceLoadingService; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class NikeLoaderApplicationTests { @Autowired private RaceRepository raceRepository; @Test public void contextLoads() { Race race = new Race(); String name = "New_race"; race.setName(name); raceRepository.save(race); List<Race> races = raceRepository.findAll(); Assert.assertEquals(1, races.size()); Assert.assertEquals(name, races.get(0).getName()); } }
true
d2a1a69165e8974dc3fca54ae1b3ab032019d9ad
Java
atomarea/FlowX
/src/main/java/net/atomarea/flowx/ui/ShareWithActivity.java
UTF-8
17,138
1.851563
2
[]
no_license
package net.atomarea.flowx.ui; import android.app.PendingIntent; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.Toast; import net.atomarea.flowx.Config; import net.atomarea.flowx.R; import net.atomarea.flowx.entities.Account; import net.atomarea.flowx.entities.Conversation; import net.atomarea.flowx.entities.Message; import net.atomarea.flowx.persistance.FileBackend; import net.atomarea.flowx.services.XmppConnectionService; import net.atomarea.flowx.ui.adapter.ConversationAdapter; import net.atomarea.flowx.xmpp.XmppConnection; import net.atomarea.flowx.xmpp.jid.InvalidJidException; import net.atomarea.flowx.xmpp.jid.Jid; import java.net.URLConnection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.String.format; public class ShareWithActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate { private boolean mReturnToPrevious = false; private static final String STATE_SHARING_IS_RUNNING = "state_sharing_is_running"; static boolean ContactChosen = false; static boolean IntentReceived = false; boolean SharingIsRunning = false; @Override public void onConversationUpdate() { refreshUi(); } private class Share { public List<Uri> uris = new ArrayList<>(); public boolean image; public boolean video; public String account; public String contact; public String text; public String uuid; public boolean multiple = false; } private Share share; private static final int REQUEST_START_NEW_CONVERSATION = 0x0501; private ListView mListView; private ConversationAdapter mAdapter; private List<Conversation> mConversations = new ArrayList<>(); private Toast mToast; private AtomicInteger attachmentCounter = new AtomicInteger(0); private UiCallback<Message> attachFileCallback = new UiCallback<Message>() { @Override public void userInputRequried(PendingIntent pi, Message object) { // TODO Auto-generated method stub } @Override public void success(final Message message) { xmppConnectionService.sendMessage(message); runOnUiThread(new Runnable() { @Override public void run() { if (attachmentCounter.decrementAndGet() <= 0) { int resId; if (share.image && share.multiple) { resId = R.string.shared_images_with_x; } else if (share.image) { resId = R.string.shared_image_with_x; } else if (share.video) { resId = R.string.shared_video_with_x; } else { resId = R.string.shared_file_with_x; } replaceToast(getString(resId, message.getConversation().getName())); if (mReturnToPrevious) { finish(); } else { switchToConversation(message.getConversation()); } } } }); } @Override public void error(final int errorCode, Message object) { runOnUiThread(new Runnable() { @Override public void run() { replaceToast(getString(errorCode)); if (attachmentCounter.decrementAndGet() <= 0) { finish(); } } }); } }; protected void hideToast() { if (mToast != null) { mToast.cancel(); } } protected void replaceToast(String msg) { hideToast(); mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG); mToast.show(); } protected void onActivityResult(int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_START_NEW_CONVERSATION && resultCode == RESULT_OK) { share.contact = data.getStringExtra("contact"); share.account = data.getStringExtra(EXTRA_ACCOUNT); } if (xmppConnectionServiceBound && share != null && share.contact != null && share.account != null) { share(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getActionBar() != null) { getActionBar().setDisplayHomeAsUpEnabled(false); getActionBar().setHomeButtonEnabled(false); } setContentView(R.layout.share_with); setTitle(getString(R.string.title_activity_sharewith)); mListView = (ListView) findViewById(R.id.choose_conversation_list); mAdapter = new ConversationAdapter(this, this.mConversations); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { share(mConversations.get(position)); } }); if (savedInstanceState != null) { SharingIsRunning = savedInstanceState.getBoolean(STATE_SHARING_IS_RUNNING, false); } if (!SharingIsRunning) { Log.d(Config.LOGTAG, "ShareWithActivity onCreate: state restored"); this.share = new Share(); } else { Log.d(Config.LOGTAG, "ShareWithActivity onCreate: shring running, finish()"); this.finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.share_with, menu); return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_add: final Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class); startActivityForResult(intent, REQUEST_START_NEW_CONVERSATION); return true; } return super.onOptionsItemSelected(item); } @Override public void onStart() { super.onStart(); Intent intent = getIntent(); if (intent == null) { return; } else { IntentReceived = true; } Log.d(Config.LOGTAG, "ShareWithActivity onStart() getIntent " + intent.toString()); this.mReturnToPrevious = getPreferences().getBoolean("return_to_previous", false); final String type = intent.getType(); final String action = intent.getAction(); Log.d(Config.LOGTAG, "action: " + action + ", type:" + type); share.uuid = intent.getStringExtra("uuid"); if (Intent.ACTION_SEND.equals(action)) { final String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); final String text = intent.getStringExtra(Intent.EXTRA_TEXT); final Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); Log.d(Config.LOGTAG, "ShareWithActivity onStart() Uri: " + uri); if (type != null && uri != null && (text == null || !type.equals("text/plain"))) { this.share.uris.clear(); this.share.uris.add(uri); this.share.image = type.startsWith("image/") || isImage(uri); this.share.video = type.startsWith("video/") || isVideo(uri); } else { if (subject != null) { this.share.text = format("[%s]%n%s", subject, text); } else { this.share.text = text; } } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) { this.share.image = type != null && type.startsWith("image/"); if (!this.share.image) { return; } this.share.uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); } if (xmppConnectionServiceBound) { if (share.uuid != null) { share(); } else { xmppConnectionService.populateWithOrderedConversations(mConversations, this.share.uris.size() == 0); } } } @Override public void onSaveInstanceState(final Bundle savedInstanceState) { Log.d(Config.LOGTAG, "ShareWithActivity onSaveInstanceState: IntentReceived: " + IntentReceived + " ContactChosen: " + ContactChosen); if (IntentReceived && ContactChosen) { Log.d(Config.LOGTAG, "ShareWithActivity onSaveInstanceState: state saved"); savedInstanceState.putBoolean(STATE_SHARING_IS_RUNNING, true); } else { Log.d(Config.LOGTAG, "ShareWithActivity onSaveInstanceState: sharing is running, do nothing at this point"); } super.onSaveInstanceState(savedInstanceState); } protected boolean isImage(Uri uri) { try { String guess = URLConnection.guessContentTypeFromName(uri.toString()); return (guess != null && guess.startsWith("image/")); } catch (final StringIndexOutOfBoundsException ignored) { return false; } } protected boolean isVideo(Uri uri) { try { String guess = URLConnection.guessContentTypeFromName(uri.toString()); return (guess != null && guess.startsWith("video/")); } catch (final StringIndexOutOfBoundsException ignored) { return false; } } @Override void onBackendConnected() { if (xmppConnectionServiceBound && share != null && ((share.contact != null && share.account != null) || share.uuid != null)) { share(); return; } refreshUiReal(); } private void share() { final Conversation conversation; if (share.uuid != null) { conversation = xmppConnectionService.findConversationByUuid(share.uuid); if (conversation == null) { return; } } else { Account account; try { account = xmppConnectionService.findAccountByJid(Jid.fromString(share.account)); } catch (final InvalidJidException e) { account = null; } if (account == null) { return; } try { conversation = xmppConnectionService .findOrCreateConversation(account, Jid.fromString(share.contact), false); } catch (final InvalidJidException e) { return; } } ContactChosen = true; share(conversation); } private void share(final Conversation conversation) { final Account account = conversation.getAccount(); final XmppConnection connection = account.getXmppConnection(); final long max = connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize(); mListView.setEnabled(false); if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP && !hasPgp()) { if (share.uuid == null) { showInstallPgpDialog(); } else { Toast.makeText(this, R.string.openkeychain_not_installed, Toast.LENGTH_SHORT).show(); finish(); } return; } if (share.uris.size() != 0) { OnPresenceSelected callback = new OnPresenceSelected() { @Override public void onPresenceSelected() { attachmentCounter.set(share.uris.size()); if (share.image) { Log.d(Config.LOGTAG, "ShareWithActivity share() image " + share.uris.size() + " uri(s) " + share.uris.toString()); share.multiple = share.uris.size() > 1; replaceToast(getString(share.multiple ? R.string.preparing_images : R.string.preparing_image)); for (Iterator<Uri> i = share.uris.iterator(); i.hasNext(); i.remove()) { ShareWithActivity.this.xmppConnectionService .attachImageToConversation(conversation, i.next(), attachFileCallback); } } else if (share.video) { Log.d(Config.LOGTAG, "ShareWithActivity share() video " + share.uris.size() + " uri(s) " + share.uris.toString()); replaceToast(getString(R.string.preparing_video)); ShareWithActivity.this.xmppConnectionService .attachVideoToConversation(conversation, share.uris.get(0), attachFileCallback); } else { Log.d(Config.LOGTAG, "ShareWithActivity share() file " + share.uris.size() + " uri(s) " + share.uris.toString()); replaceToast(getString(R.string.preparing_file)); ShareWithActivity.this.xmppConnectionService .attachFileToConversation(conversation, share.uris.get(0), attachFileCallback); } } }; if (account.httpUploadAvailable() && ((share.image && !neverCompressPictures()) || share.video || conversation.getMode() == Conversation.MODE_MULTI || FileBackend.allFilesUnderSize(this, share.uris, max)) && conversation.getNextEncryption() != Message.ENCRYPTION_OTR) { callback.onPresenceSelected(); } else { selectPresence(conversation, callback); } } else { if (mReturnToPrevious && this.share.text != null && !this.share.text.isEmpty()) { final OnPresenceSelected callback = new OnPresenceSelected() { @Override public void onPresenceSelected() { Message message = new Message(conversation, share.text, conversation.getNextEncryption()); if (conversation.getNextEncryption() == Message.ENCRYPTION_OTR) { message.setCounterpart(conversation.getNextCounterpart()); } xmppConnectionService.sendMessage(message); replaceToast(getString(R.string.shared_text_with_x, conversation.getName())); finish(); } }; if (conversation.getNextEncryption() == Message.ENCRYPTION_OTR) { selectPresence(conversation, callback); } else { callback.onPresenceSelected(); } } else { final OnPresenceSelected callback = new OnPresenceSelected() { @Override public void onPresenceSelected() { Message message = new Message(conversation, share.text, conversation.getNextEncryption()); if (conversation.getNextEncryption() == Message.ENCRYPTION_OTR) { message.setCounterpart(conversation.getNextCounterpart()); } xmppConnectionService.sendMessage(message); replaceToast(getString(R.string.shared_text_with_x, conversation.getName())); switchToConversation(message.getConversation()); } }; if (conversation.getNextEncryption() == Message.ENCRYPTION_OTR) { selectPresence(conversation, callback); } else { callback.onPresenceSelected(); } } } } public void refreshUiReal() { xmppConnectionService.populateWithOrderedConversations(mConversations, this.share != null && this.share.uris.size() == 0); mAdapter.notifyDataSetChanged(); } @Override public void onBackPressed() { if (attachmentCounter.get() >= 1) { replaceToast(getString(R.string.sharing_files_please_wait)); } else { super.onBackPressed(); } } }
true
4446fda5b2308381372225c714db887e7617143a
Java
sayederfanarefin/lagom-init
/hello-impl/src/main/java/info/sayederfanarefin/hello/hello/impl/KafkaConsumer.java
UTF-8
3,787
2.234375
2
[ "Apache-2.0" ]
permissive
package info.sayederfanarefin.hello.hello.impl; import akka.Done; import akka.NotUsed; import akka.actor.ActorSystem; import akka.http.javadsl.Http; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.ws.Message; import akka.http.javadsl.model.ws.TextMessage; import akka.http.javadsl.model.ws.WebSocketRequest; import akka.http.javadsl.model.ws.WebSocketUpgradeResponse; import akka.japi.Pair; import akka.stream.ActorMaterializer; import akka.stream.Materializer; import akka.stream.javadsl.Flow; import akka.stream.javadsl.Keep; import akka.stream.javadsl.Source; import akka.stream.javadsl.Sink; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Singleton; import info.sayederfanarefin.hello.hello.api.ExternalService; import javax.inject.Inject; import java.util.Arrays; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; @Singleton public class KafkaConsumer { String url= "wss://api-pub.bitfinex.com/ws/2" ; String src = "{ \"event\": \"subscribe\", \"channel\": \"book\", \"symbol\": \"tBTCUSD\", \"prec\": \"P0\", \"freq\": \"F0\" }"; TextMessage textMessage = TextMessage.create(src); public KafkaConsumer() { System.out.println(" ********* it works ***********"); getBitfinex(); } private void getBitfinex(){ Sink<Message, CompletionStage<Done>> printSink = Sink.foreach((message) -> System.out.println("****************************Got message: " + message.asTextMessage().getStrictText()) ); ActorSystem system = ActorSystem.create(); Materializer materializer = ActorMaterializer.create(system); Http http = Http.get(system); // emit "one" and then "two" and then keep the source from completing final Source<Message, CompletableFuture<Optional<Message>>> source = Source.from(Arrays.<Message>asList(textMessage)) .concatMat(Source.maybe(), Keep.right()); final Flow<Message, Message, CompletableFuture<Optional<Message>>> flow = Flow.fromSinkAndSourceMat( printSink, source, Keep.right()); final Pair<CompletionStage<WebSocketUpgradeResponse>, CompletableFuture<Optional<Message>>> pair = http.singleWebSocketRequest( WebSocketRequest.create(url), flow, materializer); CompletionStage<WebSocketUpgradeResponse> upgradeCompletion = pair.first(); CompletableFuture<Optional<Message>> closed = pair.second(); CompletionStage<Done> connected = upgradeCompletion.thenApply(upgrade-> { System.out.println("************* response *************** " + upgrade.response().status()); // just like a regular http request we can access response status which is available via upgrade.response.status // status code 101 (Switching Protocols) indicates that server support WebSockets if (upgrade.response().status().equals(StatusCodes.SWITCHING_PROTOCOLS)) { return Done.getInstance(); } else { throw new RuntimeException(("Connection failed: " + upgrade.response().status())); } }); connected.thenAccept(done -> connected()); closed.thenAccept(done -> System.out.println("************* Connection closed")); // at some later time we want to disconnect // pair.second().complete(Optional.empty()); } private void connected(){ System.out.println("************* Connected"); } }
true
16556cdd02ca2e7b2e044859088996dc28ff5a04
Java
gustavobte/struts
/src/com/indra/report/PdfGerator.java
UTF-8
1,031
2.0625
2
[]
no_license
package com.indra.report; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class PdfGerator extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Document document = new Document(); try { response.setContentType("application/pdf"); PdfWriter.getInstance(document, response.getOutputStream()); document.open(); document.add(new Paragraph("Hello Kiran")); document.add(new Paragraph(new Date().toString())); } catch (Exception e) { e.printStackTrace(); } document.close(); return null; } }
true
e4f5aa89694355f3d1ac9c8ab1cd5d175f967e5d
Java
macrobber/CattleTrak
/app/src/main/java/com/example/macro/cattletrak/DeactivateCattle.java
UTF-8
4,774
2.15625
2
[]
no_license
package com.example.macro.cattletrak; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONArray; public class DeactivateCattle extends ActionBarActivity { private String uid; private String Tag; private EditText eTag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_deactivate_cattle); // ************ Section for Back Button Here ******************* android.support.v7.app.ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); // ************ Section for Back Button Here ******************* Bundle extras = getIntent().getExtras(); if(extras == null) { return; } this.uid = extras.getString("uid"); this.eTag = (EditText) findViewById(R.id.deactivateCow); // this.Tag = this.eTag.getText().toString(); Button btnDeactivate = (Button) findViewById(R.id.btnDeactivate); btnDeactivate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Tag = eTag.getText().toString(); new AlertDialog.Builder(DeactivateCattle.this) .setTitle("Deactivate Entry") .setMessage("Are you sure you want to deactivate this entry?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // continue with delete // these three lines moved if(Tag != null) { new DeactivateCow().execute(new CattleApiConnector()); } //theese three lines moved } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { eTag.setText(""); // do nothing } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); // these three lines moved /* if(Tag != null) { new DeactivateCow().execute(new CattleApiConnector()); } */ //theese three lines moved // below is fine } }); } private class DeactivateCow extends AsyncTask<CattleApiConnector, Long, JSONArray> { @Override protected JSONArray doInBackground(CattleApiConnector... params) { // This is executed in the background thread return params[0].DelCattle(Tag, uid); } @Override protected void onPostExecute(JSONArray jArray) { // once do in background is done - it sends the result to the main thread...here // JSONObject cow = jArray.getJSONObject(0); try { // JSONObject cow = jArray.getJSONObject(0); eTag.setText(""); Toast.makeText(getApplicationContext(), "Record Deactivated", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } } @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_deactivate_cattle, 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(); // ***** Section for back button ****** if(id==android.R.id.home) { onBackPressed(); return true; } // ***** Section for back button ****** //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
969a880ce67872ecda5c9885661d38cef409222b
Java
luotianwen/opManage
/src/com/op/entity/lines/ActiveLines.java
UTF-8
2,367
2.328125
2
[]
no_license
package com.op.entity.lines; import java.util.Date; /** * 活动总体线路(activeLines)实体类 * @author 世峰户外商城 * @version Revision: 1.00 * Date: 2015-12-10 10:51:36 */ public class ActiveLines { //总体线路ID private String al_id; //总体线路地图标注(坐标集合) private String al_coordinates; //总体线路描述 private String al_description; //总体线路创建时间 private Date al_create_time; //总体线路创建用户 private String al_create_user; //总体线路修改人 private String al_update_user; //总体线路修改时间 private Date al_update_time; //是否已经删除(0:默认值;1:是) private int al_is_delete; /** *总体线路ID */ public String getAl_id() { return al_id; } public void setAl_id(String al_id) { this.al_id = al_id; } /** *总体线路地图标注(坐标集合) */ public String getAl_coordinates() { return al_coordinates; } public void setAl_coordinates(String al_coordinates) { this.al_coordinates = al_coordinates; } /** *总体线路描述 */ public String getAl_description() { return al_description; } public void setAl_description(String al_description) { this.al_description = al_description; } /** *总体线路创建时间 */ public Date getAl_create_time() { return al_create_time; } public void setAl_create_time(Date al_create_time) { this.al_create_time = al_create_time; } /** *总体线路创建用户 */ public String getAl_create_user() { return al_create_user; } public void setAl_create_user(String al_create_user) { this.al_create_user = al_create_user; } /** *总体线路修改人 */ public String getAl_update_user() { return al_update_user; } public void setAl_update_user(String al_update_user) { this.al_update_user = al_update_user; } /** *总体线路修改时间 */ public Date getAl_update_time() { return al_update_time; } public void setAl_update_time(Date al_update_time) { this.al_update_time = al_update_time; } /** *是否已经删除(0:默认值;1:是) */ public int getAl_is_delete() { return al_is_delete; } public void setAl_is_delete(int al_is_delete) { this.al_is_delete = al_is_delete; } }
true
be00123b4a43ad7b39b08a0d7be56536fa5e77aa
Java
notbadwt/WebApplication
/server/src/main/java/com/application/weixin/service/TokenService.java
UTF-8
2,322
2.4375
2
[]
no_license
package com.application.weixin.service; import com.application.weixin.exception.JWeixinException; import com.application.weixin.model.AccessToken; import java.util.function.Supplier; public interface TokenService { /** * 获得微信接口调用凭证 * * @param appId 公众号appid * @param secret 公众号secret * @return token的实例对象 * @throws JWeixinException 微信访问的异常信息 */ AccessToken fetchAccessToken( String appId, String secret) throws JWeixinException; /** * 获取网页授权取code的url * * @param appId 公众号appid * @param redirectUrl 回调接口地址 * @param scope 请求类型 base userinfo * @param state 状态值,没有请填写空字符串 * @return 微信网页授权请求地址,请在微信浏览器中访问 * @throws JWeixinException 微信访问的异常信息 */ String fetchPageAccessTokenUrl(String appId, String redirectUrl, String scope, String state) throws JWeixinException; /** * 通过网页授权获得的code获取网页授权的token * * @param appId 公众号appid * @param secret 公众号secret * @param code 网页授权取到的code * @return token的实例 * @throws JWeixinException 微信模块的异常信息 */ AccessToken fetchPageAccessToken(String appId, String secret, String code) throws JWeixinException; /** * 通过用户识别器来获取缓存在服务器中的token * * @param keySupplier 用户识别器,有调用者提供 * @param appId 公众号appid * @return token实例 * @throws JWeixinException 微信模块的异常信息 */ AccessToken fetchPageAccessToken(Supplier<String> keySupplier, String appId) throws JWeixinException; /** * 通过制定的refreshToken值来刷新当前token * * @param appId 公众号appid * @param refreshToken 刷新所需要的refreshToken值,正常情况下是从用户识别器中返回的token中获得 * @return 刷新后的token实例 * @throws JWeixinException 微信模块的异常信息 */ AccessToken refreshPageAccessToken(String appId, String refreshToken) throws JWeixinException; }
true
353f43fa1cfea000ca90d225f505ba6da5c2e7e7
Java
snocorp/floweb2
/webapp/src/main/java/net/sf/flophase/floweb/xaction/TransactionQueryServlet.java
UTF-8
1,358
2.3125
2
[]
no_license
package net.sf.flophase.floweb.xaction; import java.io.IOException; import java.util.List; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.flophase.floweb.common.Response; import com.google.gson.Gson; import com.google.inject.Singleton; /** * This servlet returns a Response containing a list of transactions formatted as JSON. */ @Singleton public class TransactionQueryServlet extends HttpServlet { /** * The month parameter. */ private static final String PARM_MONTH = "month"; /** * Serialization identifier */ private static final long serialVersionUID = 9209614462585301347L; /** * The transaction service to execute the logic. */ @Inject TransactionService xactionService; /** * The JSON formatter. */ @Inject Gson gson; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String month = req.getParameter(PARM_MONTH); Response<List<FinancialTransaction>> response = xactionService.getTransactions(month); String output = gson.toJson(response); resp.setContentType("application/json"); resp.setContentLength(output.length()); resp.getWriter().write(output); } }
true
2e444748e39c85627777c0317fb6586183a2879b
Java
naveenthontepu/BaseProject
/app/src/main/java/thontepu/naveen/baseproject/BaseProject.java
UTF-8
2,720
2.53125
3
[]
no_license
package thontepu.naveen.baseproject; import android.app.Activity; import android.app.Application; import android.os.Bundle; import thontepu.naveen.baseproject.Dagger2.BaseProjectComponent; import thontepu.naveen.baseproject.Dagger2.DaggerBaseProjectComponent; import thontepu.naveen.baseproject.Dagger2.Modules.BaseProjectModule; import thontepu.naveen.baseproject.Utilities.SessionSharedPrefs; import thontepu.naveen.baseproject.Utilities.Utilities; /** * Created by mac on 12/22/16 */ public class BaseProject extends Application { private BaseProjectComponent baseProjectComponent; /** * The Shared preference is being initialize in the application class to make it as a Singleton Pattern. * <p> * Registering Activity Lifecycle callbacks so as to know when an activity created and destroyed. * The present code will let you know when the application is in foreground and background so that you * can trigger some actions when the user moves of the application. */ @Override public void onCreate() { super.onCreate(); baseProjectComponent = DaggerBaseProjectComponent.builder().baseProjectModule(new BaseProjectModule(this)).build(); SessionSharedPrefs.setInstance(this); Utilities.printLog("onCreate"); registerActivityLifecycleCallbacks(new ActivityLifeCycle()); SessionSharedPrefs.getInstance().setTimesOpened(SessionSharedPrefs.getInstance().getTimesOpened() + 1); } public String getString() { return "trial dagger component"; } public BaseProjectComponent getBaseProjectComponent() { return baseProjectComponent; } private class ActivityLifeCycle implements ActivityLifecycleCallbacks { String activityName; @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { activityName = activity.getComponentName().getClassName(); } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { if (activityName.equalsIgnoreCase(activity.getComponentName().getClassName())) { // TODO: 12/22/16 trigger actions when the user closes your application } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } } }
true
67da10313b9000bb9cc772b63df0a376c16e63a4
Java
anixumoh/APIVerifiable
/src/main/java/Base/TestBase.java
UTF-8
534
2.125
2
[]
no_license
package Base; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import static utility.Utility.fetchvalue; public class TestBase { public String baseurl; @BeforeClass(alwaysRun = true) public void SetUp() { switch (fetchvalue("Environment")) { case "Production": baseurl = fetchvalue("baseurlProd"); break; case "Staging": baseurl = fetchvalue("baseurlStaging"); break; } } }
true
05564376acd923e83fd86c55e48ad4caaadd7956
Java
enymc/springbootdemo
/src/main/java/com/spootboot/demo/Bean/MyConfigBean.java
UTF-8
751
2.40625
2
[]
no_license
package com.spootboot.demo.Bean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /* 获取自定义配置文件中的常量 */ @Configuration @ConfigurationProperties(prefix = "") @PropertySource("classpath:myConfig.properties") public class MyConfigBean { private String name; private int number; private int port; public void setName(String name) { this.name = name; } public void setNumber(int number) { this.number = number; } public String getName() { return name; } public int getNumber() { return number; } }
true
3ba7b45fcd42a224e9d1b29723197a758b64ee52
Java
LehmannF/TaskbarProject
/brainfuck/command/Out.java
UTF-8
454
2.765625
3
[]
no_license
package brainfuck.command; import brainfuck.ComputationalModel; public class Out implements Command { @Override public void execute() { ComputationalModel cm = new ComputationalModel(); System.out.println((char) cm.getCurrentCaseValue()); } /** * Print the instruction in short syntax for the rewrite instruction * */ @Override public void printShort() { System.out.print("."); } }
true
8c09eae100bddfce598aa503d729b5a1135eb087
Java
kimsangyoung1114/uiTest
/uit/src/dao/impl/UserInfoDAOImpl.java
UTF-8
876
2.3125
2
[]
no_license
package dao.impl; import org.apache.ibatis.session.SqlSession; import dao.UserInfoDAO; import servlet.MybatisServlet; import vo.UserInfoVO; public class UserInfoDAOImpl implements UserInfoDAO{ @Override public int insertUserInfo(UserInfoVO ui) { try(SqlSession ss = MybatisServlet.getSession()){ int insert =ss.insert("UserInfo.insertUserInfo", ui); ss.commit(); return insert; } } @Override public UserInfoVO selectUserInfoForLogin(UserInfoVO ui) { try(SqlSession ss = MybatisServlet.getSession()){ return ss.selectOne("UserInfo.selectUserInfoForLogin",ui); } } public static void main(String[] args) { UserInfoDAO udao = new UserInfoDAOImpl(); UserInfoVO uv = new UserInfoVO(); uv.setUiId("test"); uv.setUiPassword("test"); System.out.println(udao.selectUserInfoForLogin(uv)); } }
true
913e576834478009ec527d2b74071c4ec087b233
Java
hb06ars/Sistema
/src/main/java/brandaoti/sistema/model/Categoria.java
UTF-8
1,123
2.25
2
[]
no_license
package brandaoti.sistema.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Categoria") public class Categoria implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Integer categoriaID; @Column(name = "codigo", length=100) private String codigo; @Column(name = "descricao", length=100) private String descricao; @Column(name = "ativo") private Boolean ativo = true; public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Boolean getAtivo() { return ativo; } public void setAtivo(Boolean ativo) { this.ativo = ativo; } public Integer getCategoriaID() { return categoriaID; } public void setCategoriaID(Integer categoriaID) { this.categoriaID = categoriaID; } }
true
a14afdced13cd1aabfc6ac2b05f0c8c28c0d0829
Java
ggodet-bar/TeamAvatars
/src/business/process/manageteammembers/Parser.java
UTF-8
335
1.773438
2
[]
no_license
package business.process.manageteammembers; import java.net.URI; import java.util.EnumMap; import java.util.List; import business.dataref.TeamData; public abstract class Parser { public static Parser instance ; public abstract void setURI(URI uri) ; public abstract List<EnumMap<TeamData, Object>> getTeamStructure() ; }
true
3774caafdb90d85d6d12d55d15f9d881020c54a5
Java
tazioicaro/TCC
/BB/src/main/java/com/bb/controller/control/cadastros/CadastroDepartamentoBean.java
UTF-8
6,943
2.21875
2
[]
no_license
package com.bb.controller.control.cadastros; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.event.SelectEvent; import org.primefaces.event.TransferEvent; import org.primefaces.event.UnselectEvent; import com.bb.controller.control.repository.Departamentos; import com.bb.controller.services.NegocioException; import com.bb.controller.util.jsf.FacesUtil; import com.bb.models.Departamento; @Named @ViewScoped public class CadastroDepartamentoBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private Departamentos repositorioDepartamentos; private Departamento departamentoPai = new Departamento(); private Departamento departamentoPosSave; private List<String> gerentesSelecionados; private Departamento departamentoNovoGerente; List<Departamento> listGerentes = new ArrayList<>(); private boolean exibirPikeList; private boolean exibirNovoGerente; private boolean edicao= false; private List<String> gerentes = new ArrayList<String>(); private List<String> gerentesConvert = new ArrayList<String>(); public void inicializar() { if (this.departamentoPai == null) { obterGerentes(); exibirPikeList = false; exibirNovoGerente = false; } else if (this.departamentoPai.getCodigo() != null) { edicaoGerentes(); exibirPikeList = true; } } public CadastroDepartamentoBean() { limpar(); } List<String> obterGerentes() { return this.gerentes = repositorioDepartamentos.todosGerentesString(); } public void cadastrar() { try { this.departamentoPai = repositorioDepartamentos.guardar(this.departamentoPosSave); FacesUtil.addInforMessage("Departamento " + departamentoPosSave.getNome() + " cadastrado com sucesso"); limpar(); obterGerentes(); exibirPikeList = true; } catch (NegocioException ne) { FacesUtil.addErrorMessage(ne.getMessage()); } } public void cadastrarGerentes() { Departamento dep; try { if (!departamentoPai.getGerentes().isEmpty()) { for (Departamento dept : departamentoPai.getGerentes()){ repositorioDepartamentos.removerDepartamento(dept); } departamentoPai.getGerentes().clear(); for (String depo : gerentesConvert) { dep = new Departamento(); dep.setNome(depo); dep.setDepartamentoPai(departamentoPai); departamentoPai.getGerentes().add(dep); repositorioDepartamentos.guardar(dep); } FacesUtil.addInforMessage("Líder(es) vinculado(s) com sucesso"); limparCadastrarGerentes(); edicao = true; } if (!edicao) { for (String depo : gerentesConvert) { dep = new Departamento(); dep.setDepartamentoPai(departamentoPai); dep.setNome(depo); repositorioDepartamentos.guardar(dep); } FacesUtil.addInforMessage("Líder(es) cadastrado(s) com sucesso"); limparCadastrarGerentes(); } } catch (NegocioException ne) { FacesUtil.addErrorMessage(ne.getMessage()); } } // Possibilita salvar paenas um líder por demartamento public void cadastrarNovoGerente() { try { departamentoNovoGerente.setDepartamentoPai(departamentoPai); repositorioDepartamentos.guardar(departamentoNovoGerente); FacesUtil.addInforMessage("Líder " + departamentoNovoGerente.getNome() + " criado com sucesso " + "e vinculado ao Departamento " + departamentoPai.getNome() + " !"); limparCadastrarGerentes(); bloquearCadastroNovoGerente(); gerentesConvert = new ArrayList<>(); } catch (NegocioException ne) { FacesUtil.addErrorMessage(ne.getMessage()); } } public void edicaoGerentes() { obterGerentes(); for (Departamento dep : departamentoPai.getGerentes()) { gerentesConvert.add(dep.getNome()); } } public void limparCadastrarGerentes() { departamentoPai = new Departamento(); departamentoNovoGerente = new Departamento(); gerentesSelecionados = null; bloquearExibirPikeList(); limpar(); gerentesConvert = new ArrayList<>(); } public void limpar() { departamentoPosSave = new Departamento(); } public void liberarCadastroNovoGerente() { exibirNovoGerente = true; exibirPikeList = false; departamentoNovoGerente = new Departamento(); } public void bloquearCadastroNovoGerente() { exibirNovoGerente = false; } public void alterarExibirPikeList() { exibirPikeList = true; } public void bloquearExibirPikeList() { exibirPikeList = false; } public void onTransfer(TransferEvent event) { } public void onSelect(SelectEvent event) { } public void onUnselect(UnselectEvent event) { } public void onReorder() { } // G&S public Departamento getDepartamentoPai() { return departamentoPai; } public void setDepartamentoPai(Departamento departamentoPai) { this.departamentoPai = departamentoPai; } public List<String> getGerentes() { return gerentes; } public void setGerentes(List<String> gerentes) { this.gerentes = gerentes; } public boolean isExibirPikeList() { return exibirPikeList; } public void setExibirPikeList(boolean exibirPikeList) { this.exibirPikeList = exibirPikeList; } public Departamento getDepartamentoPosSave() { return departamentoPosSave; } public void setDepartamentoPosSave(Departamento departamentoPosSave) { this.departamentoPosSave = departamentoPosSave; } public List<String> getGerentesSelecionados() { return gerentesSelecionados; } public void setGerentesSelecionados(List<String> gerentesSelecionados) { this.gerentesSelecionados = gerentesSelecionados; } public List<String> getGerentesConvert() { return gerentesConvert; } public void setGerentesConvert(List<String> gerentesConvert) { this.gerentesConvert = gerentesConvert; } public boolean isExibirNovoGerente() { return exibirNovoGerente; } public void setExibirNovoGerente(boolean exibirNovoGerente) { this.exibirNovoGerente = exibirNovoGerente; } public Departamento getDepartamentoNovoGerente() { return departamentoNovoGerente; } public void setDepartamentoNovoGerente(Departamento departamentoNovoGerente) { this.departamentoNovoGerente = departamentoNovoGerente; } public boolean isEdicao() { return edicao; } public void setEdicao(boolean edicao) { this.edicao = edicao; } public List<Departamento> getListGerentes() { return listGerentes; } public void setListGerentes(List<Departamento> listGerentes) { this.listGerentes = listGerentes; } }
true
95c1fc8ee82d9bac991e936f24f53de7b92c1106
Java
HarryWu-CHN/MyWeChat
/app/src/main/java/com/example/mywechat/ui/contacts/ContactFragment.java
UTF-8
8,237
1.867188
2
[]
no_license
package com.example.mywechat.ui.contacts; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.mywechat.ui.NewFriend.FriendApplyActivity; import com.example.mywechat.App; import com.example.mywechat.R; import com.example.mywechat.model.FriendRecord; import com.example.mywechat.model.UserInfo; import com.example.mywechat.ui.Group.MyGroupsActivity; import com.example.mywechat.viewmodel.NewFriendViewModel; import com.example.mywechat.Util.FileUtil; import org.litepal.LitePal; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.LinkedList; import java.util.List; import dagger.hilt.android.AndroidEntryPoint; @AndroidEntryPoint public class ContactFragment extends Fragment { private String username; private Button friendApplyButton; private Button myGroupsButton; private LinkedList<Contact> contacts; private ContactAdapter adapter; private RecyclerView recyclerView; private NewFriendViewModel NfViewModel; public ContactFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment ContactsFragment. */ // TODO: Rename and change types and number of parameters public static ContactFragment newInstance() { return new ContactFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); username = ((App) requireActivity().getApplication()).getUsername(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { showActionBar(view); NfViewModel = new ViewModelProvider(this) .get(NewFriendViewModel.class); friendApplyButton = view.findViewById(R.id.friendApplyButton); friendApplyButton.setOnClickListener(v -> { Intent intent = new Intent(getActivity(), FriendApplyActivity.class); startActivity(intent); }); myGroupsButton = view.findViewById(R.id.myGroupButton); myGroupsButton.setOnClickListener(v -> { Intent intent = new Intent(getActivity(), MyGroupsActivity.class); startActivity(intent); }); // 设置LayoutManager及Adapter LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); recyclerView = view.findViewById(R.id.contacts_recyclerview); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL)); adapter = new ContactAdapter(); recyclerView.setAdapter(adapter); NfViewModel.contactGet(); NfViewModel.getContactsData().observe(getViewLifecycleOwner(), response -> { if (response == null) { return; } contacts = new LinkedList<>(); List<String> friendNames = response.getFriendNames(); List<String> friendNickNames = response.getFriendNickNames(); List<String> friendIcons = response.getFriendIcons(); for (int i = 0; i < friendNames.size(); i++) { String friendName = friendNames.get(i); String friendNickName = friendNickNames.get(i); String friendIcon = friendIcons.get(i); FriendRecord friendRecord = LitePal.where("friendName = ?", friendName).findFirst(FriendRecord.class); if (friendRecord == null || friendRecord.getIconPath() == null) { contacts.add(new Contact(friendName, friendNickName)); friendRecord = new FriendRecord(friendName, friendNickName); getIconAndSave(friendRecord, friendIcon, i); } else { Bitmap bitmap = BitmapFactory.decodeFile(friendRecord.getIconPath()); contacts.add(new Contact(friendName, friendNickName, bitmap)); } } adapter.setContacts(contacts); UserInfo userInfo = LitePal.where("username = ?", username).findFirst(UserInfo.class); userInfo.setFriendNames(friendNames); userInfo.save(); }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_contacts, container, false); } private void showActionBar(@NonNull View view) { Context context = view.getContext(); while (!(context instanceof Activity)) { context = ((ContextWrapper) context).getBaseContext(); } ((AppCompatActivity) context).getSupportActionBar().show(); } @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @SuppressLint("HandlerLeak") @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: Pair<Integer, Bitmap> updatePair = (Pair<Integer, Bitmap>) msg.obj; contacts.get(updatePair.first).setAvatarIcon(updatePair.second); adapter.setContacts(contacts); break; case 1: Log.d("InternetImageView", "NETWORK_ERROR"); break; case 2: Log.d("InternetImageView", "SERVER_ERROR"); break; default: break; } } }; public void getIconAndSave(final FriendRecord friendRecord, final String friendIcon, final int index) { //开启一个线程用于联网 new Thread(() -> { int arg1 = 0; String path = "http://8.140.133.34:7262/" + friendIcon; Bitmap bitmap = null; try { //通过HTTP请求下载图片 URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(10000); //获取返回码 int code = connection.getResponseCode(); if (code == 200) { InputStream inputStream = connection.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); inputStream.close(); } else { arg1 = 1; Log.d("HttpError", "下载图片失败"); } } catch (IOException e) { arg1 = 2; e.printStackTrace(); } if (bitmap == null) return; File file = FileUtil.SaveBitmap2Png(bitmap, requireContext()); Message msg = new Message(); msg.what = 0; msg.arg1 = arg1; msg.obj = new Pair<>(index, bitmap); handler.sendMessage(msg); friendRecord.setIconPath(file.getAbsolutePath()); friendRecord.save(); }).start(); } }
true
ccff5a15c606743997d03157e0c7455177c9463c
Java
audicarmo/one-bank-service-old-project
/src/main/java/br/com/bank/onlybank/utils/DataUtil.java
UTF-8
433
2.328125
2
[]
no_license
package br.com.bank.onlybank.utils; import org.springframework.stereotype.Component; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; @Component public class DataUtil { private static final String STANDARD_FORMAT = "MM/dd/yyyy HH:mm"; public String dateFormat(Date date) { Format formatter = new SimpleDateFormat(STANDARD_FORMAT); return formatter.format(date); } }
true
e8d54dd924371d66559c416fc6b7fbb277c0e116
Java
luoolu/XiaoSuMeiTu
/src/com/fzu/imageimocc/processing/ImageProcess.java
UTF-8
6,578
2.546875
3
[]
no_license
package com.fzu.imageimocc.processing; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; /** * * @author Administrator * */ public class ImageProcess { private Bitmap mBitmap; private float[] mColorMatrix = { (float) 0.393,(float) 0.768,(float) 0.189,0,0, (float) 0.349,(float) 0.686,(float) 0.168,0,0, (float) 0.272,(float) 0.534,(float) 0.131,0,0, 0,0,0,1,0}; public ImageProcess(Bitmap bitmap) { this.mBitmap = bitmap; } /** * 怀旧效果 * @return */ public Bitmap Method_Reminiscence() { Bitmap bmp = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888); android.graphics.ColorMatrix colorMatrix = new android.graphics.ColorMatrix(); colorMatrix.set(mColorMatrix); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); canvas.drawBitmap(mBitmap, 0, 0, paint); return bmp; } /** * 光晕效果 * @param bmp * @param x 光晕中心点在bmp中的x坐标 * @param y 光晕中心点在bmp中的y坐标 * @param r 光晕的半径 * @return */ public Bitmap Method_Fuzzy(int x, int y, float r) { long start = System.currentTimeMillis(); // 高斯矩阵 int[] gauss = new int[] { 1, 2, 1, 2, 4, 2, 1, 2, 1 }; int width = mBitmap.getWidth(); int height = mBitmap.getHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int delta = 18; // 值越小图片会越亮,越大则越暗 int idx = 0; int[] pixels = new int[width * height]; mBitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { idx = 0; int distance = (int) (Math.pow(k - x, 2) + Math.pow(i - y, 2)); // 不是中心区域的点做模糊处理 if (distance > r * r) { for (int m = -1; m <= 1; m++) { for (int n = -1; n <= 1; n++) { pixColor = pixels[(i + m) * width + k + n]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = newR + (int) (pixR * gauss[idx]); newG = newG + (int) (pixG * gauss[idx]); newB = newB + (int) (pixB * gauss[idx]); idx++; } } newR /= delta; newG /= delta; newB /= delta; newR = Math.min(255, Math.max(0, newR)); newG = Math.min(255, Math.max(0, newG)); newB = Math.min(255, Math.max(0, newB)); pixels[i * width + k] = Color.argb(255, newR, newG, newB); newR = 0; newG = 0; newB = 0; } } } bitmap.setPixels(pixels, 0, width, 0, 0, width, height); long end = System.currentTimeMillis(); System.out.println("used time="+(end - start)); return bitmap; } /** * 图片锐化(拉普拉斯变换) * @param bmp * @return */ public Bitmap Method_Sharpen() { long start = System.currentTimeMillis(); // 拉普拉斯矩阵 int[] laplacian = new int[] { -1, -1, -1, -1, 9, -1, -1, -1, -1 }; int width = mBitmap.getWidth(); int height = mBitmap.getHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int pixR = 0; int pixG = 0; int pixB = 0; int pixColor = 0; int newR = 0; int newG = 0; int newB = 0; int idx = 0; float alpha = 0.3F; int[] pixels = new int[width * height]; mBitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i = 1, length = height - 1; i < length; i++) { for (int k = 1, len = width - 1; k < len; k++) { idx = 0; for (int m = -1; m <= 1; m++) { for (int n = -1; n <= 1; n++) { pixColor = pixels[(i + n) * width + k + m]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = newR + (int) (pixR * laplacian[idx] * alpha); newG = newG + (int) (pixG * laplacian[idx] * alpha); newB = newB + (int) (pixB * laplacian[idx] * alpha); idx++; } } newR = Math.min(255, Math.max(0, newR)); newG = Math.min(255, Math.max(0, newG)); newB = Math.min(255, Math.max(0, newB)); pixels[i * width + k] = Color.argb(255, newR, newG, newB); newR = 0; newG = 0; newB = 0; } } bitmap.setPixels(pixels, 0, width, 0, 0, width, height); long end = System.currentTimeMillis(); System.out.println("used time="+(end - start)); return bitmap; } }
true
4e23cdc92b90d1fa850a6e87538a21cef2798a4c
Java
timiblossom/ShareMyVision
/src/com/smv/common/bean/EmailNameListDTO.java
UTF-8
1,439
2.53125
3
[]
no_license
package com.smv.common.bean; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EmailNameListDTO") public class EmailNameListDTO { @XmlElement(name = "entry", required = true) List<EmailNameEntryDTO> entries = new ArrayList<EmailNameEntryDTO>(); public List<EmailNameEntryDTO> getEntries() { return entries; } public void setEntries(List<EmailNameEntryDTO> entries) { this.entries = entries; } protected String entriesToString() { if ((entries != null) && (!entries.isEmpty()) && (entries.size() > 0)) { StringBuilder builder = new StringBuilder(); for (int index = 0; index < entries.size(); index++) { builder.append("entry["); builder.append(index); builder.append("]="); builder.append(entries.get(index)); builder.append(","); } return builder.toString(); } return null; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("EmailNameListDTO [entries="); builder.append(entriesToString()); builder.append("]"); return builder.toString(); } }
true
3fef7ce0d36141f5cba898e072cc00d8f3e42310
Java
zcc888/Java9Source
/jdk.scripting.nashorn/jdk/nashorn/internal/IntDeque.java
UTF-8
1,505
2.828125
3
[]
no_license
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package jdk.nashorn.internal; /** * Small helper class for fast int deques */ public class IntDeque { private int[] deque = new int[16]; private int nextFree = 0; /** * Push an int value * @param value value */ public void push(final int value) { if (nextFree == deque.length) { final int[] newDeque = new int[nextFree * 2]; System.arraycopy(deque, 0, newDeque, 0, nextFree); deque = newDeque; } deque[nextFree++] = value; } /** * Pop an int value * @return value */ public int pop() { return deque[--nextFree]; } /** * Peek * @return top value */ public int peek() { return deque[nextFree - 1]; } /** * Get the value of the top element and increment it. * @return top value */ public int getAndIncrement() { return deque[nextFree - 1]++; } /** * Decrement the value of the top element and return it. * @return decremented top value */ public int decrementAndGet() { return --deque[nextFree - 1]; } /** * Check if deque is empty * @return true if empty */ public boolean isEmpty() { return nextFree == 0; } }
true
df85ec378a826b20c153b5455dc4ee6cb7616694
Java
khajahussain1/SELENIUM2
/src/Interview_Quesions/SuperKeyword.java
UTF-8
924
3.5625
4
[]
no_license
package Interview_Quesions; class A1{ int id; String name; String color="White"; A1(int id, String name) { this.id=id; this.name=name; System.out.println("Welcome to parant class constractor"); } void message() { System.out.println("Welcome to Chennai"); } } class D1 extends A1{ float salary; D1(int id, String name, float salary) { super(id, name); this.salary=salary; //System.out.println("Welcome to sub calss constractor"); } @Override void message() { System.out.println(id+" "+name+" "+salary); //System.out.println("Welcome to Hyderabad"); } void display() { super.message(); } String color="black"; void printcolor() { System.out.println(color); System.out.println(super.color); } } public class SuperKeyword { public static void main(String[] args) { D1 d=new D1(111, "khaja", 2365f); d.printcolor(); d.display(); d.message(); } }
true
d058fdbbc9acc0a7cbce93cda11cd16ac1a05220
Java
Caroline-RG/Idiomas
/Idiomas/src/main/java/pe/edu/upc/service/IAlumnoService.java
UTF-8
223
2.015625
2
[]
no_license
package pe.edu.upc.service; import java.util.List; import pe.edu.upc.entity.Alumno; public interface IAlumnoService { public void insertar(Alumno alumno); public void eliminar(int id); public List<Alumno> listar(); }
true
8e5326e214f50ad1fb9503ee683101391ca62b86
Java
usmanali353/food_ordering
/app/src/main/java/usmanali/food_ordering/Menu.java
UTF-8
198
2.25
2
[]
no_license
package usmanali.food_ordering; public class Menu { String name; int picture; public Menu(String name, int picture) { this.name = name; this.picture = picture; } }
true
ae34f361abfa34e12c7fca0b512a0550647de74a
Java
Saiphani724/CodeOnDroid
/app/src/main/java/codeondroid/codeondroid/CustomLinknode.java
UTF-8
901
2.6875
3
[ "Apache-2.0" ]
permissive
package codeondroid.codeondroid; public class CustomLinknode { String content; int cursor; CustomLinknode prev; CustomLinknode next; public CustomLinknode(String cont,int curs, CustomLinknode pre) { content=cont; cursor=curs; prev=pre; next=null; } public CustomLinknode(CustomLinknode source) { content=source.content; cursor = source.cursor; prev=source.prev; next=source.next; } public void setNext(String cont,int curs) { CustomLinknode temp = new CustomLinknode(cont,curs,this); next = temp; } public CustomLinknode getNext() { return next; } public CustomLinknode getPrev() { return prev; } public String getcontent() { return content; } public int getcursor() { return cursor; } }
true
c1ead23fb90f448d8a528569246d470068a628b5
Java
evrenozcan/inferno
/src/net/cosmologic/inferno/android/handler/AccelerometerHandler.java
UTF-8
2,158
2.515625
3
[]
no_license
/* * */ package net.cosmologic.inferno.android.handler; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * The Class AccelerometerHandler. * * @author Evren Ozcan */ public class AccelerometerHandler implements SensorEventListener, IHandler { /** The blocked. */ private volatile boolean blocked; /** The x. */ float x; /** The y. */ float y; /** The z. */ float z; /** * Instantiates a new accelerometer handler. * * @param context the context */ public AccelerometerHandler(final Context context) { final SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); if (!manager.getSensorList(Sensor.TYPE_ACCELEROMETER).isEmpty()) { final Sensor acceleroMeter = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0); manager.registerListener(this, acceleroMeter, SensorManager.SENSOR_DELAY_GAME); } } /**{@inheritDoc}*/ @Override public void onAccuracyChanged(final Sensor sensor, final int accuracy) { if (blocked) { return; } } /**{@inheritDoc}*/ @Override public void onSensorChanged(final SensorEvent event) { if (blocked) { return; } x = event.values[0]; y = event.values[1]; z = event.values[2]; } /** * Gets the x. * * @return the x */ public float getX() { return x; } /** * Gets the y. * * @return the y */ public float getY() { return y; } /** * Gets the z. * * @return the z */ public float getZ() { return z; } /**{@inheritDoc}*/ @Override public boolean isBlocked() { return blocked; } /**{@inheritDoc}*/ @Override public void setBlocked(final boolean blocked) { this.blocked = blocked; } }
true
af5087b526145bbc9b8dfd55b009f7492874bb9a
Java
Papalaye2/projet_tutore2
/group10/deuxieme programme/ges_institut/src/com/example/ges_institut/Presen_Activity.java
UTF-8
1,041
1.8125
2
[]
no_license
package com.example.ges_institut; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; public class Presen_Activity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_presen_); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.presen_, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub if(item.getItemId()== R.id.MenuEditioncv) { Intent intent= new Intent(Presen_Activity.this,Compo_cv_Activity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } }
true
6940aac7e2749de28f089b080f4e7d5d017ae074
Java
wangpeach/xyshop-supplier
/src/main/java/com/xy/controller/ShopUpdateWalletController.java
UTF-8
2,350
1.875
2
[]
no_license
package com.xy.controller; import com.alibaba.fastjson.JSONObject; import com.github.pagehelper.PageInfo; import com.xy.models.ShopUpdateWallet; import com.xy.pojo.ParamsPojo; import com.xy.services.ShopUpdateWalletService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.web.bind.annotation.*; import tk.mybatis.mapper.entity.Condition; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.util.StringUtil; @RestController @Scope(value = "prototype") @RequestMapping(value = "updateWallet/") public class ShopUpdateWalletController { @Autowired private ShopUpdateWalletService updateWalletService; @RequestMapping(value = "pagelist") public @ResponseBody PageInfo<ShopUpdateWallet> pageList(@RequestBody JSONObject json) { ParamsPojo pj = new ParamsPojo(json); Condition cond = new Condition(ShopUpdateWallet.class); Example.Criteria cri = cond.createCriteria(); if (StringUtils.isNotEmpty(pj.getSearch())) { String[] cols = {"shopName", "cartName", "cartOpenAddr"}; String condition = "%s like", arg = "%"+ pj.getSearch() +"%"; for (String item : cols) { cri.andCondition(String.format(condition, StringUtil.camelhumpToUnderline(item)), arg); } } cri.andEqualTo("status", "wait"); return updateWalletService.selectPageInfoByCondition(cond, pj.getStart(), pj.getLength()); } @RequestMapping(value = "update") public @ResponseBody int updateWallet(@ModelAttribute ShopUpdateWallet updateWallet) { return updateWalletService.updateByPrimaryKeySelective(updateWallet); } /** * 审核通过 * * @param updateWallet * @return */ @RequestMapping(value = "pass") public @ResponseBody int pass(@ModelAttribute ShopUpdateWallet updateWallet) { return updateWalletService.updatePass(updateWallet); } /** * 驳回 * * @param updateWallet * @return */ @RequestMapping(value = "fail") public @ResponseBody int fail(@ModelAttribute ShopUpdateWallet updateWallet) { return updateWalletService.updateFail(updateWallet); } }
true
e761763c0be812fd2a50c6d8da4fd90bf276c9ee
Java
pravalikavis/Alarm
/app/src/main/java/com/example/lakshmi/alarm/AlarmReceiver.java
UTF-8
1,940
1.984375
2
[]
no_license
package com.example.lakshmi.alarm; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.widget.EditText; import android.widget.Toast; import android.os.Bundle; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; import static android.content.Intent.getIntent; public class AlarmReceiver extends BroadcastReceiver { private static final int MY_NOTIFICATION_ID=1; NotificationManager notificationManager; Notification myNotification; String s="hi"; @Override public void onReceive(Context context, Intent intent ) { Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show(); Intent myIntent = new Intent(context, SetAlarm.class); PendingIntent pendingIntent = PendingIntent.getActivity( context, 0, myIntent, 0); myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); s=intent.getExtras().getString("st"); Uri myUri = intent.getParcelableExtra("ring"); myNotification = new NotificationCompat.Builder(context) .setContentTitle("Alarm:") .setContentText(s) .setTicker("Notification!") .setWhen(System.currentTimeMillis()) .setContentIntent(pendingIntent) .setSound(myUri) .setAutoCancel(true) .setSmallIcon(R.drawable.clk) .build(); notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(MY_NOTIFICATION_ID, myNotification); } }
true
99502a69be123b2acb5236fa5b2fad66c7636dfb
Java
geison-bkz/RelacionamentoClasses
/src/view/PrincipalController.java
UTF-8
2,418
2.828125
3
[]
no_license
package view; import domain.Pessoa; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import java.util.ArrayList; public class PrincipalController { @FXML private TextField txtNome; @FXML private TextField txtIdade; @FXML private RadioButton rdMasc; @FXML private RadioButton rdFem; @FXML private TextField txtTitulo; @FXML private TextField txtAno; @FXML private TextField txtValor; @FXML private TextArea txtResult; private ArrayList<Pessoa> pessoas = new ArrayList<Pessoa>(); private void limpaTela(){ txtNome.setText(""); txtIdade.setText(""); txtTitulo.setText(""); txtAno.setText(""); txtValor.setText(""); rdMasc.setSelected(true); rdFem.setSelected(false); } @FXML void buscarNome() { txtResult.setText(""); String nomeBusca = txtNome.getText().toUpperCase(); for (Pessoa p: pessoas) { if(p.getNome().toUpperCase().startsWith(nomeBusca)){ txtResult.appendText(p.toString()); } } } @FXML void cadastrar() { Pessoa p = new Pessoa(); p.setNome(txtNome.getText()); p.setIdade(Integer.parseInt(txtIdade.getText())); p.getDvd().setTitulo(txtTitulo.getText()); p.getDvd().setAno(Integer.parseInt(txtAno.getText())); p.getDvd().setValor(Double.parseDouble(txtValor.getText())); p.setSexo(rdMasc.isSelected()?'M':'F'); pessoas.add(p); txtResult.setText(""); for (Pessoa pessoa: pessoas) { txtResult.appendText(pessoa.toString()); } limpaTela(); } @FXML void dvdMaisCaro() { Pessoa pesDvdCaro = new Pessoa(); for (Pessoa p : pessoas) { if(p.getDvd().getValor() > pesDvdCaro.getDvd().getValor()){ pesDvdCaro = p; } } txtResult.setText(pesDvdCaro.toString()); } @FXML void listarSexo() { txtResult.setText(""); char sexo = rdMasc.isSelected()?'M':'F'; for (Pessoa p : pessoas) { if(p.getSexo()==sexo){ txtResult.appendText(p.toString()); } } } }
true
3f524e769364b2c1ca2f3a29dc915302b489a7ca
Java
huizailovers/community
/src/main/java/life/majiang/community/model/User.java
UTF-8
410
1.640625
2
[]
no_license
package life.majiang.community.model; import lombok.Builder; import lombok.Data; import lombok.experimental.Tolerate; import java.util.List; /** * @author zhangch */ @Data @Builder public class User { private Long id; private String accountId; private String name; private String token; private Long gmtCreate; private List<Orders> orders; @Tolerate public User() {} }
true
c54648d74a0e4c4ac6446cff88e162fbdedb4427
Java
Shawmiya/Design_Pattern
/Creational DesignPattern/PrototypePattern/prototype_pattern_example1/src/com/example/prototype/Application.java
UTF-8
368
2.859375
3
[]
no_license
package com.example.prototype; public class Application { public static void main(String[] args) { Registry registry = new Registry(); Car car = (Car) registry.getVehicle(VehicleType.CAR); System.out.println(car); car.setType("newtype"); System.out.println(car); Car car1 = (Car) registry.getVehicle(VehicleType.CAR); System.out.println(car1); } }
true
006600e9239c004e0d38d3b3a6b05a9240a28c50
Java
rockets1131/SmartVideoSurveillance
/app/src/main/java/com/liutianjiao/smartvideosurveillance/data/Node.java
UTF-8
614
2.265625
2
[]
no_license
package com.liutianjiao.smartvideosurveillance.data; public class Node { public String nodeName; public Device deviceList[]; public int nodeId; public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public Device[] getDeviceList() { return deviceList; } public void setDeviceList(Device[] deviceList) { deviceList = deviceList; } public int getNodeId() { return nodeId; } public void setNodeId(int nodeId) { this.nodeId = nodeId; } }
true
481fabe6475e783ba0d466b9c1954afe51505dd5
Java
doraemonpup/java-hbshop
/server/src/shop/local/exceptions/ProduktExistiertBereitsException.java
UTF-8
578
2.65625
3
[]
no_license
package shop.local.exceptions; import shop.local.valueobjects.Produkt; /** * @exception Produkt ist bereits vorhanden */ public class ProduktExistiertBereitsException extends Exception{ public ProduktExistiertBereitsException(Produkt produkt, String zusatzMsg) { super("Produkt ID " + produkt.getID() + ", Name " + produkt.getProduktName() + " existiert bereits" + zusatzMsg); } public ProduktExistiertBereitsException(Produkt produkt) { super("Produkt ID " + produkt.getID() + ", Name " + produkt.getProduktName() + " existiert bereits" ); } }
true
1ef7ce8a77d1a1b57d3e4c4a1e4154af5fd724a8
Java
librairy/harvester
/src/main/java/es/upm/oeg/librairy/harvester/parser/OfficeFileReader.java
UTF-8
3,931
2.296875
2
[ "Apache-2.0" ]
permissive
package es.upm.oeg.librairy.harvester.parser; import com.google.common.base.Strings; import es.upm.oeg.librairy.harvester.builder.DateBuilder; import es.upm.oeg.librairy.harvester.data.Document; import es.upm.oeg.librairy.harvester.service.LanguageService; import org.apache.commons.lang.StringUtils; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.sax.BodyContentHandler; import org.apache.tika.sax.ContentHandlerDecorator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; /** * @author Badenes Olmedo, Carlos <[email protected]> */ public abstract class OfficeFileReader { private static final Logger LOG = LoggerFactory.getLogger(FileReader.class); private static final Integer MAXIMUM_TEXT_CHUNK_SIZE = 100000; @Value("#{environment['HARVESTER_SOURCE']?:'${harvester.source}'}") String source; @Autowired LanguageService languageService; public static String getText(InputStream inputStream, String filename){ Metadata metadata = new Metadata(); metadata.set(Metadata.RESOURCE_NAME_KEY, filename); try { AutoDetectParser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(-1); parser.parse(inputStream, handler, metadata); return handler.toString(); } catch (Exception e) { LOG.error("Error parsing document: '" + filename + "'", e); return ""; } } public static String getTextChunks(InputStream inputStream, String filename){ final List<String> chunks = new ArrayList<>(); chunks.add(""); ContentHandlerDecorator handler = new ContentHandlerDecorator() { @Override public void characters(char[] ch, int start, int length) { String lastChunk = chunks.get(chunks.size() - 1); String thisStr = new String(ch, start, length); if (lastChunk.length() + length > MAXIMUM_TEXT_CHUNK_SIZE) { chunks.add(thisStr); } else { chunks.set(chunks.size() - 1, lastChunk + thisStr); } } }; AutoDetectParser parser = new AutoDetectParser(); Metadata metadata = new Metadata(); metadata.set(Metadata.RESOURCE_NAME_KEY, filename); try { parser.parse(inputStream, handler, metadata); return chunks.stream().collect(Collectors.joining(" ")); } catch (Exception e) { LOG.error("Error parsing document: '" + filename + "'", e); return ""; } } public Document parse(Path path) { Document document = new Document(); try { String fileName = path.getFileName().toString(); String text = getTextChunks(new FileInputStream(path.toFile()), fileName); if (!Strings.isNullOrEmpty(text)){ document.setId(UUID.randomUUID().toString()); document.setName(fileName); document.setText(text); document.setDate(DateBuilder.now()); document.setFormat(StringUtils.substringAfterLast(fileName,".")); String lang = languageService.getLanguage(text.substring(0,100)); document.setLanguage(lang); document.setSource(source); } } catch (FileNotFoundException e) { e.printStackTrace(); } return document; } }
true
9aa48cf0be0acc026f8d525cfce24177fa863835
Java
LDawns/java20-homework
/9-Testing/王一-171860523/homework9/sort/MySort.java
UTF-8
129
2.15625
2
[]
no_license
package homework9.sort; import java.util.List; public interface MySort<T> { public List<T> sort(List<T> list, int mode); }
true
85a90ceb0c262b5b066232e73573af9edad8077f
Java
BYTA-TECH/doctor-service
/src/main/java/com/bytatech/ayoos/doctor/service/impl/ContactInfoServiceImpl.java
UTF-8
3,866
2.34375
2
[]
no_license
package com.bytatech.ayoos.doctor.service.impl; import com.bytatech.ayoos.doctor.service.ContactInfoService; import com.bytatech.ayoos.doctor.domain.ContactInfo; import com.bytatech.ayoos.doctor.repository.ContactInfoRepository; import com.bytatech.ayoos.doctor.repository.search.ContactInfoSearchRepository; import com.bytatech.ayoos.doctor.service.dto.ContactInfoDTO; import com.bytatech.ayoos.doctor.service.mapper.ContactInfoMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import static org.elasticsearch.index.query.QueryBuilders.*; /** * Service Implementation for managing {@link ContactInfo}. */ @Service @Transactional public class ContactInfoServiceImpl implements ContactInfoService { private final Logger log = LoggerFactory.getLogger(ContactInfoServiceImpl.class); private final ContactInfoRepository contactInfoRepository; private final ContactInfoMapper contactInfoMapper; private final ContactInfoSearchRepository contactInfoSearchRepository; public ContactInfoServiceImpl(ContactInfoRepository contactInfoRepository, ContactInfoMapper contactInfoMapper, ContactInfoSearchRepository contactInfoSearchRepository) { this.contactInfoRepository = contactInfoRepository; this.contactInfoMapper = contactInfoMapper; this.contactInfoSearchRepository = contactInfoSearchRepository; } /** * Save a contactInfo. * * @param contactInfoDTO the entity to save. * @return the persisted entity. */ @Override public ContactInfoDTO save(ContactInfoDTO contactInfoDTO) { log.debug("Request to save ContactInfo : {}", contactInfoDTO); ContactInfo contactInfo = contactInfoMapper.toEntity(contactInfoDTO); contactInfo = contactInfoRepository.save(contactInfo); ContactInfoDTO result = contactInfoMapper.toDto(contactInfo); contactInfoSearchRepository.save(contactInfo); return result; } /** * Get all the contactInfos. * * @param pageable the pagination information. * @return the list of entities. */ @Override @Transactional(readOnly = true) public Page<ContactInfoDTO> findAll(Pageable pageable) { log.debug("Request to get all ContactInfos"); return contactInfoRepository.findAll(pageable) .map(contactInfoMapper::toDto); } /** * Get one contactInfo by id. * * @param id the id of the entity. * @return the entity. */ @Override @Transactional(readOnly = true) public Optional<ContactInfoDTO> findOne(Long id) { log.debug("Request to get ContactInfo : {}", id); return contactInfoRepository.findById(id) .map(contactInfoMapper::toDto); } /** * Delete the contactInfo by id. * * @param id the id of the entity. */ @Override public void delete(Long id) { log.debug("Request to delete ContactInfo : {}", id); contactInfoRepository.deleteById(id); contactInfoSearchRepository.deleteById(id); } /** * Search for the contactInfo corresponding to the query. * * @param query the query of the search. * @param pageable the pagination information. * @return the list of entities. */ @Override @Transactional(readOnly = true) public Page<ContactInfoDTO> search(String query, Pageable pageable) { log.debug("Request to search for a page of ContactInfos for query {}", query); return contactInfoSearchRepository.search(queryStringQuery(query), pageable) .map(contactInfoMapper::toDto); } }
true
0bf66e4823c8bafa25fc7b00ca1a32ea4483d809
Java
lynn8570/WristBand
/app/src/main/java/com/lynn/wristband/activity/WelcomePagerActivity.java
UTF-8
2,143
2.078125
2
[]
no_license
package com.lynn.wristband.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.Button; import com.lynn.wristband.R; import com.lynn.wristband.adapter.WelcomePagerAdapter; import com.lynn.wristband.base.FullScreenBaseActivity; import com.lynn.wristband.view.SliderViewPagerIndicator; import butterknife.BindView; import butterknife.ButterKnife; public class WelcomePagerActivity extends FullScreenBaseActivity { @BindView(R.id.welcome_pager) ViewPager mViewPager; @BindView(R.id.enter_button) Button mEnterButton; @BindView(R.id.indicator_pager) SliderViewPagerIndicator mIndicator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ButterKnife.bind(this); initViewPager(); mEnterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent startMainActivity = new Intent(WelcomePagerActivity.this, MainActivity.class); startActivity(startMainActivity); WelcomePagerActivity.this.finish(); } }); } @Override public int getLayoutId() { return R.layout.activity_welcome_pager; } private void initViewPager() { mViewPager.setAdapter(new WelcomePagerAdapter(this)); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position == 2) { mEnterButton.setVisibility(View.VISIBLE); } else { mEnterButton.setVisibility(View.GONE); } } @Override public void onPageScrollStateChanged(int state) { } }); mIndicator.setViewPager(mViewPager); } }
true
c68fcf2e1cc63de9c50f069dfc220d975d568613
Java
prpundge/sim
/src/main/java/com/sim/entity/Sale.java
UTF-8
2,234
2.234375
2
[]
no_license
package com.sim.entity; import java.io.Serializable; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.fasterxml.jackson.annotation.JsonIgnore; /** * The persistent class for the sale database table. * */ @Entity @NamedQuery(name = "Sale.findAll", query = "SELECT s FROM Sale s") public class Sale implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "sale_id") private int saleId; @Column(name = "created_on",insertable=false) private Date createdOn; @Column(name = "customer_name") private String customerName; @Column(name = "last_updated_on",insertable=false) private Date lastUpdatedOn; private int price; private int quanity; // bi-directional many-to-one association to PackedStock @ManyToOne @JoinColumn(name = "packed_stock_id") private PackedStock packedStock; public Sale() { } public int getSaleId() { return this.saleId; } public void setSaleId(int saleId) { this.saleId = saleId; } public Date getCreatedOn() { return this.createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public String getCustomerName() { return this.customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public Date getLastUpdatedOn() { return this.lastUpdatedOn; } public void setLastUpdatedOn(Date lastUpdatedOn) { this.lastUpdatedOn = lastUpdatedOn; } public int getPrice() { return this.price; } public void setPrice(int price) { this.price = price; } public int getQuanity() { return this.quanity; } public void setQuanity(int quanity) { this.quanity = quanity; } public PackedStock getPackedStock() { return this.packedStock; } public void setPackedStock(PackedStock packedStock) { this.packedStock = packedStock; } }
true
22b520c1572eb2138e9260f972c9b4d1cd18f4d7
Java
yyjjls/FlutterwitsystemPlugin
/android/src/main/java/com/witsystem/top/flutterwitsystem/induce/Induce.java
UTF-8
5,624
2
2
[]
no_license
package com.witsystem.top.flutterwitsystem.induce; import android.app.ActivityManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.ParcelUuid; import android.util.Log; import androidx.annotation.RequiresApi; import com.witsystem.top.flutterwitsystem.rouse.Rouse; import java.util.ArrayList; import java.util.List; /** * 感应开锁 */ public final class Induce implements InduceUnlock { private Context context; private BluetoothAdapter blueAdapter; private static final String SERVICE_PATH = "com.witsystem.top.flutterwitsystem.induce.InduceService"; private static final int REQUEST_CODE = 0x01; private BluetoothManager bluetoothManager; private static Induce induce; public static Induce instance(Context context) { if (induce == null) { synchronized (Induce.class) { if (induce == null) { induce = new Induce(context); } } } return induce; } private Induce(Context context) { this.context = context; bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); assert bluetoothManager != null; blueAdapter = bluetoothManager.getAdapter(); } @Override public boolean isReaction() { return true; } //开启感应开锁 @Override public boolean openInduceUnlock() { if (!isReaction()) return false; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return false; } List<ScanFilter> scanFilterList = new ArrayList<>(); ScanFilter.Builder builder = new ScanFilter.Builder(); builder.setServiceUuid(ParcelUuid.fromString("0000fff1-0000-1000-8000-00805f9b34fb")); //builder.setServiceUuid(ParcelUuid.fromString("0000f1ff-0000-1000-8000-00805f9b34fb")); //builder.setDeviceName("Slock04EE033EA8CF");//你要扫描的设备的名称,如果使用lightble这个app来模拟蓝牙可以直接设置name ScanFilter scanFilter = builder.build(); scanFilterList.add(scanFilter); //指定蓝牙的方式,这里设置的ScanSettings.SCAN_MODE_LOW_LATENCY是比较高频率的扫描方式 ScanSettings.Builder settingBuilder = new ScanSettings.Builder(); // settingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY); //settingBuilder.setScanMode(ScanSettings.SCAN_MODE_BALANCED); settingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);//高功耗 //settingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER); //settingBuilder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE); settingBuilder.setMatchMode(ScanSettings.MATCH_MODE_STICKY); settingBuilder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES); settingBuilder.setLegacy(true); ScanSettings settings = settingBuilder.build(); //指定扫描到蓝牙后是以什么方式通知到app端,这里将以可见服务的形式进行启动 Intent intent = new Intent(SERVICE_PATH).setPackage(context.getPackageName()); PendingIntent callbackIntent = null; callbackIntent = PendingIntent.getForegroundService( context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); //启动蓝牙扫描 blueAdapter.getBluetoothLeScanner().startScan(scanFilterList, settings, callbackIntent); //启动服务 context.startService(intent); ///启动定时器 Rouse.instance(context).startRouse(); Intent intent1 = new Intent(context, InduceService.class); context.startService(intent1); Log.e("定时任务", "启动感应服务"); return true; } // 关闭感应开锁 public boolean stopInduceUnlock() { //关闭定时器 Rouse.instance(context).stopRouse(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return false; } //关闭扫描并且停止当前服务 context.stopService(stopScan()); return true; } ///关闭扫描 代表感应开锁还在后台运行 @RequiresApi(api = Build.VERSION_CODES.O) public Intent stopScan() { //关闭后台扫描 Intent intent = new Intent(SERVICE_PATH) .setPackage(context.getPackageName()); PendingIntent callbackIntent = PendingIntent.getForegroundService( context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); blueAdapter.getBluetoothLeScanner().stopScan(callbackIntent); return intent; } //感应开锁是否在运行 public boolean isRunningInduceUnlock() { ActivityManager myManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(30); for (ActivityManager.RunningServiceInfo runningServiceInfo : runningService) { if (runningServiceInfo.service.getClassName().equals(SERVICE_PATH)) { return true; } } return false; } }
true
90d5da6788d1e8933185fc48e47dccbcb9710054
Java
angelhosuarezrucoba/plantilla
/src/java/dao/MensajeDao.java
UTF-8
3,440
2.375
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 dao; import bd.Conexion; import chat.Usuario; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author Home */ public class MensajeDao { public static void insert(Usuario usuario, Usuario contacto, String mensaje) { Connection con = null; PreparedStatement ps = null; try { con = Conexion.conectar(); Timestamp now = new Timestamp(new Date().getTime()); ps = con.prepareCall("insert into internal_chat set fecha=? , fecha_index=? , hora_index=hour(?) ,campana=?,usuario=?,usuario_name=?,contacto=?,contacto_name=?,tipo=?,mensaje=?"); ps.setTimestamp(1, now); ps.setTimestamp(2, now); ps.setTimestamp(3, now); ps.setInt(4, usuario.getCampana()); ps.setLong(5, usuario.getUsuario()); ps.setString(6, usuario.getNombre()); ps.setLong(7, contacto.getUsuario()); ps.setString(8, contacto.getNombre()); ps.setString(9, "OUT"); ps.setString(10, mensaje); ps.execute(); ps.setLong(5, contacto.getUsuario()); ps.setString(6, contacto.getNombre()); ps.setLong(7, usuario.getUsuario()); ps.setString(8, usuario.getNombre()); ps.setString(9, "IN"); ps.setString(10, mensaje); ps.execute(); } catch (Exception ex) { ex.printStackTrace(); } finally { Conexion.cerrarConexion(con); } } public static JSONArray getMessages(Usuario usuario, Usuario contacto) { JSONArray messages = new JSONArray(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = Conexion.conectar(); ps = con.prepareStatement("select * , time_to_sec(fecha) as fecha_ from internal_chat where usuario=? and contacto=? and fecha_index=date(now()) order by fecha"); ps.setLong(1, usuario.getUsuario()); ps.setLong(2, contacto.getUsuario()); rs = ps.executeQuery(); while(rs.next()){ JSONObject message = new JSONObject(); message.put("mensaje", rs.getString("mensaje")); message.put("tipo", rs.getString("tipo")); message.put("usuario_name", rs.getString("usuario_name")); message.put("usuario", rs.getInt("usuario")); message.put("contacto_name", rs.getString("contacto_name")); message.put("contacto", rs.getInt("contacto")); message.put("fecha", rs.getString("fecha_")); messages.add(message); } } catch (Exception ex) { ex.printStackTrace(); } finally { Conexion.cerrarConexion(con); } return messages; } }
true
74631fff7152eb72c00ab29d4843f3dd13e113a8
Java
MyriadKaelos/EaseWithData
/src/Ease2.java
UTF-8
9,924
2.65625
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.*; import static javax.swing.JFrame.EXIT_ON_CLOSE; public class Ease2 extends JPanel implements KeyListener, MouseListener { private boolean start = false; public int mouseX; public int mouseY; public int height; public int width; public int refreshRate; private Frame frame; private String easeType; private Graphics2D g2d; private DatagramSocket udpSocket; private Socket socket; private BufferedReader in; private PrintWriter out; private InetAddress IPAddress; private byte[] sendData; private byte[] receiveData; byte[] byteIn = new byte[256]; byte[] byteOut = new byte[256]; String StringIn = ""; String StringOut = ""; private Timer t; private boolean close = false; public Ease2(int width, int height, int refreshRate, String easeType) throws InterruptedException { this.easeType = easeType; JFrame frame = new JFrame("Game"); frame.add(this); frame.addKeyListener(this); frame.addMouseListener(this); frame.setVisible(true); frame.setSize(width, height + 22); frame.setResizable(false); frame.setFocusable(true); frame.setLocationRelativeTo(null); this.frame = frame; this.width = width; this.height = height; //setting common defaults for a screen.^^^ this.refreshRate = refreshRate; frame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { System.err.println("EXIT."); if(easeType.equals("UDPclient")) { close = true; sendData = new byte[256]; int o = "#2fishBlueFish".getBytes().length; DatagramPacket sendPacket = new DatagramPacket( ("#2fishBlueFish").getBytes(), o, IPAddress, 9090); try { udpSocket.send(sendPacket); System.exit(0); } catch (IOException e) { System.err.println(e); } } else if(easeType.equals("UDPserver")) { try { receiveData = new byte[256]; sendData = new byte[256]; DatagramPacket receivePacket; receivePacket = new DatagramPacket(receiveData, receiveData.length); udpSocket.receive(receivePacket); sendData = "#2fishBlueFish".getBytes(); udpSocket.send( new DatagramPacket(sendData,sendData.length,receivePacket.getAddress(),receivePacket.getPort()) ); System.exit(0); } catch(IOException e) { System.err.println(e); } } else { System.exit(0); } } }); } public void paintComponent(Graphics g) { g2d = (Graphics2D)g; if(!start) { System.out.println("starting " + easeType); if(easeType == "base") { start = true; } else if(easeType == "UDPserver") { UDPserver(); System.out.println("server up."); } else if(easeType == "TCPserver") { TCPserver(); System.out.println("server up."); } else if(easeType == "UDPclient") { UDPclient(); System.out.println("client connected."); } else if(easeType == "TCPclient") { TCPclient(); System.out.println("client connected."); } new Timer(refreshRate, taskPerformer).start(); } mouseX = (int) MouseInfo.getPointerInfo().getLocation().getX() - frame.getX(); mouseY = (int) MouseInfo.getPointerInfo().getLocation().getY() - frame.getY(); if(easeType == "base") { paint(); } else if(easeType == "UDPserver") { UDPserverS(); } else if(easeType == "TCPserver") { TCPserverS(); } else if(easeType == "UDPclient") { UDPclientS(); } else if(easeType == "TCPclient") { TCPclientS(); } if(close) { System.exit(0); } } private void UDPserver() { try { udpSocket = new DatagramSocket(9090); System.err.println("Your hostname is: " + InetAddress.getLocalHost().getHostName()); start = true; } catch (SocketException | UnknownHostException e) { e.printStackTrace(); } } private void TCPserver() { try { ServerSocket listener = new ServerSocket(9090); System.err.println("Your address is: " + listener.getInetAddress().getLocalHost()); while (true) try { socket = listener.accept(); //tries to accept the client until the client connects. in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); start = true; break; } catch (IOException e) { System.err.println(e); } } catch (IOException e) { e.printStackTrace(); } } private void UDPclient() { try { udpSocket = new DatagramSocket(); IPAddress = InetAddress.getByName(JOptionPane.showInputDialog("Type in the hostname which has been displayed on your server's console.")); start = true; } catch (UnknownHostException | SocketException e) { e.printStackTrace(); } } private void TCPclient() { while (true) try { socket = new Socket(JOptionPane.showInputDialog("Type in the IP address which has been displayed on your server's console.\nOnly items after the '/'"), 9090); //Asks the user to put in the IP address of the server which they are trying to connect to. in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); //Sets up the ports which will send data in and out. start = true; break; } catch (IOException e) { System.err.println(e); } } private void UDPserverS() { try { receiveData = new byte[256]; sendData = new byte[256]; DatagramPacket receivePacket; receivePacket = new DatagramPacket(receiveData, receiveData.length); udpSocket.receive(receivePacket); byteIn = receivePacket.getData(); if(new String(receiveData, 0, receivePacket.getLength()).equals("#2fishBlueFish")) { System.err.println("Exiting"); System.exit(0); } paint(); sendData = byteOut; udpSocket.send( new DatagramPacket(sendData,sendData.length,receivePacket.getAddress(),receivePacket.getPort()) ); } catch(IOException e) { System.err.println(e); } } private void TCPserverS() { try { if(in.ready()) { StringIn = in.readLine(); //sets Ease up to use any data sent in. paint(); } } catch (IOException e) { e.printStackTrace(); } out.println(StringOut); } private void UDPclientS() { sendData = new byte[256]; receiveData = new byte[256]; DatagramPacket sendPacket = new DatagramPacket( byteOut, byteOut.length, IPAddress, 9090); try { udpSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); udpSocket.receive(receivePacket); byteIn = receivePacket.getData(); if(new String(receiveData, 0, receivePacket.getLength()).equals("#2fishBlueFish")) { System.err.println("Exiting"); System.exit(0); } paint(); } catch(IOException e) { System.err.println(e); } } private void TCPclientS() { try { if(in.ready()) { StringIn = in.readLine(); //sets Ease up to use any data sent in. paint(); } } catch (IOException e) { e.printStackTrace(); } out.println(StringOut); } ActionListener taskPerformer = evt -> { repaint(); }; public void paint() {} public void rect(int x, int y, int w, int h, Color c) { g2d.setColor(c); g2d.fillRect(x,y,w,h); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
true
49a35da413bcb8ccf7bd29819a3166d7e13bff82
Java
kravchik/senjin
/src/main/java/yk/senjin/shaders/uniforms/UniformVariable.java
UTF-8
1,374
2.1875
2
[ "MIT" ]
permissive
package yk.senjin.shaders.uniforms; import org.lwjgl.opengl.GL20; import yk.jcommon.utils.BadException; import yk.senjin.shaders.ShaderHandler; /** * Created by: Yuri Kravchik Date: 2 11 2007 Time: 16:10:19 */ abstract public class UniformVariable { public static UniformVariable createVariable(final String name, final float a, final float b) { return new Uniform2f(name, a, b); } public static UniformVariable createVariable(final String name, final float a, final float b, final float c) { return new Uniform3f(name, a, b, c); } public static UniformVariable createVariable(final String name, final float a, final float b, final float c, final float d) { return new Uniform4f(name, a, b, c, d); } public static UniformVariable createVariable(final String name, final int value) { return new Uniform1i(name, value); } public String name; public int index; public UniformVariable(String name) { this.name = name; } public void setValue(Object o) { BadException.notImplemented(); } public void initForProgram(final int program) { index = GL20.glGetUniformLocation(program, ShaderHandler.getBufferedString(name)); } abstract public void plug(); }
true
de9aca124fc5baee0c0abfe3b4b7a492c456f433
Java
feigezc/apple-auto
/apple-auto-calculate/apple-auto-calculate-fence/apple-auto-calculate-fence-local/src/main/java/com/appleframework/auto/calculate/fence/service/impl/FenceLocationService.java
UTF-8
1,197
2.15625
2
[ "Apache-2.0" ]
permissive
package com.appleframework.auto.calculate.fence.service.impl; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.appleframework.auto.calculate.fence.model.FenceLocation; @Service("fenceLocationService") public class FenceLocationService { protected final Logger logger = LoggerFactory.getLogger(getClass()); private Map<String, Map<String, FenceLocation>> fenceLocationMap = new HashMap<>(); public Map<String, FenceLocation> get(String key) { Map<String, Map<String, FenceLocation>> fenceLocationMap = getfenceLocationMap(); return fenceLocationMap.get(key); } public void put(String key, Map<String, FenceLocation> map) { Map<String, Map<String, FenceLocation>> fenceLocationMap = getfenceLocationMap(); fenceLocationMap.put(key, map); } public void delete(String key) { fenceLocationMap.remove(key); } private Map<String, Map<String, FenceLocation>> getfenceLocationMap() { //Map<String, Map<String, FenceLocation>> fenceLocationMap = hazelcastInstance.getMap("FENCE_LOCATION"); return fenceLocationMap; } }
true
1e82bcf49dbce0028231e924c529d19db8dc9328
Java
tdurieux/BugSwarm-dissection
/BugSwarm/yamcs-yamcs-160476934/buggy_files/yamcs-core/src/main/java/org/yamcs/web/rest/RestHandler.java
UTF-8
17,120
1.664063
2
[]
no_license
package org.yamcs.web.rest; import static io.netty.handler.codec.http.HttpHeaders.setContentLength; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.YProcessor; import org.yamcs.YamcsServer; import org.yamcs.alarms.AlarmServer; import org.yamcs.api.MediaType; import org.yamcs.management.ManagementService; import org.yamcs.protobuf.SchemaWeb; import org.yamcs.protobuf.Web.RestExceptionMessage; import org.yamcs.protobuf.Yamcs.NamedObjectId; import org.yamcs.protobuf.YamcsManagement.ClientInfo; import org.yamcs.protobuf.YamcsManagement.LinkInfo; import org.yamcs.security.Privilege; import org.yamcs.utils.StringConverter; import org.yamcs.web.BadRequestException; import org.yamcs.web.HttpException; import org.yamcs.web.HttpRequestHandler; import org.yamcs.web.InternalServerErrorException; import org.yamcs.web.NotFoundException; import org.yamcs.web.RouteHandler; import org.yamcs.xtce.Algorithm; import org.yamcs.xtce.MetaCommand; import org.yamcs.xtce.NameDescription; import org.yamcs.xtce.Parameter; import org.yamcs.xtce.SequenceContainer; import org.yamcs.xtce.XtceDb; import org.yamcs.yarch.Stream; import org.yamcs.yarch.TableDefinition; import org.yamcs.yarch.YarchDatabase; import com.fasterxml.jackson.core.JsonGenerator; import com.google.protobuf.MessageLite; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.protostuff.JsonIOUtil; import io.protostuff.Schema; /** * Contains utility methods for REST handlers. May eventually refactor this out. */ public abstract class RestHandler extends RouteHandler { private static final Logger log = LoggerFactory.getLogger(RestHandler.class); private static final byte[] NEWLINE_BYTES = "\r\n".getBytes(); protected static ChannelFuture sendOK(RestRequest restRequest) { ChannelHandlerContext ctx = restRequest.getChannelHandlerContext(); HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK); setContentLength(httpResponse, 0); return HttpRequestHandler.sendOK(ctx, restRequest.getHttpRequest(), httpResponse); } protected static <T extends MessageLite> ChannelFuture sendOK(RestRequest restRequest, T responseMsg, Schema<T> responseSchema) throws HttpException { ByteBuf body = restRequest.getChannelHandlerContext().alloc().buffer(); ByteBufOutputStream channelOut = new ByteBufOutputStream(body); try { if (MediaType.PROTOBUF.equals(restRequest.deriveTargetContentType())) { responseMsg.writeTo(channelOut); } else { JsonGenerator generator = restRequest.createJsonGenerator(channelOut); JsonIOUtil.writeTo(generator, responseMsg, responseSchema, false); generator.close(); body.writeBytes(NEWLINE_BYTES); // For curl comfort } } catch (IOException e) { throw new InternalServerErrorException(e); } byte[] dst = new byte[body.readableBytes()]; body.markReaderIndex(); body.readBytes(dst); body.resetReaderIndex(); HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, body); setContentTypeHeader(httpResponse, restRequest.deriveTargetContentType().toString()); setContentLength(httpResponse, body.readableBytes()); return HttpRequestHandler.sendOK(restRequest.getChannelHandlerContext(), restRequest.getHttpRequest(), httpResponse); } protected static ChannelFuture sendOK(RestRequest restRequest, MediaType contentType, ByteBuf body) { ChannelHandlerContext ctx = restRequest.getChannelHandlerContext(); if (body == null) { HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK); setContentLength(httpResponse, 0); return HttpRequestHandler.sendOK(ctx, restRequest.getHttpRequest(), httpResponse); } else { HttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, body); setContentTypeHeader(httpResponse, contentType.toString()); setContentLength(httpResponse, body.readableBytes()); return HttpRequestHandler.sendOK(ctx, restRequest.getHttpRequest(), httpResponse); } } protected static void sendRestError(RestRequest req, HttpResponseStatus status, Throwable t) { MediaType contentType = req.deriveTargetContentType(); ChannelHandlerContext ctx = req.getChannelHandlerContext(); if (MediaType.JSON.equals(contentType)) { try { ByteBuf buf = ctx.alloc().buffer(); ByteBufOutputStream channelOut = new ByteBufOutputStream(buf); JsonGenerator generator = req.createJsonGenerator(channelOut); JsonIOUtil.writeTo(generator, toException(t).build(), SchemaWeb.RestExceptionMessage.WRITE, false); generator.close(); buf.writeBytes(NEWLINE_BYTES); // For curl comfort HttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, buf); setContentTypeHeader(response, MediaType.JSON.toString()); // UTF-8 by default IETF RFC4627 setContentLength(response, buf.readableBytes()); HttpRequestHandler.sendError(ctx, req.getHttpRequest(), response); } catch (IOException e2) { log.error("Could not create JSON Generator", e2); log.debug("Original exception not sent to client", t); HttpRequestHandler.sendPlainTextError(ctx, req.getHttpRequest(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } } else if (MediaType.PROTOBUF.equals(contentType)) { ByteBuf buf = req.getChannelHandlerContext().alloc().buffer(); ByteBufOutputStream channelOut = new ByteBufOutputStream(buf); try { toException(t).build().writeTo(channelOut); HttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, buf); setContentTypeHeader(response, MediaType.PROTOBUF.toString()); setContentLength(response, buf.readableBytes()); HttpRequestHandler.sendError(ctx, req.getHttpRequest(), response); } catch (IOException e2) { log.error("Could not write to channel buffer", e2); log.debug("Original exception not sent to client", t); HttpRequestHandler.sendPlainTextError(ctx, req.getHttpRequest(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } } else { HttpRequestHandler.sendPlainTextError(ctx, req.getHttpRequest(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } } /** * Just a little shortcut because builders are dead ugly */ private static RestExceptionMessage.Builder toException(Throwable t) { RestExceptionMessage.Builder exceptionb = RestExceptionMessage.newBuilder(); exceptionb.setType(t.getClass().getSimpleName()); if (t.getMessage() != null) { exceptionb.setMsg(t.getMessage()); } return exceptionb; } protected static String verifyInstance(RestRequest req, String instance) throws NotFoundException { if (!YamcsServer.hasInstance(instance)) { throw new NotFoundException(req, "No instance named '" + instance + "'"); } return instance; } protected static LinkInfo verifyLink(RestRequest req, String instance, String linkName) throws NotFoundException { verifyInstance(req, instance); LinkInfo linkInfo = ManagementService.getInstance().getLinkInfo(instance, linkName); if (linkInfo == null) { throw new NotFoundException(req, "No link named '" + linkName + "' within instance '" + instance + "'"); } return linkInfo; } protected static ClientInfo verifyClient(RestRequest req, int clientId) throws NotFoundException { ClientInfo ci = ManagementService.getInstance().getClientInfo(clientId); if (ci == null) { throw new NotFoundException(req, "No such client"); } else { return ci; } } protected static YProcessor verifyProcessor(RestRequest req, String instance, String processorName) throws NotFoundException { verifyInstance(req, instance); YProcessor processor = YProcessor.getInstance(instance, processorName); if (processor == null) { throw new NotFoundException(req, "No processor '" + processorName + "' within instance '" + instance + "'"); } else { return processor; } } protected static String verifyNamespace(RestRequest req, XtceDb mdb, String pathName) throws NotFoundException { if (mdb.getNamespaces().contains(pathName)) { return pathName; } String rooted = "/" + pathName; if (mdb.getNamespaces().contains(rooted)) { return rooted; } throw new NotFoundException(req, "No such namespace"); } protected static NamedObjectId verifyParameterId(RestRequest req, XtceDb mdb, String pathName) throws NotFoundException { return verifyParameterWithId(req, mdb, pathName).getRequestedId(); } protected static Parameter verifyParameter(RestRequest req, XtceDb mdb, String pathName) throws NotFoundException { return verifyParameterWithId(req, mdb, pathName).getItem(); } protected static NameDescriptionWithId<Parameter> verifyParameterWithId(RestRequest req, XtceDb mdb, String pathName) throws NotFoundException { int lastSlash = pathName.lastIndexOf('/'); if (lastSlash == -1 || lastSlash == pathName.length() - 1) { throw new NotFoundException(req, "No such parameter (missing namespace?)"); } String namespace = pathName.substring(0, lastSlash); String name = pathName.substring(lastSlash + 1); // First try with a prefixed slash (should be the common case) NamedObjectId id = NamedObjectId.newBuilder().setNamespace("/" + namespace).setName(name).build(); Parameter p = mdb.getParameter(id); if (p == null) { // Maybe some non-xtce namespace like MDB:OPS Name id = NamedObjectId.newBuilder().setNamespace(namespace).setName(name).build(); p = mdb.getParameter(id); } // It could also be a system parameter if (p == null) { String rootedName = pathName.startsWith("/") ? pathName : "/" + pathName; p = mdb.getSystemParameterDb().getSystemParameter(rootedName, false); } if (p != null && !authorised(req, Privilege.Type.TM_PARAMETER, p.getQualifiedName())) { log.warn("Parameter {} found, but withheld due to insufficient privileges. Returning 404 instead", StringConverter.idToString(id)); p = null; } if (p == null) { throw new NotFoundException(req, "No parameter named " + StringConverter.idToString(id)); } else { return new NameDescriptionWithId<Parameter>(p, id); } } protected static Stream verifyStream(RestRequest req, YarchDatabase ydb, String streamName) throws NotFoundException { Stream stream = ydb.getStream(streamName); if (stream == null) { throw new NotFoundException(req, "No stream named '" + streamName + "' (instance: '" + ydb.getName() + "')"); } else { return stream; } } protected static TableDefinition verifyTable(RestRequest req, YarchDatabase ydb, String tableName) throws NotFoundException { TableDefinition table = ydb.getTable(tableName); if (table == null) { throw new NotFoundException(req, "No table named '" + tableName + "' (instance: '" + ydb.getName() + "')"); } else { return table; } } protected static MetaCommand verifyCommand(RestRequest req, XtceDb mdb, String pathName) throws NotFoundException { int lastSlash = pathName.lastIndexOf('/'); if (lastSlash == -1 || lastSlash == pathName.length() - 1) { throw new NotFoundException(req, "No such command (missing namespace?)"); } String namespace = pathName.substring(0, lastSlash); String name = pathName.substring(lastSlash + 1); // First try with a prefixed slash (should be the common case) NamedObjectId id = NamedObjectId.newBuilder().setNamespace("/" + namespace).setName(name).build(); MetaCommand cmd = mdb.getMetaCommand(id); if (cmd == null) { // Maybe some non-xtce namespace like MDB:OPS Name id = NamedObjectId.newBuilder().setNamespace(namespace).setName(name).build(); cmd = mdb.getMetaCommand(id); } if (cmd != null && !authorised(req, Privilege.Type.TC, cmd.getQualifiedName())) { log.warn("Command {} found, but withheld due to insufficient privileges. Returning 404 instead", StringConverter.idToString(id)); cmd = null; } if (cmd == null) { throw new NotFoundException(req, "No such command"); } else { return cmd; } } protected static Algorithm verifyAlgorithm(RestRequest req, XtceDb mdb, String pathName) throws NotFoundException { int lastSlash = pathName.lastIndexOf('/'); if (lastSlash == -1 || lastSlash == pathName.length() - 1) { throw new NotFoundException(req, "No such algorithm (missing namespace?)"); } String namespace = pathName.substring(0, lastSlash); String name = pathName.substring(lastSlash + 1); // First try with a prefixed slash (should be the common case) NamedObjectId id = NamedObjectId.newBuilder().setNamespace("/" + namespace).setName(name).build(); Algorithm algorithm = mdb.getAlgorithm(id); if (algorithm != null) { return algorithm; } // Maybe some non-xtce namespace like MDB:OPS Name id = NamedObjectId.newBuilder().setNamespace(namespace).setName(name).build(); algorithm = mdb.getAlgorithm(id); if (algorithm != null) { return algorithm; } throw new NotFoundException(req, "No such algorithm"); } protected static SequenceContainer verifyContainer(RestRequest req, XtceDb mdb, String pathName) throws NotFoundException { int lastSlash = pathName.lastIndexOf('/'); if (lastSlash == -1 || lastSlash == pathName.length() - 1) { throw new NotFoundException(req, "No such container (missing namespace?)"); } String namespace = pathName.substring(0, lastSlash); String name = pathName.substring(lastSlash + 1); // First try with a prefixed slash (should be the common case) NamedObjectId id = NamedObjectId.newBuilder().setNamespace("/" + namespace).setName(name).build(); SequenceContainer container = mdb.getSequenceContainer(id); if (container != null) { return container; } // Maybe some non-xtce namespace like MDB:OPS Name id = NamedObjectId.newBuilder().setNamespace(namespace).setName(name).build(); container = mdb.getSequenceContainer(id); if (container != null) { return container; } throw new NotFoundException(req, "No such container"); } protected static AlarmServer verifyAlarmServer(YProcessor processor) throws BadRequestException { if (!processor.hasAlarmServer()) { String instance = processor.getInstance(); String processorName = processor.getName(); throw new BadRequestException("Alarms are not enabled for processor '" + instance + "/" + processorName + "'"); } else { return processor.getParameterRequestManager().getAlarmServer(); } } protected static boolean authorised(RestRequest req, Privilege.Type type, String privilege) { return Privilege.getInstance().hasPrivilege(req.getAuthToken(), type, privilege); } protected static class NameDescriptionWithId<T extends NameDescription> { final private T item; private final NamedObjectId requestedId; NameDescriptionWithId(T item, NamedObjectId requestedId) { this.item = item; this.requestedId = requestedId; } public T getItem() { return item; } public NamedObjectId getRequestedId() { return requestedId; } } }
true
a95f3df422fe8036bb6cd930892b2cabb608d0e9
Java
haitaolv/oceanplayer
/app/src/main/java/com/mega/oceanplayer/LanguageUtil.java
UTF-8
3,965
2.3125
2
[]
no_license
package com.mega.oceanplayer; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.os.LocaleList; import android.util.DisplayMetrics; import java.util.Locale; public class LanguageUtil { public static final int LANGUAGE_FOLLOW_SYSTEM = 0; public static final int LANGUAGE_CHINA = 1; public static final int LANGUAGE_US = 2; private static final String LOCALE_SP = "LOCALE_SP"; private static final String LOCALE_SP_KEY = "LOCALE_SP_KEY"; private static final String TAG = LanguageUtil.class.getSimpleName(); public static Locale getLanguageById(int id) { Locale locale = Locale.getDefault(); switch (id) { case LANGUAGE_FOLLOW_SYSTEM: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { locale = Resources.getSystem().getConfiguration().getLocales().get(0); } else { locale = Resources.getSystem().getConfiguration().locale; } break; case LANGUAGE_US: locale = Locale.US; break; case LANGUAGE_CHINA: locale = Locale.CHINA; break; } return locale; } public static Locale readSavedLocale(Context context) { SharedPreferences spLocale = context.getSharedPreferences(LOCALE_SP, Context.MODE_PRIVATE); int language = 0; try { language = spLocale.getInt(LOCALE_SP_KEY, 0); } catch(Exception ex) { ex.printStackTrace(); } LogUtil.d(TAG, "read saved Locale from " + context.toString() + ", locale=" + language); return getLanguageById(language); } public static void saveLocale(Context context, int locale) { SharedPreferences spLocal = context.getSharedPreferences(LOCALE_SP, Context.MODE_PRIVATE); SharedPreferences.Editor edit = spLocal.edit(); edit.putInt(LOCALE_SP_KEY, locale); if(edit.commit()) { LogUtil.d(TAG, "save Locale to " + context.toString() + ", locale=" + locale); }else { LogUtil.d(TAG, "Failed to save Locale to " + context.toString() + ", locale=" + locale); } } public static boolean updateLocale(Context context, Locale locale) { if (needUpdateLocale(context, locale)) { Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); DisplayMetrics displayMetrics = resources.getDisplayMetrics(); configuration.setLocale(locale); resources.updateConfiguration(configuration, displayMetrics); return true; } else { LogUtil.d(TAG, "no need to change language: currentLocal=" + getCurrentLocale(context) + ", newLocale=" + locale); } return false; } public static boolean needUpdateLocale(Context pContext, Locale newUserLocale) { return newUserLocale != null && !getCurrentLocale(pContext).equals(newUserLocale); } public static Locale getCurrentLocale(Context context) { Locale locale; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //7.0有多语言设置获取顶部的语言 Configuration config = context.getResources().getConfiguration(); locale = config.getLocales().get(0); LocaleList ll = config.getLocales(); for(int i=0; i< ll.size(); i++){ LogUtil.d(TAG, "Find Locale in current configuration locale list: " + ll.get(i)); } } else { locale = context.getResources().getConfiguration().locale; } LogUtil.d(TAG, "current locale is: " + locale); return locale; } }
true
ff3898dc60fb7480fae5a858fca72ec32be57cae
Java
Shadow649/hardware-shop
/order-parent/order-query/src/test/java/com/shadow649/hardwareshop/query/eventhandler/OrderProjectionEventHandlerTest.java
UTF-8
3,956
2.25
2
[]
no_license
package com.shadow649.hardwareshop.query.eventhandler; import com.shadow649.hardwareshop.domain.CustomerInfo; import com.shadow649.hardwareshop.domain.OrderRow; import com.shadow649.hardwareshop.domain.OrderStatus; import com.shadow649.hardwareshop.domain.ProductID; import com.shadow649.hardwareshop.event.OrderApprovedEvent; import com.shadow649.hardwareshop.event.OrderConfirmedEvent; import com.shadow649.hardwareshop.event.OrderProductUpdatedEvent; import com.shadow649.hardwareshop.query.OrderNotFoundException; import com.shadow649.hardwareshop.query.domain.OrderEntry; import com.shadow649.hardwareshop.query.domain.OrderLine; import com.shadow649.hardwareshop.query.service.OrderEntryService; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.math.BigDecimal; import java.util.Collections; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; public class OrderProjectionEventHandlerTest { @Mock private OrderEntryService service; @Captor private ArgumentCaptor<OrderEntry> entryCaptor; private OrderProjectionEventHandler orderProjectionEventHandler; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); orderProjectionEventHandler = new OrderProjectionEventHandler(service); } @Test(expected = OrderNotFoundException.class) public void givenOrderNotExists_whenServiceGetById_ThrowOrderNotFoundException() { when(service.getById(anyString())).thenThrow(new OrderNotFoundException()); orderProjectionEventHandler.on(new OrderConfirmedEvent("id")); } @Test public void whenAnOrderIsApproved_thenSaveProjection() { CustomerInfo customerInfo = new CustomerInfo("Mario", "[email protected]"); List<OrderRow> rows = Collections.singletonList(new OrderRow(new ProductID("pID"), "product1", new BigDecimal(11))); orderProjectionEventHandler.on(new OrderApprovedEvent("id", customerInfo, rows)); verify(service).save(entryCaptor.capture()); OrderEntry saved = entryCaptor.getValue(); assertThat(saved.getOrderLines().size()).isEqualTo(rows.size()); assertThat(saved.getOrderLines().get(0).getName()).isEqualTo("product1"); } @Test public void whenAProductInOrderIsUpdated_thenTheUpdatedEntryIsSaved() { OrderEntry orderEntry = new OrderEntry("test1", "[email protected]", new Date(1), OrderStatus.CONFIRMED); OrderLine orderLine = new OrderLine(orderEntry, "123", "test", 123); orderEntry.setOrderLines(Collections.singletonList(orderLine)); when(service.getById("test1")).thenReturn(orderEntry); orderProjectionEventHandler.on(new OrderProductUpdatedEvent("test1", "123", "newName", new BigDecimal(1000))); verify(service).save(entryCaptor.capture()); OrderEntry saved = entryCaptor.getValue(); assertThat(saved.getOrderLines().get(0).getName()).isEqualTo("newName"); assertThat(saved.getOrderLines().get(0).getOldName()).isEqualTo("test"); assertThat(saved.getOrderLines().get(0).isUpdated()).isTrue(); } @Test public void whenAProductNotInTheOrderIsUpdated_thenNoUpdate() { OrderEntry orderEntry = new OrderEntry("test1", "[email protected]", new Date(1), OrderStatus.CONFIRMED); OrderLine orderLine = new OrderLine(orderEntry, "123", "test", 123); orderEntry.setOrderLines(Collections.singletonList(orderLine)); when(service.getById("test1")).thenReturn(orderEntry); orderProjectionEventHandler.on(new OrderProductUpdatedEvent("test1", "5", "newName", new BigDecimal(1000))); verify(service).getById("test1"); verifyNoMoreInteractions(service); } }
true
2baac6b8a644df0f79f151ea70737b6b36560eba
Java
MCemilSisman/groupJ
/RoadBlocker/src/ObjectPackage/Level.java
UTF-8
2,396
3.0625
3
[]
no_license
package ObjectPackage; public class Level { Blocks[] blocksArray; Table table; int noOfBlocks; public Level() { } public void createTable(int sizeX, int sizeY) { table = new Table(sizeX, sizeY); } public void createBlocks(int numberOfBlocks) { blocksArray = new Blocks[numberOfBlocks]; noOfBlocks = numberOfBlocks; } public void setTable(int x, int y, BlockType type) { table.setLocationEnum(x,y,type); } public void addBlock(Blocks a) { boolean found = false; for( int i = 0; i < noOfBlocks; i++){ if(blocksArray[i] == null){ if( found == false){ blocksArray[i] = a; found = true; } } } } public void addEditorBlock(Blocks added) { if(blocksArray != null) { Blocks[] temp = new Blocks[noOfBlocks + 1]; for(int i = 0; i < noOfBlocks; i++) temp[i] = blocksArray[i]; temp[noOfBlocks] = added; blocksArray = temp; } else { blocksArray = new Blocks[1]; blocksArray[0] = added; } noOfBlocks++; } public void removeEditorBlock(Blocks removed) { if(noOfBlocks != 1) { Blocks[] temp = new Blocks[noOfBlocks - 1]; boolean found = false; for(int i = 0; i < noOfBlocks; i++) { if((!(blocksArray[i].equals(removed))) && !found) { temp[i] = blocksArray[i]; } else if(found) { temp[i - 1] = blocksArray[i]; } else found = true; } blocksArray = temp; } else { blocksArray = null; } noOfBlocks--; } public Table getTable(){ return table; } public Blocks[] getBlocks(){ return blocksArray; } }
true
f922a16030654282746efea04f67234218a50bd8
Java
nolDsouza/generic_booking_system
/src/NWC/model/AppTime.java
UTF-8
1,698
2.984375
3
[]
no_license
package NWC.model; public class AppTime { private int head = 0; private int tail = 0; public int[] buffer = {0,0,0,0,0,0,0,0}; public AppTime(int[] buffer) { this.buffer = buffer; for (int i=0;i<buffer.length;i++) { if (buffer[i] == 1) { head = i+10; break; } } for (int i=buffer.length-1; i>=0 ;i--) { if (buffer[i] == 1) { tail = i+11; break; } } } public AppTime(int head, int tail) { this.head = head; this.tail = tail; for (int i=(head-10); i<(tail-10); i++) { buffer[i] = 1; } } public void setBuffer(int[] buffer) { this.buffer = buffer; } public void flip(int[] buffer) { for (int i=0; i<8; i++) { if (buffer[i] == 1) { this.buffer[i] = -1; } } } public void add(AppTime a) { for (int i=0;i<8;i++) { if (this.buffer[i] != 1 && a.buffer[i] == 1) { this.buffer[i] = 1; } } } public String bufferTS() { String tempString = "["; for (int i=0; i<buffer.length; i++) { tempString += buffer[i]; } return tempString += "]"; } public String toString() { return String.format("%d:00-%d:00", head, tail); } public boolean matches(int[] buffer) { for (int i=0;i<buffer.length; i++) { if (this.buffer[i] == 1) { if (buffer[i] != 1) { return false; } } } return true; } public static boolean isEmpty(int[] buffer) { for (int i=0;i<buffer.length;i++) { if (buffer[i] == 1) return false; } return true; } public boolean isFull() { for (int i=0;i<buffer.length;i++) { if (buffer[i] == 0) return false; } return true; } }
true
dae47cb6dc8c985864c116d35651ad5af2295ac7
Java
xiaojianma9999/MemoryExercise
/app/src/main/java/com/xiaojianma/memoryexercise/activity/BaseActivity.java
UTF-8
13,860
2.453125
2
[]
no_license
package com.xiaojianma.memoryexercise.activity; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.PowerManager; import android.speech.tts.TextToSpeech; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import com.xiaojianma.memoryexercise.R; import java.util.Locale; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class BaseActivity extends Activity implements TextToSpeech.OnInitListener { private static final String TAG = "BaseActivity"; // TTS对象 protected TextToSpeech mTextToSpeech; protected float speechRate = 1.0f; protected String speechRateText = "1.0X"; protected ExecutorService service = Executors.newSingleThreadExecutor(); protected volatile Lock lock = new ReentrantLock(); // 1、朗读文本 2、自动播放设置页面 3、随机播放设置页面 protected volatile int executeThread = 1; protected volatile Condition speckCondition = lock.newCondition(); protected volatile Condition autoPlayCondition = lock.newCondition(); protected volatile Condition randomPlayCondition = lock.newCondition(); protected volatile boolean isAutoPlay = false; protected volatile boolean isRandomAutoPlay = false; protected volatile boolean pauseAutoPlay = false; protected volatile boolean pauseRandomPlay = false; protected Menu menu; // 电源管理锁 protected PowerManager.WakeLock wakeLock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, this.getLocalClassName()); wakeLock.acquire(); initTextToSpeech(); } private void initTextToSpeech() { // 参数Context,TextToSpeech.OnInitListener mTextToSpeech = new TextToSpeech(this, this); // 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规 mTextToSpeech.setPitch(1.0f); // 设置语速 mTextToSpeech.setSpeechRate(speechRate); } @Override protected void onDestroy() { if (mTextToSpeech != null) { mTextToSpeech.stop(); mTextToSpeech.shutdown(); mTextToSpeech = null; } service.shutdownNow(); if (wakeLock != null) { wakeLock.release(); } super.onDestroy(); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { /* 使用的是小米手机进行测试,打开设置,在系统和设备列表项中找到更多设置, 点击进入更多设置,在点击进入语言和输入法,见语言项列表,点击文字转语音(TTS)输出, 首选引擎项有三项为Pico TTs,科大讯飞语音引擎3.0,度秘语音引擎3.0。其中Pico TTS不支持 中文语言状态。其他两项支持中文。选择科大讯飞语音引擎3.0。进行测试。 如果自己的测试机里面没有可以读取中文的引擎, 那么不要紧,我在该Module包中放了一个科大讯飞语音引擎3.0.apk,将该引擎进行安装后,进入到 系统设置中,找到文字转语音(TTS)输出,将引擎修改为科大讯飞语音引擎3.0即可。重新启动测试 Demo即可体验到文字转中文语言。 */ // setLanguage设置语言 int result = mTextToSpeech.setLanguage(Locale.CHINA); // TextToSpeech.LANG_MISSING_DATA:表示语言的数据丢失 // TextToSpeech.LANG_NOT_SUPPORTED:不支持 if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show(); } } } protected void speechText(String text) { lock.lock(); try { // while (executeThread != 1) { // Log.w(TAG, "speechText await"); // speckCondition.await(); // } if (mTextToSpeech != null) { /* TextToSpeech的speak方法有两个重载。 // 执行朗读的方法 speak(CharSequence text,int queueMode,Bundle params,String utteranceId); // 将朗读的的声音记录成音频文件 synthesizeToFile(CharSequence text,Bundle params,File file,String utteranceId); 第二个参数queueMode用于指定发音队列模式,两种模式选择 (1)TextToSpeech.QUEUE_FLUSH:该模式下在有新任务时候会清除当前语音任务,执行新的语音任务 (2)TextToSpeech.QUEUE_ADD:该模式下会把新的语音任务放到语音任务之后, 等前面的语音任务执行完了才会执行新的语音任务 */ speechRate = getSpeechRate(); mTextToSpeech.setSpeechRate(speechRate); mTextToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null); } if (isAutoPlay) { executeThread = 2; autoPlayCondition.signal(); } else if (isRandomAutoPlay) { executeThread = 3; randomPlayCondition.signal(); } } catch (Exception e) { Log.e(TAG, "speechText error: " + e.toString()); } finally { lock.unlock(); } } private float getSpeechRate() { if (getString(R.string.point_five_rate).equals(speechRateText)) { return 0.5f; } else if (getString(R.string.point_seventy_five_rate).equals(speechRateText)) { return 0.75f; } else if (getString(R.string.one_rate).equals(speechRateText)) { return 1.0f; } else if (getString(R.string.one_point_twenty_five_rate).equals(speechRateText)) { return 1.25f; } else if (getString(R.string.one_point_five_rate).equals(speechRateText)) { return 1.5f; } else if (getString(R.string.one_point_seventy_five_rate).equals(speechRateText)) { return 1.75f; } else if (getString(R.string.two_rate).equals(speechRateText)) { return 2.0f; } return 1.0f; } protected void initActionBar(String title) { ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.show(); actionBar.setTitle(title); // actionBar.setDisplayShowHomeEnabled(true); // actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setDisplayShowCustomEnabled(true); // actionBar.setDisplayShowTitleEnabled(true); // View layoutActionbar = LayoutInflater.from(this).inflate(R.layout.layout_titlebar, null); // TextView titleText = layoutActionbar.findViewById(R.id.text_title); // titleText.setText(title); // actionBar.setCustomView(layoutActionbar); } } // public void onClick(View view) { // switch (view.getId()) { // case R.id.back: // finish(); // break; // case R.id.menu: // break; // default: // break; // } // } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); this.menu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.isCheckable()) { item.setChecked(true); } switch (item.getItemId()) { case android.R.id.home: // 返回键的id this.finish(); case R.id.auto_play: CharSequence title = item.getTitle(); if (title.equals(getString(R.string.auto_play))) { autoPlay(item); } else if (title.equals(getString(R.string.pause))) { pauseAutoPlay(item); } break; case R.id.random_play: CharSequence state = item.getTitle(); if (state.equals(getString(R.string.open_random_play))) { randomPlay(item); } else if (state.equals(getString(R.string.close_random_play))) { pauseRandomPlay(item); } break; case R.id.play_speed: PopupWindow popupWindow = new PopupWindow(this); View inflate = LayoutInflater.from(this).inflate(R.layout.pop_window_layout, null); popupWindow.setContentView(inflate); setSelected(inflate); setClickListener(inflate, popupWindow); // popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT); // popupWindow.setHeight(LinearLayout.LayoutParams.MATCH_PARENT); popupWindow.setOutsideTouchable(true); popupWindow.setFocusable(true); View decorView = getWindow().getDecorView(); int width = decorView.getWidth(); int height = decorView.getHeight(); popupWindow.showAtLocation(decorView, Gravity.NO_GRAVITY, width / 10 * 7, height / 5); break; } return super.onOptionsItemSelected(item); } protected void pauseAutoPlay(MenuItem item) { pauseAutoPlay = true; item.setTitle(R.string.auto_play); isAutoPlay = false; // executeThread = 1; // speckCondition.signal(); } protected void autoPlay(MenuItem item) { item.setTitle(R.string.pause); // 先暂停随机自动播放 if (menu != null) { pauseRandomPlay(menu.getItem(1)); } pauseAutoPlay = false; isAutoPlay = true; executeThread = 2; } protected void pauseRandomPlay(MenuItem item) { pauseRandomPlay = true; item.setTitle(R.string.open_random_play); isRandomAutoPlay = false; // executeThread = 1; // speckCondition.signal(); } protected void randomPlay(MenuItem item) { item.setTitle(R.string.close_random_play); // 先暂停自动播放 if (menu != null) { pauseAutoPlay(menu.getItem(0)); } pauseRandomPlay = false; isRandomAutoPlay = true; executeThread = 3; } private void setClickListener(View inflate, final PopupWindow popupWindow) { setSpeechRateText(inflate, popupWindow, R.id.point_five); setSpeechRateText(inflate, popupWindow, R.id.point_seventy_five); setSpeechRateText(inflate, popupWindow, R.id.one); setSpeechRateText(inflate, popupWindow, R.id.one_point_twenty_five); setSpeechRateText(inflate, popupWindow, R.id.one_point_five); setSpeechRateText(inflate, popupWindow, R.id.one_point_seventy_five); setSpeechRateText(inflate, popupWindow, R.id.two); } private void setSpeechRateText(final View inflate, final PopupWindow popupWindow, final int id) { final TextView text = inflate.findViewById(id); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { speechRateText = text.getText().toString().trim(); setGrayBackground(inflate, id); popupWindow.dismiss(); Toast.makeText(BaseActivity.this, "当前播放速度为:" + speechRateText, Toast.LENGTH_SHORT).show(); } }); } @SuppressLint("ResourceAsColor") private void setSelected(View inflate) { if (getString(R.string.point_five_rate).equals(speechRateText)) { setGrayBackground(inflate, R.id.point_five); } else if (getString(R.string.point_seventy_five_rate).equals(speechRateText)) { setGrayBackground(inflate, R.id.point_seventy_five); } else if (getString(R.string.one_rate).equals(speechRateText)) { setGrayBackground(inflate, R.id.one); } else if (getString(R.string.one_point_twenty_five_rate).equals(speechRateText)) { setGrayBackground(inflate, R.id.one_point_twenty_five); } else if (getString(R.string.one_point_five_rate).equals(speechRateText)) { setGrayBackground(inflate, R.id.one_point_five); } else if (getString(R.string.one_point_seventy_five_rate).equals(speechRateText)) { setGrayBackground(inflate, R.id.one_point_seventy_five); } else if (getString(R.string.two_rate).equals(speechRateText)) { setGrayBackground(inflate, R.id.two); } } @SuppressLint("ResourceAsColor") private void setGrayBackground(View inflate, int p) { inflate.findViewById(p).setBackgroundColor(R.color.gray); } }
true
828a2329bcc858f5417dafec9c5407b27a53a376
Java
dengjiaping/YorkiT_etbHD
/YorKoft_SF_HD/src/com/yorkit/testetablehd/pos/dialog/PayDialogFragment.java
UTF-8
13,839
1.601563
2
[]
no_license
package com.yorkit.testetablehd.pos.dialog; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Dialog; import android.os.Bundle; import android.text.InputType; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.google.gson.Gson; import com.yorkit.moble.ResultData; import com.yorkit.moble.RequesSubmitData; import com.yorkit.moble.pos.PayMoneyType; import com.yorkit.moble.pos.PosCorp; import com.yorkit.moble.pos.PosDish; import com.yorkit.moble.pos.PosMobleTwo; import com.yorkit.moble.pos.PosOrderInfo; import com.yorkit.network.NetWorkUnit; import com.yorkit.network.config.NetworkProtocol; import com.yorkit.testetablehd.R; import com.yorkit.testetablehd.myinterface.MyDialogInterface; import com.yorkit.testetablehd.myinterface.PassData; import com.yorkit.testetablehd.pos.adatper.PayTypeAdatper; import com.yorkit.testetablehd.pos.keyborad.MyNumberKeyboard; import com.yorkit.util.dialog.ListenerInfo; import com.yorkit.util.AlertMeseage; import com.yorkit.util.MathUnit; /** * @author liushengjop * @time 2014年4月11日 下午5:25:37 * */ public class PayDialogFragment extends BaseDialogFragment implements OnClickListener { public String idStr = ""; public String tag=getClass().getSimpleName(); /**总价格*/ private EditText et_total_price; /**找零*/ private EditText et_change; /**余额*/ private EditText et_over; private PosCorp posCorp; private ArrayList<PosMobleTwo> posPayments; private ArrayList<PosMobleTwo> posCurrencys; // private ArrayList<PosDish> orderDishs; private PosOrderInfo orderInfo; /**总价格*/ private Double totalMoney ; /**总数量*/ private int totalQuantity; /**余额*/ private Double over = 0.0; /**当前价格*/ private Double doubleCurrent = 0.0; private ListView listView; private PayTypeAdatper mAdatper; private MyNumberKeyboard my_keyboard; /**默认付款方式*/ private PosMobleTwo defaultMonety; private PosMobleTwo defaultPayType; /**按钮名称*/ private String btn_name="btn"; /**数据传输*/ private PassData<Boolean> passData; public void setPassData(PassData<Boolean> passData) { this.passData = passData; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); posCorp = getArguments().getParcelable("posCorp"); posPayments = getArguments().getParcelableArrayList("posPayments"); posCurrencys = getArguments().getParcelableArrayList("posCurrencys"); // orderDishs = getArguments().getParcelableArrayList("orderDishs"); orderInfo = getArguments().getParcelable("orderInfo"); Iterator<PosMobleTwo> iterable = posCurrencys.iterator(); while (iterable.hasNext()) { PosMobleTwo mobleTwo = iterable.next(); if(posCorp.cyId == mobleTwo.id) { defaultMonety = mobleTwo; break; } } Iterator<PosMobleTwo> iterable2 = posPayments.iterator(); while (iterable2.hasNext()) { PosMobleTwo mobleTwo = iterable2.next(); if(posCorp.ptId == mobleTwo.id) { defaultPayType = mobleTwo; break; } } totalMoney = 0.0; totalQuantity = 0; over = 0.0; Iterator<PosDish> iterator = orderInfo.dishes.iterator(); while (iterator.hasNext()) { PosDish posDish = iterator.next(); if(posDish.dishesStatus == 1) { totalMoney = totalMoney + posDish.quantity * posDish.currentPrice; totalQuantity = totalQuantity + posDish.quantity ; } } over = totalMoney; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().setTitle(R.string.txt_dialog_pay_title); getDialog().setCanceledOnTouchOutside(false); idStr = getActivity().getPackageName(); View view=inflater.inflate(R.layout.dialog_pay, container, false); et_total_price=(EditText) view.findViewById(R.id.et_total_price); et_change = (EditText)view.findViewById(R.id.et_change); et_over = (EditText)view.findViewById(R.id.et_over); listView = (ListView)view.findViewById(R.id.listView); mAdatper = new PayTypeAdatper(new ArrayList<PayMoneyType>(), getActivity()); listView.setAdapter(mAdatper); et_total_price.setText(""+totalMoney); et_over.setText(""+totalMoney); et_change.setText("0.0"); my_keyboard = (MyNumberKeyboard)view.findViewById(R.id.my_keyboard); setListener(); dealButton(view); return view; } /*** * 处理功能按钮 */ public void dealButton(View view) { for (int i = 0; i < posPayments.size(); i++) { int btn_id = getResources().getIdentifier(btn_name+i, "id", idStr); Button btn = (Button)view.findViewById(btn_id); btn.setText(posPayments.get(i).title); btn.setTag(i); btn.setOnClickListener(this); } //退出按钮 int btn_exit_id = getResources().getIdentifier(btn_name+(posPayments.size()), "id", getActivity().getPackageName()); Button btn_exit = (Button)view.findViewById(btn_exit_id); btn_exit.setText(R.string.txt_dialog_btn_pay_type_exit); btn_exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(passData != null) passData.passData(false); getDialog().dismiss(); } }); int btn_id_select = getResources().getIdentifier(btn_name+(posPayments.size()+1), "id", "com.yorkit.testetablehd"); //其它货币 Button btn_select = (Button)view.findViewById(btn_id_select); btn_select.setText(R.string.txt_dialog_btn_pay_type_other); btn_select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertSelectCashTypeDialog(); } }); if(posPayments.size() + 2 < 12) { for (int i = posPayments.size() + 2; i < 12; i++) { int btn_id = getResources().getIdentifier(btn_name+i, "id", "com.yorkit.testetablehd"); Button btn = (Button)view.findViewById(btn_id); btn.setVisibility(View.INVISIBLE); } } } public void setListener() { et_over.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { my_keyboard.setEditext(et_over,new MyNumberKeyboard.EnterListener() { @Override public void enterListener() { try { if(over <= 0) submitPause(getSubmitData()); else AlertMeseage.showToast(getActivity(), "请收款完成后进行提交"); } catch (JSONException e) { e.printStackTrace(); } } }); } } }); et_over.requestFocus(); et_change.setInputType(InputType.TYPE_NULL); et_total_price.setInputType(InputType.TYPE_NULL); if (android.os.Build.VERSION.SDK_INT <= 10) {//4.0以下 danielinbiti et_over.setInputType(InputType.TYPE_NULL); } else { getActivity().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); try { Class<EditText> cls = EditText.class; Method setShowSoftInputOnFocus; setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class); setShowSoftInputOnFocus.setAccessible(true); setShowSoftInputOnFocus.invoke(et_over, false); } catch (Exception e) { e.printStackTrace(); } } } @Override public void onClick(View v) { Calculate(posPayments.get((Integer) v.getTag()) ,defaultMonety); } private void alertSelectCashTypeDialog() { SelectCashDialogFragment fragment=new SelectCashDialogFragment(); Bundle bundle = new Bundle(); bundle.putParcelableArrayList("posCurrencys",posCurrencys); fragment.setArguments(bundle); fragment.setmPassData(new PassData<PosMobleTwo>() { @Override public void passData(PosMobleTwo t) { //设置当前货币为选中货币 PosMobleTwo posMobleTwo = new PosMobleTwo(); posMobleTwo.id = defaultPayType.id; posMobleTwo.title = t.title; posMobleTwo.ptCode = defaultPayType.ptCode; Calculate(posMobleTwo,t); } }); fragment.show(getFragmentManager(), fragment.tag); } public void Calculate(PosMobleTwo currentPayType,PosMobleTwo currentMoneyType){ if(over <= 0) { AlertMeseage.showToast(getActivity(), "金额以经够了"); et_over.setText("0.0"); return; } if(TextUtils.isEmpty(et_over.getText().toString())) { AlertMeseage.showToast(getActivity(), "请填写金额"); return; } else if(Double.valueOf(et_over.getText().toString()) == 0) { AlertMeseage.showToast(getActivity(), "提交金额数不能为0"); return; } try { doubleCurrent = Double.valueOf(et_over.getText().toString()); } catch (NumberFormatException e) { AlertMeseage.showToast(getActivity(), "填写正确数据格式"); return; } //付款方式对象生成 PayMoneyType payMoneyType = new PayMoneyType(); payMoneyType.ptStr = currentPayType.title; payMoneyType.ptId = currentPayType.id; payMoneyType.ptCode = currentPayType.ptCode; payMoneyType.ctStr = currentMoneyType.title; payMoneyType.cyId = currentMoneyType.id; payMoneyType.rate = currentMoneyType.rate; payMoneyType.dollar =currentMoneyType.dollar; payMoneyType.cyCode = currentMoneyType.cyCode; //是否需要找回 如果当前货币类型 等于默认货币类型就不计算汇率 否则就计算汇率 if(currentMoneyType.id == defaultMonety.id) { if(over - doubleCurrent < 0 ) { payMoneyType.amount = over; } else { payMoneyType.amount = doubleCurrent; } over = over - doubleCurrent; } else { if(over - MathUnit.mul(doubleCurrent, currentMoneyType.rate) < 0) { payMoneyType.amount = MathUnit.div(over, currentMoneyType.rate, 2); } else { payMoneyType.amount = doubleCurrent; } over = over - MathUnit.mul(doubleCurrent, currentMoneyType.rate); } //四舍五入 over = MathUnit.round(over, 1); if(over <= 0 ) { et_change.setText(""+over) ; et_over.setText("0.0"); } else { //余额 et_over.setText(""+over); et_change.setText("0.0") ; } //数据 if(mAdatper != null) mAdatper.addItem(payMoneyType); else { mAdatper = new PayTypeAdatper(new ArrayList<PayMoneyType>(), getActivity()); listView.setAdapter(mAdatper); mAdatper.addItem(payMoneyType); } //提交数据 if(over <= 0) { try { submitPause(getSubmitData()); } catch (JSONException e) { e.printStackTrace(); } } } /*** * 提交数据 * @return * @throws JSONException */ public JSONObject getSubmitData() throws JSONException { RequesSubmitData requesSubmitData = new RequesSubmitData(); JSONObject body = requesSubmitData.getBody(); Gson gson = new Gson(); // String content = gson.toJson(orderDishs); // JSONArray dishes = new JSONArray(content); JSONArray payment = new JSONArray(gson.toJson(mAdatper.getData())); // body.put("dishes", dishes); body.put("payment", payment); // body.put("orderStatus", SaleFragment.SUBMIT); body.put("tableName", orderInfo.tableName); body.put("userNumber", orderInfo.userNumber); body.put("dishesAmount", totalMoney); return requesSubmitData.getObj(); } public void submitPause(JSONObject obj) { new NetWorkUnit(getActivity(), Request.Method.POST, NetworkProtocol.POSPAYMONEY,obj, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { ResultData jsonMainObj = ResultData.readJsonMainObj(response); if(!TextUtils.isEmpty(jsonMainObj.getDesc())){ AlertMeseage.showToast(getActivity(), jsonMainObj.getDesc()); } if(jsonMainObj.getStatus() == 200) { if(passData != null) { passData.passData(true); } Bundle bundle = new Bundle(); bundle.putString("content", "找回"+over); ListenerInfo listenerInfo = new ListenerInfo(); listenerInfo.dialogOnClickListener = new MyDialogInterface.OnClickListener() { @Override public void onClick(Dialog dialog) { getDialog().dismiss(); dialog.dismiss(); } }; if(over < 0) { AlertMeseage.showSure(getFragmentManager(),bundle,listenerInfo); } else { getDialog().dismiss(); } } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); } }
true
1dc1df9018806f6d199cda5405445396f3bd07da
Java
anaspitzmaus/kgp
/kgp/src/com/rose/kgp/echo/PnlMV.java
UTF-8
3,034
2.421875
2
[]
no_license
package com.rose.kgp.echo; import java.awt.BorderLayout; import java.awt.Font; import java.beans.PropertyChangeListener; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSplitPane; import net.miginfocom.swing.MigLayout; public class PnlMV extends JPanel { JFormattedTextField ftxtPGMean; /** * Create the panel. */ public PnlMV() { setLayout(new BorderLayout(0, 0)); JSplitPane splitPane = new JSplitPane(); splitPane.setResizeWeight(0.5); add(splitPane, BorderLayout.CENTER); JPanel pnlValues = new JPanel(); splitPane.setLeftComponent(pnlValues); pnlValues.setLayout(new MigLayout("", "[][100.00,grow][]", "[][][][]")); JLabel lblPGMean = new JLabel("PGmean:"); lblPGMean.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblPGMean, "cell 0 0,alignx left"); ftxtPGMean = new JFormattedTextField(); ftxtPGMean.setColumns(5); ftxtPGMean.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(ftxtPGMean, "cell 1 0,alignx left"); JLabel lblPGMeanUnit = new JLabel("mmHg"); lblPGMeanUnit.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblPGMeanUnit, "cell 2 0"); JLabel lblPGMax = new JLabel("PGmax:"); lblPGMax.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblPGMax, "cell 0 1,alignx left"); JFormattedTextField ftxtPGMax = new JFormattedTextField(); ftxtPGMax.setColumns(5); ftxtPGMax.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(ftxtPGMax, "cell 1 1,alignx left"); JLabel lblPGmaxUnit = new JLabel("mmHg"); lblPGmaxUnit.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblPGmaxUnit, "cell 2 1"); JLabel lblEmax = new JLabel("Emax:"); lblEmax.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblEmax, "cell 0 2,alignx left"); JFormattedTextField ftxtEmax = new JFormattedTextField(); ftxtEmax.setColumns(5); ftxtEmax.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(ftxtEmax, "cell 1 2,alignx left"); JLabel lblEmaxUnit = new JLabel("cm/s"); lblEmaxUnit.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblEmaxUnit, "cell 2 2"); JLabel lblAMax = new JLabel("Amax:"); lblAMax.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblAMax, "cell 0 3,alignx left"); JFormattedTextField ftxtAMax = new JFormattedTextField(); ftxtAMax.setColumns(5); ftxtAMax.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(ftxtAMax, "cell 1 3,alignx left"); JLabel lblAMaxUnit = new JLabel("cm/s"); lblAMaxUnit.setFont(new Font("Tahoma", Font.PLAIN, 14)); pnlValues.add(lblAMaxUnit, "cell 2 3"); JPanel pnlPicture = new JPanel(); splitPane.setRightComponent(pnlPicture); pnlPicture.setLayout(new BorderLayout(0, 0)); } protected void setPGMeanListener(PropertyChangeListener l) { ftxtPGMean.addPropertyChangeListener(l); } }
true
c1f603fba73a08a7e142aec01f68e007c304d68f
Java
jackle1/Graph-ADT
/src/main/java/ca/ubc/ece/cpen221/graphs/two/ai/BearAI.java
UTF-8
539
2.453125
2
[]
no_license
package ca.ubc.ece.cpen221.graphs.two.ai; import ca.ubc.ece.cpen221.graphs.two.ArenaWorld; import ca.ubc.ece.cpen221.graphs.two.commands.Command; import ca.ubc.ece.cpen221.graphs.two.commands.WaitCommand; import ca.ubc.ece.cpen221.graphs.two.items.animals.ArenaAnimal; public class BearAI extends AbstractAI implements AI{ //UNUSED, bears just use the default AreanAnimalAI public BearAI() { } @Override public Command getNextAction(ArenaWorld world, ArenaAnimal animal) { return new WaitCommand(); } }
true
85d2076620305cae5875f0a434ea7dbb86c421ec
Java
yuexiaoyi/javademo
/src/main/java/com/lxy/innerClass/AnonymousClassTest.java
UTF-8
1,162
3.765625
4
[]
no_license
package com.lxy.innerClass; /** * 匿名类通过抽象类实现 */ abstract class Device{ private String name; public abstract double getPrice(); public Device(String name) { this.name = name; } public Device() { } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class AnonymousClassTest { public void test(Device d){ System.out.println("购买一个"+d.getName()+"花费"+d.getPrice()); } public static void main(String[] args) { AnonymousClassTest act = new AnonymousClassTest(); act.test(new Device("IBM") { @Override public double getPrice() { return 10000d; } }); Device d = new Device() { { System.out.println("匿名内部类的初始化..."); } @Override public double getPrice() { return 10000d; } public String getName() { return "MAC"; } }; act.test(d); } }
true
7338b430b56ac8bc5e1c816ef714f0e992977818
Java
thomascastleman/huffman-coding
/src/huffman/PriorityQueue.java
UTF-8
814
3.703125
4
[]
no_license
package huffman; import java.util.*; public class PriorityQueue extends Tree { public ArrayList<Node> objects = new ArrayList<Node>(); public HashMap<Node, Integer> nodeToPriority = new HashMap<Node, Integer>(); // enqueue node to priority queue public void enqueue(Node n, int priority) { // add entry to hashmap nodeToPriority.put(n, priority); for (int i = 0; i <= this.objects.size(); i++) { if (i == this.objects.size()) { this.objects.add(n); break; } else if (nodeToPriority.get(this.objects.get(i)) > priority) { this.objects.add(i, n); break; } } } // dequeue node from priority queue public Node dequeue() { if (this.objects.size() > 0) { Node n = this.objects.get(0); this.objects.remove(0); return n; } else { return null; } } }
true
4e77e36fa1be7d996b614af8e0d73e21268b74c7
Java
alexanderwerning/AILibs
/JAICore/jaicore-ml/src/main/java/ai/libs/jaicore/ml/learningcurve/extrapolation/ipl/InversePowerLawLearningCurve.java
UTF-8
3,298
3.015625
3
[]
no_license
package ai.libs.jaicore.ml.learningcurve.extrapolation.ipl; import java.math.BigDecimal; import org.apache.commons.math3.analysis.solvers.BrentSolver; import org.apache.commons.math3.analysis.solvers.UnivariateSolver; import org.apache.commons.math3.exception.NoBracketingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.ml.interfaces.AnalyticalLearningCurve; /** * Representation of a learning curve with the Inverse Power Law function, which * has three parameters named a, b and c. The function is f(x) = (1-a) - b * * x^c. O * * @author Lukas Brandt * */ public class InversePowerLawLearningCurve implements AnalyticalLearningCurve { private Logger logger = LoggerFactory.getLogger(InversePowerLawLearningCurve.class); private double a; private double b; private double c; public InversePowerLawLearningCurve(double a, double b, double c) { if (!(a > 0 && a < 1)) { throw new IllegalArgumentException("Parameter a has to be in (0,1)"); } if (!(c > -1 && c < 0)) { throw new IllegalArgumentException("Parameter c has to be in (-1,0)"); } this.a = a; this.b = b; this.c = c; } public InversePowerLawLearningCurve(InversePowerLawConfiguration configuration) { if (!(configuration.getA() > 0 && configuration.getA() < 1)) { throw new IllegalArgumentException("Parameter a has to be in (0,1)"); } if (!(configuration.getC() > -1 && configuration.getC() < 0)) { throw new IllegalArgumentException("Parameter c has to be in (-1,0)"); } this.a = configuration.getA(); this.b = configuration.getB(); this.c = configuration.getC(); } @Override public double getSaturationPoint(double epsilon) { if (epsilon <= 0) { throw new IllegalArgumentException("Parameter epsilon has to be >= 0"); } double n = this.c - 1.0d; double base = -(epsilon / (this.b * this.c)); return Math.pow(Math.E, Math.log(base) / n); } @Override public double getCurveValue(double x) { return (1.0d - this.a) - this.b * Math.pow(x, this.c); } @Override public double getDerivativeCurveValue(double x) { return (-this.b) * this.c * Math.pow(x, this.c - 1.0d); } @Override public String toString() { return "(1 - " + BigDecimal.valueOf(this.a).toPlainString() + ") - " + BigDecimal.valueOf(this.b).toPlainString() + " * x ^ " + BigDecimal.valueOf(this.c).toPlainString(); } @Override public double getConvergenceValue() { UnivariateSolver solver = new BrentSolver(0, 1.0d); double convergencePoint = -1; int upperIntervalBound = 10000; int retriesLeft = 8; while (retriesLeft > 0 && convergencePoint == -1) { try { convergencePoint = solver.solve(1000, x -> this.getDerivativeCurveValue(x) - 0.0000001, 1, upperIntervalBound); } catch (NoBracketingException e) { logger.warn(String.format("No solution could be found in interval [1,%d]", upperIntervalBound)); retriesLeft--; upperIntervalBound *= 2; } } if (convergencePoint == -1) { throw new RuntimeException( String.format("No solution could be found in interval [1,%d]", upperIntervalBound)); } return this.getCurveValue(convergencePoint); } public double getA() { return this.a; } public double getB() { return this.b; } public double getC() { return this.c; } }
true
744bb1b3a95c90262d5ab7c3d2e89033add7941a
Java
jacky99714/WebTravel
/WebTravel/src/jacky/controller/SceneImgServlet.java
UTF-8
1,480
2.265625
2
[]
no_license
package jacky.controller; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.bean.MemberBean; import model.bean.SceneBean; import model.dao.hibernate.SceneDAOHibernate; import model.service.MemberService; @WebServlet("/SceneImgServletq") public class SceneImgServlet extends HttpServlet { private static final long serialVersionUID = 1L; public SceneImgServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("image/gif; charset=UTF-8"); String sceneName = request.getParameter("sceneName"); MemberService ms = new MemberService(); ServletOutputStream out = response.getOutputStream(); if(sceneName!=null){ SceneBean scene =ms.selectScene(sceneName); byte[] photo = scene.getScenePhoto(); if(photo!=null){ out.write(photo); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
bb6b1161ac06293b6a6e840b911406b5503d83ca
Java
yxs19910622/ExpertQA
/ExpertQA/src/org/izhong/expert/util/StringUtil.java
UTF-8
2,064
2.890625
3
[]
no_license
package org.izhong.expert.util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtil { public static String UnicodeToUTF8(String strIn){ String strOut = null; if(strIn == null || strIn.trim().equals("")) { return strIn; } try { strOut=(new String(strIn.getBytes("iso-8859-1"),"UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return strOut; } public static String replaceEscape(String str) { return str.replace("&amp;", "&") .replace("&lt;", "<") .replace("&gt;", ">") .replace("&apos;", "'") .replace("&quot;", "\""); } public static String replaceNull(String str) { return str==null?"":str; } public static String UrlEncode(String str, String charset) { if(str == null) { return ""; } String s = ""; try { s = URLEncoder.encode(str, charset); } catch(Exception e) { } return s; } public static String UrlEncode(String str) { return UrlEncode(str, "utf-8"); } public static String UnicodeToChar(String unicodeString){ String rtn = ""; try{ String sss[] = unicodeString.split("a"); for (int i=sss.length-1;i>=0;i--){ char letter = (char)Integer.parseInt(sss[i]); rtn += new Character(letter).toString(); } }catch(Exception e){ e.printStackTrace(); } return rtn; } public static String CharToUnicode(String a){ String rtn = ""; try { if(null != a && a.length()>0){ for(int i=a.length()-1;i>=0;i--){ rtn += a.substring(i, i+1).hashCode(); rtn += i>0?"a":""; } } } catch (Exception e) { e.printStackTrace(); } return rtn; } public static String replaceBlank(String str) { String dest = ""; if (str!=null) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } }
true
0dd5d31fb1cf551acc72c693d072ffb55350f861
Java
Cicadaes/td
/bestseller/w-report-cloud/src/main/java/td/enterprise/service/TenantTagsCountService.java
UTF-8
11,255
1.828125
2
[]
no_license
package td.enterprise.service; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import td.enterprise.common.exception.BusinessException; import td.enterprise.common.util.DateUtil; import td.enterprise.common.util.RunDateUtil; import td.enterprise.dao.ProjectDao; import td.enterprise.dao.TenantTagsCountDao; import td.enterprise.entity.CityAppIntrestCount; import td.enterprise.entity.Project; import td.enterprise.entity.TenantTagsCount; import td.enterprise.page.CityAppIntrestCountPage; import td.enterprise.page.TenantTagsCountPage; import java.text.DecimalFormat; import java.util.*; /** * <br> * <b>功能:</b>人群设备 TenantTagsCountService<br> * <b>作者:</b>code generator<br> * <b>日期:</b> 2016-08-11 <br> * <b>版权所有:<b>Copyright(C) 2015, Beijing TendCloud Science & Technology Co., Ltd.<br> */ @Service("tenantTagsCountService") @Transactional(value = "transactionManager", readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public class TenantTagsCountService extends BaseService<TenantTagsCount> { public final static Logger logger = Logger.getLogger(TenantTagsCountService.class); public final static String pattern = "yyyy-MM-dd"; @Autowired private TenantTagsCountDao dao; @Autowired private CityAppIntrestCountService cityAppIntrestCountService; @Autowired private ProjectDao projectDao; @Autowired private CrowdService crowdService; public TenantTagsCountDao getDao() { return dao; } /** * @param params * @return */ public List<TenantTagsCount> selectForRadar(Map params) { params.put("startDate", null); params.put("endDate", null); List<TenantTagsCount> result = getDao().selectForRadar(params); int peopleNum = crowdService.getAllCount(params); if (result.size() == 0) { TenantTagsCountPage page = new TenantTagsCountPage(); page.setProjectId((Integer) params.get("projectId")); page.setCrowdId((Integer) params.get("crowdId")); // page.setCycleStatistics((Integer) params.get("cycleStatistics")); page.setRunDate((String) params.get("runDate")); page = filter(page); // params.put("cycleStatistics", page.getCycleStatistics()); params.put("runDate", page.getRunDate()); result = getDao().selectForRadar(params); //顺推,拿到总人群数 peopleNum = crowdService.getAllCount(params); } if (result.size() != 0) { TenantTagsCount peopleTag = new TenantTagsCount(); peopleTag.setTagName("人群总数"); peopleTag.setTagCode("000000"); peopleTag.setMetricValue(peopleNum); result.add(peopleTag); } return result; } /** * 城市app提升度 * * @param params * @return */ public List<TenantTagsCount> selectAppPreference(Map params) { String runDate = (String) params.get("runDate"); List<TenantTagsCount> result = selectForRadar(params); Integer projectId = (Integer) params.get("projectId"); Project project = projectDao.selectByPrimaryKey(projectId); String cityName = project.getCity(); CityAppIntrestCountPage cityAppIntrestCountPage = new CityAppIntrestCountPage(); cityAppIntrestCountPage.setCityName(cityName); cityAppIntrestCountPage.setPageEnabled(false); cityAppIntrestCountPage.setRunDate(runDate); List<TenantTagsCount> tenantTagsCountList = new ArrayList<>(); List<CityAppIntrestCount> cityAppIntrestCountsList = cityAppIntrestCountService.queryListByPage(cityAppIntrestCountPage); Map<String, CityAppIntrestCount> cityTagDataMap = new HashMap<>(); for (CityAppIntrestCount cityAppIntrestCount : cityAppIntrestCountsList) { cityTagDataMap.put(cityAppIntrestCount.getTagName(), cityAppIntrestCount); } TenantTagsCount peopleTag = new TenantTagsCount(); Double peopleTagMetricValue = 0.0d; for (TenantTagsCount count : result) { if ("人群总数".equalsIgnoreCase(count.getTagName()) && "000000".equalsIgnoreCase(count.getTagCode())) { peopleTag = count; peopleTagMetricValue = Double.valueOf(count.getMetricValue()); } } TenantTagsCount tenantTagsCount = null; DecimalFormat decimalFormat = new DecimalFormat("#.##"); for (TenantTagsCount tenantTagsCountObj : result) { if (!"000000".equalsIgnoreCase(tenantTagsCountObj.getTagCode())) { tenantTagsCount = tenantTagsCountObj; Double tagCountMetricValue = Double.valueOf(tenantTagsCountObj.getMetricValue()); Double tagCountValue = peopleTagMetricValue == 0 ? 0.0d : (tagCountMetricValue / peopleTagMetricValue); if (cityTagDataMap.containsKey(tenantTagsCountObj.getTagName())) { CityAppIntrestCount cityAppIntrestCount = cityTagDataMap.get(tenantTagsCountObj.getTagName()); int cityAppInMetricValue = cityAppIntrestCount.getMetricValue(); Double dvalue = 0.0d; if (cityAppInMetricValue != 0) { logger.info(((tagCountValue * 100) / cityAppInMetricValue) + " , " + (((tagCountValue * 100) / cityAppInMetricValue) - 1)); dvalue = ((tagCountValue * 100) / cityAppInMetricValue) - 1.0d; } tenantTagsCount.setCityPreValue(decimalFormat.format(dvalue * 100)); } else { //没有匹配到,默认提升度为0 tenantTagsCount.setCityPreValue("0.0"); } tenantTagsCountList.add(tenantTagsCount); } } return tenantTagsCountList; } public List<TenantTagsCount> selectByCodesIn(Map params) { return getDao().selectByCodesIn(params); } public int deleteByParams(TenantTagsCount tenantTagsCount) { return getDao().deleteByParams(tenantTagsCount); } //去数据库中检索有数据的有效日期区间 private TenantTagsCountPage filter(TenantTagsCountPage page) { try { Map<String, String> map = new HashMap<>(); //runDate 是endDate的前一天 Date runDate = DateUtil.format(page.getRunDate(), pattern); map = getValiableRunDate(runDate, page.getCycleStatistics(), page.getTenantId(), page.getProjectId(), page.getCrowdId()); if (map.size() > 0) { //page.setStartDate(map.get("startDate")); //page.setEndDate(map.get("endDate")); page.setRunDate(map.get("runDate")); // if (map.containsKey("cycleStatistics")) { // page.setCycleStatistics(Integer.valueOf(map.get("cycleStatistics"))); // } logger.info(" ####### filter之后 runDate=" + map.get("runDate") + " #######"); } } catch (Exception e) { logger.error("getValiableRunDate方法异常, "); } return page; } @SuppressWarnings("finally") public Map<String, String> getValiableRunDate(Date runDate, Integer cycleStatistics, String tenantId, int projectId, int crowdId) { TenantTagsCountPage page = new TenantTagsCountPage(); Map<String, String> map = new HashMap<>(); //map.put("startDate", sdf.format(startDate)); //map.put("endDate", sdf.format(endDate)); try { int dateLength = cycleStatistics; if (dateLength != 30 && dateLength != 60 && dateLength != 90 && dateLength != 180) { dateLength = RunDateUtil.getInstance().getCycleStatistics(dateLength); // map.put("cycleStatistics", String.valueOf(dateLength)); } TenantTagsCountPage tenantJobHousingCountPage = new TenantTagsCountPage(); tenantJobHousingCountPage.setRunDate(DateUtil.format(runDate, pattern)); tenantJobHousingCountPage.setCycleStatistics(dateLength); tenantJobHousingCountPage.setCrowdId(crowdId); tenantJobHousingCountPage.setProjectId(projectId); tenantJobHousingCountPage.setTenantId(tenantId); //查找同等计算周期下,计算日期在当前参数run_date之前记录 TenantTagsCount count = dao.queryLatestRow(tenantJobHousingCountPage); if (count != null) { //map.put("startDate", count.getStartDate()); //map.put("endDate", count.getEndDate()); map.put("runDate", count.getRunDate()); // map.put("cycleStatistics", String.valueOf(dateLength)); } } catch (Exception e) { throw new BusinessException(e); } finally { return map; } } public void queryAndInsertSum(String parentProjectId, String runDate) { TenantTagsCountPage page = new TenantTagsCountPage(); page.setProjectId(Integer.parseInt(parentProjectId)); page.setRunDate(runDate); List<TenantTagsCount> list = dao.queryChildrenSum(page); dao.batchDeleteByProjectAndDate(page); if (null != list && list.size() > 0) { int pointsDataLimit = 1000;//限制条数 int size = list.size(); if (pointsDataLimit < size) { int part = size / pointsDataLimit;//分批数 for (int i = 0; i < part; i++) { //1000条 List<TenantTagsCount> listTmp = list.subList(0, pointsDataLimit); batchInsert(listTmp, parentProjectId, runDate); //移除 list.subList(0, pointsDataLimit).clear(); } if (!list.isEmpty()) { batchInsert(list, parentProjectId, runDate); } } else { batchInsert(list, parentProjectId, runDate); } } } private void batchInsert(List<TenantTagsCount> list, String parentProjectId, String runDate) { for (TenantTagsCount tenantTagsCount : list) { tenantTagsCount.setProjectId(Integer.parseInt(parentProjectId)); tenantTagsCount.setRunDate(runDate); } dao.batchInsert(list); } public void batchSelectAndInsert(String parentProjectId, String runDate) { TenantTagsCountPage page = new TenantTagsCountPage(); page.setProjectId(Integer.parseInt(parentProjectId)); page.setRunDate(runDate); try { dao.batchDeleteByProjectAndDate(page); dao.batchSelectAndInsert(page); } catch (Exception e) { e.printStackTrace(); } } }
true
bbfcfa62789b7a161e15a1dcf141bc30c730e90b
Java
maliszewski/agamobile
/app/src/main/java/br/com/agafarma/agamobile/Data/LoginDAO.java
UTF-8
3,803
2.15625
2
[]
no_license
package br.com.agafarma.agamobile.Data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import br.com.agafarma.agamobile.Model.UsuarioModel; public class LoginDAO { private static final String DEBUG_TAG = "LoginDAO"; private SQLiteDatabase bd; private Context context; public LoginDAO(Context paramContext) { context = paramContext; Abrir(); } private void Abrir() { if (bd == null || !bd.isOpen()) { bd = DB.getInstance(context).getWritableDatabase(); bd.enableWriteAheadLogging(); } } private void Fechar() { if (bd == null && bd.isOpen()) { bd.close(); } } public UsuarioModel Buscar() { UsuarioModel localObject = new UsuarioModel(); Abrir(); Cursor localCursor = this.bd.query("login", DB.colunaLogin, null, null, null, null, null); Fechar(); if (localCursor.getCount() > 0) { localCursor.moveToFirst(); do { ((UsuarioModel) localObject).UsuarioId = localCursor.getInt(0); ((UsuarioModel) localObject).Apelido = localCursor.getString(1); ((UsuarioModel) localObject).CpfCnpj = localCursor.getString(2); ((UsuarioModel) localObject).Email = localCursor.getString(3); ((UsuarioModel) localObject).Senha = localCursor.getString(4); ((UsuarioModel) localObject).LojaId = localCursor.getInt(5); ((UsuarioModel) localObject).Administrativo = localCursor.getString(6); } while (localCursor.moveToNext()); } Log.i("LoginDAO", "Buscar OK"); return (UsuarioModel) localObject; } public void Deletar(UsuarioModel paramUsuarioModel) { StringBuilder localStringBuilder = new StringBuilder(); localStringBuilder.append("idusuario = "); localStringBuilder.append(paramUsuarioModel.UsuarioId); Abrir(); bd.delete("login", localStringBuilder.toString(), null); Fechar(); Log.i("LoginDAO", "Deletar OK"); } public void LimparApp() { Abrir(); bd.delete("login", null, null); Abrir(); bd.delete("questionarioperguntaresposta", null, null); Abrir(); bd.delete("questionariopergunta", null, null); Abrir(); bd.delete("questionario", null, null); Abrir(); bd.delete("questionarioresposta", null, null); Abrir(); bd.delete("questionariorespostafoto", null, null); Abrir(); bd.delete("aviso", null, null); Abrir(); bd.delete("mqttmensagem", null, null); Fechar(); Log.i("LoginDAO", "Sair OK"); } public void LogOff() { Abrir(); bd.delete("login", null, null); Fechar(); Log.i("LoginDAO", "Sair OK"); } public void Inserir(UsuarioModel paramUsuarioModel) { ContentValues localObject = new ContentValues(); localObject.put(DB.colunaLogin[0], Integer.valueOf(paramUsuarioModel.UsuarioId)); localObject.put(DB.colunaLogin[1], paramUsuarioModel.Apelido); localObject.put(DB.colunaLogin[2], paramUsuarioModel.CpfCnpj); localObject.put(DB.colunaLogin[3], paramUsuarioModel.Email); localObject.put(DB.colunaLogin[4], paramUsuarioModel.Senha); localObject.put(DB.colunaLogin[5], paramUsuarioModel.LojaId); localObject.put(DB.colunaLogin[6], paramUsuarioModel.Administrativo); Abrir(); this.bd.insert("login", null, (ContentValues) localObject); Fechar(); Log.i("LoginDAO", "Inserir OK"); } }
true
30e87b92d26ed5c7bea46c3d1673819830601125
Java
mischelll/Spring-Data
/Workshop - MVC/src/main/java/softuni/workshop/web/controllers/HomeController.java
UTF-8
1,418
2.3125
2
[]
no_license
package softuni.workshop.web.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import softuni.workshop.service.services.CompanyService; import softuni.workshop.service.services.EmployeeService; import softuni.workshop.service.services.ProjectService; @Controller public class HomeController extends BaseController { private final ProjectService projectService; private final EmployeeService employeeService; private final CompanyService companyService; public HomeController(ProjectService projectService, EmployeeService employeeService, CompanyService companyService) { this.projectService = projectService; this.employeeService = employeeService; this.companyService = companyService; } @GetMapping("/") public ModelAndView index() { return this.view("index"); } @GetMapping("/home") public ModelAndView home() { ModelAndView modelAndView = new ModelAndView("home"); boolean areImported = this.employeeService.areImported() && this.projectService.areImported() && this.companyService.areImported(); modelAndView.addObject("areImported", areImported); return modelAndView; } }
true
e6db238fa679e77fd524f62877c676ffce8a34b3
Java
zeyin1/ZEYIN
/src/main/java/com/example/zeyin/algorithm/leetCode/leetcode456.java
UTF-8
982
3.265625
3
[]
no_license
package com.example.zeyin.algorithm.leetCode; import java.util.Stack; /** * @Description: 用一句话描述 * @Author: zeyin * @Date: 2020年11月29日 15:53 * @Modify: */ public class leetcode456 { public boolean find132pattern(int[] nums) { if (nums.length < 3) { return false; } int second = Integer.MIN_VALUE; Stack<Integer> stack = new Stack<>(); stack.add(nums[nums.length - 1]); //从右到左,找到次大的元素 for (int i = nums.length - 2; i >= 0; i--) { //较小元素(左侧) if (nums[i] < second) { return true; } else { while (!stack.isEmpty() && nums[i] > stack.peek()) { //次大元素 second = Math.max(stack.pop(), second); } //最大元素 stack.push(nums[i]); } } return false; } }
true
1e4d55fb974e1a51ebdeb39777128701bb39d4b9
Java
grantlopresti/cs308-parser-parser
/src/slogo/exceptions/DeprecationException.java
UTF-8
679
2.734375
3
[ "MIT" ]
permissive
package slogo.exceptions; import slogo.visualcontroller.ErrorSeverity; public class DeprecationException extends RuntimeException { protected static final ErrorSeverity myErrorSeverity = ErrorSeverity.CRITICAL; protected String myString; private static final int SLEEP_TIME = 10000; public DeprecationException() { super(); } public DeprecationException(String message) { super(message); this.myString = message; } public ErrorSeverity getErrorSeverity() { return myErrorSeverity; } public String getMessage() { return this.myString; } public int getSleep() { return SLEEP_TIME; } }
true
9f3fec84edc44a683174f5c10addca9d64982bfb
Java
maciekb05/Advanced-Indoor-Microlocation
/src/maps/ParseScene.java
UTF-8
2,755
2.65625
3
[]
no_license
package maps; import beacons.Beacon; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.util.LinkedList; public class ParseScene { private LinkedList<Obstacle> obstacles; private LinkedList<Beacon> beacons; private Document doc; private String path = "./src/files/firstmap.fxml"; public void parseObstacles(){ try { loadFxml(path); obstacles = new LinkedList<>(); NodeList nList = doc.getElementsByTagName("Rectangle"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; obstacles.add(new Obstacle(eElement.getAttribute("layoutX"),eElement.getAttribute("layoutY"),eElement.getAttribute("width"),eElement.getAttribute("height"),eElement.getAttribute("fill"))); } } } catch (Exception e) { e.printStackTrace(); } } public void parseBeacons() { try { loadFxml(path); beacons = new LinkedList<>(); NodeList nList = doc.getElementsByTagName("Circle"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; beacons.add(new Beacon(eElement.getAttribute("layoutX"),eElement.getAttribute("layoutY"), eElement.getAttribute("id"))); } } } catch (SAXException | ParserConfigurationException | IOException e1) { e1.printStackTrace(); } } private void loadFxml(String path) throws IOException, SAXException, ParserConfigurationException { File fXmlFile = new File(path); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); } public void setPath(String path) { this.path = path; } public String getPath() { return path; } public LinkedList<Obstacle> getObstacles() { return obstacles; } public LinkedList<Beacon> getBeacons() { return beacons; } }
true
91fb29959c532ece61575bdeeafc6c6b7ed84318
Java
jsmmobi/CursoAndroidJamilton
/CardView/app/src/main/java/br/com/bitocean/cardview/MainActivity.java
UTF-8
1,817
2.28125
2
[]
no_license
package br.com.bitocean.cardview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.GridLayout; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.List; import br.com.bitocean.cardview.adapter.PostAdapter; import br.com.bitocean.cardview.model.Post; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private List<Post> postagens; private PostAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Define o Layout //RecyclerView.LayoutManager manager = new LinearLayoutManager(this); //LinearLayoutManager manager = new LinearLayoutManager(this); //manager.setOrientation(LinearLayout.HORIZONTAL); GridLayoutManager manager = new GridLayoutManager(getApplicationContext(),2); loadPosts(); // Define o Adapter adapter = new PostAdapter(postagens); recyclerView = (RecyclerView)findViewById(R.id.recyclerView); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); } private void loadPosts() { //String usuario, int imagem, String text postagens = new ArrayList<>(); postagens.add(new Post("Moisés Juvenal da silva",R.drawable.imagem1,"#ToFeliz")); postagens.add(new Post("Andre Silva Rosa",R.drawable.imagem2,"#PraAcabar")); postagens.add(new Post("Maria de Fátima Silva",R.drawable.imagem3,"#ToFeliz")); postagens.add(new Post("Cosme Juvenal da Silva",R.drawable.imagem4,"#ToFeliz")); } }
true
00aa626bcb2dcd2855e5291df46759aa356f7cf6
Java
taodaling/contest
/archive/unsorted/2020.06/2020.06.04 - Codeforces - Codeforces Round #647 (Div. 1) - Thanks, Algo Muse!/CJohnnyAndMegansNecklace.java
UTF-8
3,494
2.75
3
[]
no_license
package contest; import template.datastructure.DSU; import template.datastructure.MultiWayDeque; import template.io.FastInput; import template.io.FastOutput; import template.utils.Debug; import java.util.Arrays; public class CJohnnyAndMegansNecklace { //Debug debug = new Debug(false); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] balls = new int[n * 2]; in.populate(balls); // for (int x : balls) { // if ((x & ((1 << 3) - 1)) == 1) { // debug.debug("x", x); // } // } int bans = -1; int limit = 20; DSU dsu = new DSU(1 << limit); int[] cnts = new int[1 << limit]; for (int i = 0; i < limit; i++) { int mask = (1 << (i + 1)) - 1; dsu.reset(); Arrays.fill(cnts, 0); for (int j = 0; j < n * 2; j += 2) { dsu.merge(mask & balls[j], mask & balls[j + 1]); } boolean valid = true; for (int j = 2; valid && j < n * 2; j += 2) { int prev = balls[j - 2] & mask; int cur = balls[j] & mask; if (dsu.find(prev) != dsu.find(cur)) { valid = false; } } for (int x : balls) { cnts[x & mask]++; } for (int j = 0; valid && j < cnts.length; j++) { if ((cnts[j] & 1) == 1) { valid = false; } } if (!valid) { bans = i - 1; break; } bans = i; } if (bans == -1) { out.println(0); for (int i = 0; i < 2 * n; i++) { out.append(i + 1).append(' '); } return; } DSU ballDSU = new DSU(n); int[] stack = new int[1 << limit]; Arrays.fill(stack, -1); int[] match = new int[n * 2]; MultiWayDeque<int[]> groups = new MultiWayDeque<>(1 << limit, n); int mask = (1 << (1 + bans)) - 1; for (int i = 0; i < n * 2; i++) { int b = balls[i] & mask; if (stack[b] == -1) { stack[b] = i; } else { ballDSU.merge(i / 2, stack[b] / 2); groups.addLast(b, new int[]{i, stack[b]}); addEdge(match, i, stack[b]); stack[b] = -1; } } for (int i = 0; i < 1 << limit; i++) { if (groups.isEmpty(i)) { continue; } int[] top = groups.removeFirst(i); while (!groups.isEmpty(i)) { int[] head = groups.removeFirst(i); if (ballDSU.find(top[0] / 2) == ballDSU.find(head[0] / 2)) { continue; } ballDSU.merge(top[0] / 2, head[0] / 2); addEdge(match, top[0], head[0]); addEdge(match, top[1], head[1]); top[1] = head[0]; } } out.println(bans + 1); int index = 0; for (int i = 0; i < n; i++) { out.append(index + 1).append(' '); index ^= 1; out.append(index + 1).append(' '); index = match[index]; } } public void addEdge(int[] match, int i, int j) { match[i] = j; match[j] = i; } }
true
309df8da55afec256aace99350c44085506917eb
Java
biya-bi/rainbow
/rainbow-asset-explorer/rainbow-asset-explorer-impl/src/main/java/org/rainbow/asset/explorer/service/services/PurchaseOrderServiceImpl.java
UTF-8
8,652
2.109375
2
[]
no_license
package org.rainbow.asset.explorer.service.services; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.rainbow.asset.explorer.orm.entities.Location; import org.rainbow.asset.explorer.orm.entities.PurchaseOrder; import org.rainbow.asset.explorer.orm.entities.PurchaseOrderDetail; import org.rainbow.asset.explorer.orm.entities.PurchaseOrderStatus; import org.rainbow.asset.explorer.orm.entities.Vendor; import org.rainbow.asset.explorer.persistence.dao.VendorDao; import org.rainbow.asset.explorer.service.exceptions.DuplicatePurchaseOrderReferenceNumberException; import org.rainbow.asset.explorer.service.exceptions.PurchaseOrderCompleteQuantityOutOfRangeException; import org.rainbow.asset.explorer.service.exceptions.PurchaseOrderDetailsNullOrEmptyException; import org.rainbow.asset.explorer.service.exceptions.PurchaseOrderReadOnlyException; import org.rainbow.asset.explorer.service.exceptions.PurchaseOrderStatusTransitionException; import org.rainbow.asset.explorer.service.exceptions.VendorInactiveException; import org.rainbow.service.services.ServiceImpl; import org.rainbow.service.services.UpdateOperation; import org.rainbow.util.DaoUtil; public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrder> implements PurchaseOrderService { private VendorDao vendorDao; private InventoryManager inventoryManager; public PurchaseOrderServiceImpl() { } public VendorDao getVendorDao() { return vendorDao; } public void setVendorDao(VendorDao vendorDao) { this.vendorDao = vendorDao; } public InventoryManager getInventoryManager() { return inventoryManager; } public void setInventoryManager(InventoryManager inventoryManager) { this.inventoryManager = inventoryManager; } @Override public void approve(PurchaseOrder purchaseOrder) throws Exception { checkDependencies(); final PurchaseOrder persistentPurchaseOrder = this.getDao().findById(purchaseOrder.getId()); changeStatus(persistentPurchaseOrder, PurchaseOrderStatus.APPROVED); } @Override public void reject(PurchaseOrder purchaseOrder) throws Exception { checkDependencies(); final PurchaseOrder persistentPurchaseOrder = this.getDao().findById(purchaseOrder.getId()); changeStatus(persistentPurchaseOrder, PurchaseOrderStatus.REJECTED); } @Override public void complete(PurchaseOrder purchaseOrder, Location location, Map<Long, Short> productsCount) throws Exception { checkDependencies(); PurchaseOrder persistentPurchaseOrder = this.getDao().findById(purchaseOrder.getId()); List<PurchaseOrderDetail> details = getDetails(persistentPurchaseOrder.getId()); persistentPurchaseOrder.setDetails(details); validateComplete(persistentPurchaseOrder, productsCount); for (PurchaseOrderDetail detail : details) { Long productId = detail.getProduct().getId(); short receivedQuantity = 0; if (productsCount.containsKey(productId)) { receivedQuantity = productsCount.get(productId); } detail.setReceivedQuantity(receivedQuantity); detail.setRejectedQuantity((short) (detail.getOrderedQuantity() - receivedQuantity)); } changeStatus(persistentPurchaseOrder, PurchaseOrderStatus.COMPLETE); this.getInventoryManager().add(location.getId(), productsCount); } @Override public List<PurchaseOrderDetail> getDetails(Object purchaseOrderId) throws Exception { checkDependencies(); return this.getDao().findById(purchaseOrderId).getDetails(); } @Override protected void validate(PurchaseOrder purchaseOrder, UpdateOperation operation) throws Exception { switch (operation) { case CREATE: case UPDATE: final List<PurchaseOrderDetail> details = purchaseOrder.getDetails(); if (details == null || details.isEmpty() || details.stream().filter(x -> x.getOrderedQuantity() > 0).count() == 0) { throw new PurchaseOrderDetailsNullOrEmptyException(); } if (DaoUtil.isDuplicate(this.getDao(), "referenceNumber", purchaseOrder.getReferenceNumber(), purchaseOrder.getId(), operation)) { throw new DuplicatePurchaseOrderReferenceNumberException(purchaseOrder.getReferenceNumber()); } validateVendor(purchaseOrder); if (operation == UpdateOperation.UPDATE) { PurchaseOrderStatus oldStatus = getPersistentStatus(purchaseOrder.getId()); validatePersistentStatus(oldStatus, operation); // If no // exception is // thrown at // this point, // then the old // status is // PENDING. } break; case DELETE: PurchaseOrderStatus oldStatus = getPersistentStatus(purchaseOrder.getId()); validatePersistentStatus(oldStatus, operation); break; default: break; } } private void validateVendor(PurchaseOrder purchaseOrder) throws Exception { final Vendor vendor = purchaseOrder.getVendor(); if (vendor != null && vendor.getId() != null) { Vendor persistentVendor = this.getVendorDao().findById(vendor.getId()); if (!persistentVendor.isActive() && purchaseOrder.getStatus() != PurchaseOrderStatus.REJECTED) { throw new VendorInactiveException(); } } } private void validatePersistentStatus(PurchaseOrderStatus status, UpdateOperation operation) throws PurchaseOrderReadOnlyException { if (operation == UpdateOperation.UPDATE || operation == UpdateOperation.DELETE) { if (status != null && status != PurchaseOrderStatus.PENDING) { throw new PurchaseOrderReadOnlyException(status); } } } private PurchaseOrderStatus getPersistentStatus(Long purchaseOrderId) throws Exception { PurchaseOrder purchaseOrder = this.getDao().findById(purchaseOrderId); if (purchaseOrder != null) { return purchaseOrder.getStatus(); } return null; } private void changeStatus(PurchaseOrder purchaseOrder, PurchaseOrderStatus newStatus) throws Exception { PurchaseOrderStatus oldStatus = purchaseOrder.getStatus(); validateTransition(oldStatus, newStatus); purchaseOrder.setStatus(newStatus); validateVendor(purchaseOrder); this.getDao().update(purchaseOrder); } private void validateTransition(PurchaseOrderStatus oldStatus, PurchaseOrderStatus newStatus) throws PurchaseOrderStatusTransitionException { if (oldStatus == PurchaseOrderStatus.PENDING) { if (newStatus == PurchaseOrderStatus.PENDING || newStatus == PurchaseOrderStatus.APPROVED || newStatus == PurchaseOrderStatus.REJECTED) { return; } } else if (oldStatus == PurchaseOrderStatus.APPROVED) { if (newStatus == PurchaseOrderStatus.COMPLETE) { return; } } throw new PurchaseOrderStatusTransitionException(oldStatus, newStatus); } private void validateComplete(PurchaseOrder purchaseOrder, Map<Long, Short> productsCount) throws PurchaseOrderCompleteQuantityOutOfRangeException { List<Long> productIds = new ArrayList<>(productsCount.keySet()); List<PurchaseOrderDetail> details = purchaseOrder.getDetails(); for (Long productId : productIds) { short receivedQuantity = productsCount.get(productId); short orderedQuantity = 0; for (PurchaseOrderDetail detail : details) { if (detail.getProduct().getId().equals(productId)) { orderedQuantity += detail.getOrderedQuantity(); } } if (receivedQuantity < 0 || receivedQuantity > orderedQuantity) { throw new PurchaseOrderCompleteQuantityOutOfRangeException(purchaseOrder.getId(), productId, orderedQuantity, receivedQuantity); } } } @Override public void create(PurchaseOrder purchaseOrder) throws Exception { checkDependencies(); onCreate(purchaseOrder); super.create(purchaseOrder); } @Override public void create(List<PurchaseOrder> purchaseOrders) throws Exception { checkDependencies(); purchaseOrders.stream().forEach(x -> onCreate(x)); super.create(purchaseOrders); } private void onCreate(PurchaseOrder purchaseOrder) { purchaseOrder.setStatus(PurchaseOrderStatus.PENDING); if (purchaseOrder.getDetails() != null) { purchaseOrder.getDetails().stream().forEach(x -> { x.setReceivedQuantity((short) 0); x.setRejectedQuantity((short) 0); }); } } @Override protected void checkDependencies() { super.checkDependencies(); if (this.getVendorDao() == null) { throw new IllegalStateException("The vendor data access object cannot be null."); } if (this.getInventoryManager() == null) { throw new IllegalStateException("The inventory manager cannot be null."); } } }
true
3af71bbcc398b9fb2544f719fec2d1ac43d467ff
Java
hrahmadi71/MultiRefactor
/data/jrdf/jrdf-0.3.4.2/org/jrdf/graph/mem/GraphIterator.java
UTF-8
9,270
1.703125
2
[ "MIT" ]
permissive
/* * $Header: /cvsroot/jrdf/jrdf/src/org/jrdf/graph/mem/Attic/GraphIterator.java,v 1.9 2005/07/02 15:30:49 newmana Exp $ * $Revision: 1.9 $ * $Date: 2005/07/02 15:30:49 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 The JRDF Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * the JRDF Project (http://jrdf.sf.net/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The JRDF Project" and "JRDF" must not be used to endorse * or promote products derived from this software without prior written * permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "JRDF" * nor may "JRDF" appear in their names without prior written * permission of the JRDF Project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the JRDF Project. For more * information on JRDF, please see <http://jrdf.sourceforge.net/>. */ package org.jrdf.graph.mem; import org.jrdf.graph.Graph; import org.jrdf.graph.GraphElementFactory; import org.jrdf.graph.GraphException; import org.jrdf.util.ClosableIterator; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * An iterator that iterates over an entire graph. * Relies on internal iterators which iterate over all entries in * the first map, the maps it points to, and the sets they point to. * The itemIterator is used to indicate the current position. * It will always be set to return the next value until it reaches * the end of the graph. * * @author <a href="mailto:[email protected]">Paul Gearon</a> * @author Andrew Newman * * @version $Revision: 1.9 $ */ public class GraphIterator implements ClosableIterator { /** The iterator for the first index. */ private Iterator iterator; /** The iterator for the second index. */ private Iterator subIterator; /** The iterator for the third index. */ private Iterator itemIterator; /** The current element for the iterator on the first index. */ private Map.Entry firstEntry; /** The current element for the iterator on the second index. */ private Map.Entry secondEntry; /** The current subject predicate and object, last returned from next(). Only needed by the remove method. */ private Long[] currentNodes; /** The nodeFactory used to create the nodes to be returned in the triples. */ private GraphElementFactoryImpl nodeFactory; /** Handles the removal of nodes */ private GraphHandler handler; private boolean nextCalled = false; /** * Constructor. Sets up the internal iterators. * * @throws IllegalArgumentException Must be created with implementations from * the memory package. */ GraphIterator(Iterator newIterator, GraphElementFactory newNodeFactory, GraphHandler newHandler) { if (!(newNodeFactory instanceof GraphElementFactoryImpl)) { throw new IllegalArgumentException("Node factory must be a memory " + "implementation"); } // store the node factory nodeFactory = (GraphElementFactoryImpl) newNodeFactory; handler = newHandler; iterator = newIterator; } /** * Returns true if the iteration has more elements. * * @return <code>true</code> If there is an element to be read. */ public boolean hasNext() { // confirm we still have an item iterator, and that it has data available return null != itemIterator && itemIterator.hasNext() || null != subIterator && subIterator.hasNext() || null != iterator && iterator.hasNext(); } /** * Returns the next element in the iteration. * * @return the next element in the iteration. * @throws NoSuchElementException iteration has no more elements. */ public Object next() throws NoSuchElementException { if (null == iterator) { throw new NoSuchElementException(); } // move to the next position updatePosition(); if (null == iterator) { throw new NoSuchElementException(); } nextCalled = true; // get the next item Long third = (Long) itemIterator.next(); // construct the triple Long second = (Long) secondEntry.getKey(); Long first = (Long) firstEntry.getKey(); // get back the nodes for these IDs and uild the triple currentNodes = new Long[]{first, second, third}; return new TripleImpl((GraphElementFactoryImpl) nodeFactory, first, second, third); } /** * Helper method to move the iterators on to the next position. * If there is no next position then {@link #itemIterator itemIterator} * will be set to null, telling {@link #hasNext() hasNext} to return * <code>false</code>. */ private void updatePosition() { // progress to the next item if needed if (null == itemIterator || !itemIterator.hasNext()) { // the current iterator been exhausted if (null == subIterator || !subIterator.hasNext()) { // the subiterator has been exhausted if (!iterator.hasNext()) { // the main iterator has been exhausted // tell the iterator to finish iterator = null; return; } // move on the main iterator firstEntry = (Map.Entry) iterator.next(); // now get an iterator to the sub index map subIterator = ((Map) firstEntry.getValue()).entrySet().iterator(); assert subIterator.hasNext(); } // get the next entry of the sub index secondEntry = (Map.Entry) subIterator.next(); // get an interator to the next set from the sub index itemIterator = ((Set) secondEntry.getValue()).iterator(); assert itemIterator.hasNext(); } } /** * Implemented for java.util.Iterator. */ public void remove() { if (nextCalled && null != itemIterator) { itemIterator.remove(); // clean up the current index after the removal cleanIndex(); // now remove from the other 2 indexes removeFromNonCurrentIndex(); } else { throw new IllegalStateException("Next not called or beyond end of data"); } } /** * Checks if a removed item is the last of its type, and removes any associated subindexes if appropriate. */ private void cleanIndex() { // check if a set was cleaned out Set subGroup = (Set) secondEntry.getValue(); Map subIndex = (Map) firstEntry.getValue(); if (subGroup.isEmpty()) { // remove the entry for the set subIterator.remove(); // check if a subindex was cleaned out if (subIndex.isEmpty()) { // remove the subindex iterator.remove(); } } //handler.clean(secondEntry, subIterator, subIndex, ); } /** * Helper function for removal. This removes the current statement from the indexes which * the current iterator is not associated with. */ private void removeFromNonCurrentIndex() { try { // can instead use var here to determine how to delete, but this is more intuitive handler.remove(currentNodes); } catch (GraphException ge) { IllegalStateException illegalStateException = new IllegalStateException(); illegalStateException.setStackTrace(ge.getStackTrace()); throw illegalStateException; } } /** * Closes the iterator by freeing any resources that it current holds. * Nothing to be done for this class. * @return <code>true</code> indicating success. */ public boolean close() { return true; } }
true
ddde23596f03f76c466420aa905895f77ebbf9c6
Java
vsaueia/ssg-model
/src/main/java/br/com/tnt/ssg/cmt/bd/AgendamentoServicoBD.java
UTF-8
939
1.96875
2
[]
no_license
package br.com.tnt.ssg.cmt.bd; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import br.com.tnt.ssg.cmt.bo.AgendamentoServicoBO; import br.com.tnt.ssg.dmp.AgendamentoServico; @Stateless public class AgendamentoServicoBD { @EJB private AgendamentoServicoBO agendamentoServicoBO; public void save(AgendamentoServico agendamentoServico) throws Exception { agendamentoServicoBO.save(agendamentoServico); } public void remove(AgendamentoServico agendamentoServico) throws Exception { agendamentoServicoBO.remove(agendamentoServico); } public AgendamentoServico findById(Long id) throws Exception { return agendamentoServicoBO.findById(id); } public List<AgendamentoServico> findAll() throws Exception { return agendamentoServicoBO.findAll(); } public List<AgendamentoServico> findAll(AgendamentoServico criteria) throws Exception { return agendamentoServicoBO.findAll(criteria); } }
true
141aaa924542ea1e1ed9e1f15cf6ece634b806e7
Java
FilipKatana/V4-Zadatak-3
/main/Main.java
UTF-8
632
2.734375
3
[]
no_license
package main; import collections.ListaBrojeva; import procesi.Potrosac; import procesi.Proizvodjac; public class Main { public static void main(String[] args) throws InterruptedException { ListaBrojeva l = new ListaBrojeva(9); Proizvodjac pro = new Proizvodjac(l); Potrosac pot = new Potrosac(l); Thread t = new Thread(pro); Thread t2 = new Thread(pot); Thread t3 = new Thread(pro); Thread t4 = new Thread(pot); t.start(); t2.start(); t3.start(); t4.start(); t.join(); t2.join(); t3.join(); t4.join(); l.ispis(); System.out.println("Dužina: " + l.duzina()); } }
true
b7d28f6b8330b0dee6d493b5d261f3667f77c58c
Java
runningrabbit1007/WiseWorksite2
/common-base/src/main/java/com/common/base/bean/pojo/BaseSaveFilePojo.java
UTF-8
344
1.789063
2
[]
no_license
package com.common.base.bean.pojo; import java.io.Serializable; /** * Created by Jack on 2016/5/19. * 文件存储信息对象 */ public class BaseSaveFilePojo implements Serializable { private static final long serialVersionUID = 1L; /**文件地址*/ public String savePath; /**文件名*/ public String saveName; }
true