blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
2463875f5a80bba5d1faa3ea6256948052d3757c
17246eb3952727d9b9ffa782a17d8f1f581bf6ac
/spyviewer/config/util/HexPanel.java
3189eb67385f028343005c40d95f2718d582b982
[]
no_license
subirsarkar/swdev-cdf
564545a48973acadbc5a7227cd4fc7c62235d3be
3f98ebeecee2f7e5c6d000bbe9b040daf3e62ba4
refs/heads/master
2020-02-26T16:28:34.863999
2015-07-06T19:00:31
2015-07-06T19:00:31
38,607,673
0
0
null
null
null
null
UTF-8
Java
false
false
2,908
java
package config.util; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingConstants; import java.awt.Color; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; /** * Component subclassing JPanel, containing a JLabel ("0x") and a JHaxField. * @Author Th.Speer * @Version 0.1 */ public class HexPanel extends JPanel { private JHexField hexField; private JLabel hexLabel; /** * Constructs a new TextField. * The Hex field is empty */ public HexPanel() { super(); hexField = new JHexField(); finishPanel(); } /** * Constructs a new HexPanel. * The Hex field is initialized with the specified text. */ public HexPanel(String string) { super(); hexField = new JHexField(string); finishPanel(); } /** * Constructs a new empty HexPanel. * The Hex field is constructed with the specified number of columns. */ public HexPanel(int columns) { super(); hexField = new JHexField(columns); finishPanel(); } /** * Constructs a new HexPanel. * The Hex field is initialized with the specified text and columns. */ public HexPanel(String string, int columns) { super(); hexField = new JHexField(string, columns); finishPanel(); } /** * Constructs a new HexPanel. * The Hex field is initialized with the specified number and columns. */ public HexPanel(int content, int columns) { super(); hexField = new JHexField(Integer.toHexString(content), columns); finishPanel(); } private void finishPanel() { hexLabel = new JLabel("0x", SwingConstants.LEFT); hexLabel.setForeground(Color.black); hexField.setHorizontalAlignment(JTextField.RIGHT); // setLayout(new FlowLayout()); // add("West", hexLabel); // add("East", hexField); GridBagLayout gridbag2 = new GridBagLayout(); setLayout(gridbag2); GridBagConstraints GBC = new GridBagConstraints(); Tools.buildConstraints(GBC,0,0,1,1,0.,0.,GBC.EAST,GBC.NONE); gridbag2.setConstraints(hexLabel,GBC); Tools.buildConstraints(GBC,1,0,1,1,0.,0.,GBC.WEST,GBC.NONE); gridbag2.setConstraints(hexField,GBC); add(hexLabel); add(hexField); } /** * This method returns the JHexField, which can then be used with all * the JHexField methods * @returns The JHexField contained in the Panel. */ public JHexField getHexField() { return hexField; } public int getInt() { return hexField.getInt(); } public void setInt(int number) { hexField.setText(Integer.toHexString(number)); } public static void main(String args[]) { JFrame f = new JFrame("Hex Panel"); HexPanel essaih = new HexPanel("fa123", 7); f.getContentPane().add(essaih); f.setSize(100, 100); f.setVisible(true); } }
[ "Subir.Sarkar@cern.ch mailto:Subir.Sarkar@cern.ch" ]
Subir.Sarkar@cern.ch mailto:Subir.Sarkar@cern.ch
0a6399c483bccb9c17ce0afa7a0d0cf2a643f11f
b8026454363dd923797f9389ae1dacc0feae856f
/spring_workspace/spring_aop10_anno_hw/src/spring_aop10_anno_hw/TestMain.java
95f6055a72953b96a091666b820c628be57e011e
[]
no_license
poscoun/Goott_SPRING
269b50277783ab076d6c6bac5bf01b5859f0ca20
271fc71988f5341c9bd79ee5025fef705d730e53
refs/heads/master
2023-03-27T10:43:54.955569
2021-03-26T08:35:28
2021-03-26T08:35:28
348,384,550
0
0
null
null
null
null
UTF-8
Java
false
false
370
java
package spring_aop10_anno_hw; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; public class TestMain { public static void main(String[] args) { ApplicationContext ctx = new GenericXmlApplicationContext("app.xml"); Weapon w = ctx.getBean("w", Weapon.class); w.fire(); } }
[ "poscoun@gmail.com" ]
poscoun@gmail.com
7f202705e4de0da35e92fb6580829adb1aa69a91
044ffe8d27ffbdd49b468a9b9f01109832c536b8
/src/dao/GestionDao.java
9f602199d3e0691b1699b97842c1ad3459858e22
[]
no_license
BenjaminBoutrois/streams_expr-lambda_couche
9da4bff301ccf8123ed9aff0a4029c3ef3c10257
414199ed10fd922be124ca2868ce3c91e4550985
refs/heads/master
2021-05-16T22:53:16.573439
2020-03-27T19:07:13
2020-03-27T19:07:13
250,503,672
0
0
null
null
null
null
ISO-8859-1
Java
false
false
7,976
java
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import metier.Etudiant; public class GestionDao { // Informations d'accès à la base de données static final String url = "jdbc:mysql://localhost/gestion_ecole?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; static final String login = "root"; static final String password = ""; static Connection connection = null; static Statement statement = null; static ResultSet rs = null; /** * Essaie de connecter l'utilisateur à la base de données. * @param email L'email de l'utilisateur. * @param mdp Le mot de passe de l'utilisateur. * @return */ public static String seConnecter(String email , String mdp) throws SQLException, ClassNotFoundException { String role = ""; // Etape 1 : Chargement du driver Class.forName("com.mysql.cj.jdbc.Driver"); // Etape 2 : Récupération de la connexion connection = DriverManager.getConnection(url, login, password); // Etape 3 : Création d'un statement statement = connection.createStatement(); String sql = "Select * FROM Enseignant WHERE mail ='" + email + "' AND mdp ='" + mdp + "'"; // Etape 4 : Exécution requête rs = statement.executeQuery(sql); if(rs.next()) role = rs.getString("role"); else role = "incorrect"; // Etape 5 : Libérer ressources de la mémoire connection.close(); statement.close(); return role; } /*** * Crée un étudiant dans la base de données. * @param étudiant L'objet étudiant à créer. * @return L'étudiant créé. */ public static Etudiant creerEtudiant(Etudiant etudiant) throws SQLException, ClassNotFoundException { // Etape 1 : Chargement du driver Class.forName("com.mysql.cj.jdbc.Driver"); // Etape 2 : Récupération de la connexion connection = DriverManager.getConnection(url, login, password); // Etape 3 : Création d'un statement statement = connection.createStatement(); String sql = "INSERT INTO Etudiant(id, nom, prenom, mail, adresse, numero, dateNaissance) " + "VALUES ('" + Math.random() * (100000 - 1) + "','" + etudiant.getNom() + "','" + etudiant.getPrenom() + "','" + etudiant.getMail() + "','" + etudiant.getAdresse() + "','" + etudiant.getTelephone() + "','" + etudiant.getDateNaissanceEtudiant() + "')"; // Etape 4 : Exécution requête statement.executeUpdate(sql); System.out.println("L'étudiant " + etudiant.getNom() + " " + etudiant.getPrenom() + " a été créé.\n"); // Etape 5 : Libérer ressources de la mémoire connection.close(); statement.close(); return new Etudiant(); } /*** * Affiche les informations d'un étudiant grâce à son email. * @param email Email de l'étudiant. */ public static void lireEtudiant(String email) throws SQLException, ClassNotFoundException { // Etape 1 : Chargement du driver Class.forName("com.mysql.cj.jdbc.Driver"); // Etape 2 : Récupération de la connexion connection = DriverManager.getConnection(url, login, password); // Etape 3 : Création d'un statement statement = connection.createStatement(); String sql ="SELECT * FROM Etudiant WHERE mail ='" + email + "'"; // Etape 4 : Exécution requête rs=statement.executeQuery(sql); if(rs.next()) { System.out.println("Nom : "+ rs.getString("nom")); System.out.println("Prenom : "+ rs.getString("prenom")); System.out.println("Mail : "+ rs.getString("mail")); System.out.println("Adresse : "+ rs.getString("adresse")); System.out.println("Numero : "+ rs.getString("numero")); System.out.println("dateNaissance : "+ rs.getString("dateNaissance")); } else System.out.println("Aucun étudiant n'a cet email.\n"); // Etape 5 : Libérer ressources de la mémoire connection.close(); statement.close(); } /** * Supprime un étudiant de la base de données. * @param email Email de l'étudiant. */ public static void supprimerEtudiant(String email) throws SQLException, ClassNotFoundException { int resultat; // Etape 1 : Chargement du driver Class.forName("com.mysql.cj.jdbc.Driver"); // Etape 2 : Récupération de la connexion connection = DriverManager.getConnection(url, login, password); // Etape 3 : Création d'un statement statement = connection.createStatement(); String sql = "DELETE FROM Etudiant WHERE mail ='"+email+"'"; // Etape 4 : Exécution requête resultat= statement.executeUpdate(sql); if(resultat == 0) System.out.println("Aucun étudiant ne possède cet email.\n"); else System.out.println("L'étudiant a bien été supprime.\n"); // Etape 5 : Libérer ressources de la mémoire connection.close(); statement.close(); } /** * Récupère la liste de l'ensemble des étudiants de la base de données. */ public static List<String> recupererListeEtudiants() throws SQLException, ClassNotFoundException { List<String> listeEtudiants = new ArrayList<String>(); // Etape 1 : Chargement du driver Class.forName("com.mysql.cj.jdbc.Driver"); // Etape 2 : Récupération de la connexion connection = DriverManager.getConnection(url, login, password); // Etape 3 : Création d'un statement statement = connection.createStatement(); String sql = "SELECT id, nom, prenom, mail FROM etudiant\n"; // Etape 4 : Exécution requête rs = statement.executeQuery(sql); if (rs.next() == false) System.out.println("Aucun étudiant trouvé.\n"); else while(rs.next()) listeEtudiants.add(rs.getString(1) + " | " + rs.getString(2) + " | " + rs.getString(3) + " | " + rs.getString(4)); // Etape 5 : Libérer ressources de la mémoire connection.close(); statement.close(); return listeEtudiants; } /** * Modifie l'adresse d'un étudiant. * @param email Email de l'étudiant. * @param nouvelleAdresse Nouvelle adresse de l'étudiant. */ public static void modifierAdresseEtudiant(String email, String nouvelleAdresse) throws SQLException, ClassNotFoundException { int resultat; // Etape 1 : Chargement du driver Class.forName("com.mysql.cj.jdbc.Driver"); // Etape 2 : Récupération de la connexion connection = DriverManager.getConnection(url, login, password); // Etape 3 : Création d'un statement statement = connection.createStatement(); String sql = "UPDATE Etudiant SET adresse= '" + nouvelleAdresse + "'WHERE mail ='" + email + "'"; // Etape 4 : Exécution requête resultat = statement.executeUpdate(sql); if (resultat == 0) System.out.println("Aucun étudiant ne possède cet id.\n"); else System.out.println("Nouvelle adresse mise à jour.\n"); // Etape 5 : Libérer ressources de la mémoire connection.close(); statement.close(); } /** * Associe un cours à un étudiant. * @param mailEtudiant Email de l'étudiant. * @param theme Theme du cours à associer. */ public static void associerCoursEtudiant(String mailEtudiant, String theme) throws SQLException, ClassNotFoundException { int resultat; // Etape 1 : Chargement du driver Class.forName("com.mysql.cj.jdbc.Driver"); // Etape 2 : Récupération de la connexion connection = DriverManager.getConnection(url, login, password); // Etape 3 : Création d'un statement statement = connection.createStatement(); String sql = "INSERT INTO CoursEtudiant " + "VALUES ('" + theme + "', '" + mailEtudiant + "')"; // Etape 4 : Exécution requête resultat = statement.executeUpdate(sql); if (resultat == 0) System.out.println("Aucun étudiant ne possède cet id.\n"); else System.out.println("Cours associé a l'étudiant.\n"); // Etape 5 : Libérer ressources de la mémoire connection.close(); statement.close(); } }
[ "benjamin.boutrois28@gmail.com" ]
benjamin.boutrois28@gmail.com
22724bbf09c3615aa3aa0e871b82e2f99b3d0abf
03383ad5702809dbf8ede7855d176d2a74535347
/app/src/androidTest/java/com/itheima/vrdemo/ExampleInstrumentedTest.java
2cd906a62b19c0fb13b252bf9986c99e5374fb06
[ "Apache-2.0" ]
permissive
RepoForks/VRDemo
c577bcf262c2d4c5ca9d18809919e063ef4b1d26
56d3d7674f3eabf2932b2feaaf1c7c8451be419e
refs/heads/master
2021-01-25T09:20:44.710553
2017-06-01T10:22:13
2017-06-01T10:22:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
740
java
package com.itheima.vrdemo; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.itheima.vrdemo", appContext.getPackageName()); } }
[ "526247082@qq.com" ]
526247082@qq.com
6cef9a93f5fac48ff4035974664ea813aa59d3b4
b1ee54d9c043f5ecb48749702ac8e9fe68494968
/spring-rabbitmq-template-demo/spring-rabbitmq-java/src/main/java/com/sim/RabbitMQConnection.java
fbede8891456906474222014dfe175a823285ab4
[ "Apache-2.0" ]
permissive
YuanSim/spring-design-pattern-demo
0d9cae69c05e1347b6a1771151dd15511e3cc432
8bcd680289e92c7316ab36818f5f47e848cb151e
refs/heads/master
2022-12-22T02:16:40.654146
2022-11-18T03:16:54
2022-11-18T03:16:54
230,190,569
2
3
Apache-2.0
2022-12-10T05:59:17
2019-12-26T03:46:56
Java
UTF-8
Java
false
false
943
java
package com.sim; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * @QQ交流群: 648741281 * @Email: 177300883312@163.com * @微信: londu19930418 * @Author: Simon.Mr * @Created 2020/4/23 */ public class RabbitMQConnection { /** * 获取链接 * @return * @throws IOException * @throws TimeoutException */ public static Connection getConnection() throws IOException, TimeoutException { //1.创建连接 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("118.31.123.232"); connectionFactory.setPort(5672); connectionFactory.setUsername("sim"); connectionFactory.setPassword("123456"); connectionFactory.setVirtualHost("mq-sim"); return connectionFactory.newConnection(); } }
[ "17730088312@163.com" ]
17730088312@163.com
e0063bd2b569ae258e61d9153082e779e8ca2518
f40839c3d2fdee784e55f31cbc4b1682a829a4de
/Lesson02/Counter/app/src/main/java/com/codingblocks/counter/MainActivity.java
f4599f47ddb85ac6375d5a4f721c18ed876bbb85
[]
no_license
abiraja2004/NoidaIndustrialTrainingAndroid2019
c2369723318fcce727172fa5eaa02e314754d17a
4fe17c0bb794aced66e982c3451c17445a48b451
refs/heads/master
2020-09-21T05:48:34.679057
2019-05-01T08:07:02
2019-05-01T08:07:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,042
java
package com.codingblocks.counter; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { //TAG should be different for different java classes public String TAG = getClass().getSimpleName(); int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void increment(View view) { count++; Log.e(TAG, "" + count); //Set the count to the text updateViews(count); } public void decrement(View view) { if (count < 0) count = 0; else count--; updateViews(count); } public void updateViews(int count) { TextView counterText = findViewById(R.id.countTextView); counterText.setText("" + count); } }
[ "harshit@pitech.app" ]
harshit@pitech.app
eb75807d50f36c34c0122c04af0f825476901e2e
a103cf4a89e76fb2a0cea9a9c55a771cb01818c6
/learncode/Chapter07/MethodExercise.java
5c50a8cbda0b1f0e0cc147b4fb799f7f90568f17
[]
no_license
kai5192/weikai
c356c78447ecb584a302452804e7b77e266f0eb9
f189dffd6c526f1643b5573ca222c76178ce87ed
refs/heads/master
2023-06-18T16:57:45.667609
2021-07-14T06:49:46
2021-07-14T06:49:46
359,752,322
1
0
null
null
null
null
UTF-8
Java
false
false
907
java
package learncode.Chapter07; public class MethodExercise { public static void main(String[] args){ //编写一个方法copyPerson,可以复制一个独立的Person对象返回复制的对象; //注意要求得到新对象和原来的对象是独立的对象,只是他们的属性相同。 Dog dog = new Dog(); dog.age = 5; dog.name = "大黄"; Dog copydog = (new CopyDog()).copyDog(dog); System.out.println(dog.name); System.out.println(copydog.name); copydog.name = "大黑"; System.out.println("修改一个之后:"); System.out.println(dog.name); System.out.println(copydog.name); } } class Dog{ int age; String name; } class CopyDog{ public Dog copyDog(Dog dog){ Dog dog1 = new Dog(); dog1.name = dog.name; dog1.age = dog.age; return dog1; } }
[ "kai5192@163.com" ]
kai5192@163.com
84b849e70545fbb2730312aec155661e82a6b234
de2a168cfb1676f12390725187e27c96e49ed378
/src/main/java/com/udemy/cursomc/domain/enums/EstadoPagamento.java
1592a77354229a2fd72224ebe1d13bd0ef84e20b
[]
no_license
Guilherme230308/springboot-ionic-backend
8d0e59d860c65a912a230c826cef7eb9434cfb0e
7657f548018bc2d6add9e61659de41fac8183157
refs/heads/master
2020-03-17T00:04:39.738694
2018-07-25T03:52:47
2018-07-25T03:52:47
133,102,721
0
0
null
null
null
null
UTF-8
Java
false
false
676
java
package com.udemy.cursomc.domain.enums; public enum EstadoPagamento { PENDENTE(1, "Pendente"), QUITADO(2, "Quitado"), CANCELADO(3, "Cancelado"); private int cod; private String descricao; private EstadoPagamento(int cod, String descricao) { this.cod = cod; this.descricao = descricao; } public int getCod() { return cod; } public String getDescricao() { return descricao; } public static EstadoPagamento toEnum(Integer cod) { if (cod == null) { return null; } for (EstadoPagamento x : EstadoPagamento.values()) { if (cod.equals(x.getCod())) { return x; } } throw new IllegalArgumentException("Id inválido " + cod); } }
[ "guilherme_230308@hotmail.com" ]
guilherme_230308@hotmail.com
af2b49ad56689a1fb4c2bc975f644cabc2913fa4
ac83da059c433accb36f0fc07e1ab5de665ccc35
/parkingsk-parkinglot/src/main/java/com/skcc/parkingsk/parkinglot/kafka/consumer/ParkingLotConsumer.java
0a039882e441eae6f83ace283602a1ca2532a8f1
[]
no_license
seoyeon2924/parkingsk
69dae3e0c8ecab7a282e9de859c98825974a06e7
a52647e59f59f2143650532554cd3394eef3f6c3
refs/heads/master
2023-06-03T04:19:20.664407
2021-06-25T21:25:44
2021-06-25T21:25:44
380,356,358
1
0
null
null
null
null
UTF-8
Java
false
false
1,022
java
package com.skcc.parkingsk.parkinglot.kafka.consumer; import lombok.extern.slf4j.Slf4j; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Service; import com.skcc.parkingsk.parkinglot.controller.dto.MemberKafkaDTO; import com.skcc.parkingsk.parkinglot.controller.dto.ReviewKafkaDTO; @Service @Slf4j public class ParkingLotConsumer { //@KafkaListener(topics = "${spring.kafka.consumer.topic-name}") @KafkaListener(topics="member") public void processMemeber(MemberKafkaDTO memberDto) { log.info("********* ParkingLotConsumer : Kafka Listener : processMember *********"); log.debug(String.valueOf(memberDto)); // 이제 member를 받아서 할 것은 ? } //review가 등록되었을때 수신 @KafkaListener(topics="review") public void processReview(ReviewKafkaDTO reviewDto) { log.info("********* ParkingLotConsumer : Kafka Listener : processReview *********"); log.debug(String.valueOf(reviewDto)); // 이제 리뷰를 받아서 할 것은? } }
[ "seoyeon2924aa@gmail.com" ]
seoyeon2924aa@gmail.com
83920c6984c84f501570e873429c18d70e1fee9f
9fae695ff52c7394b53fdbfd1068d369f664c1ba
/app/src/main/java/uci/develops/wiraenergimobile/activity/FormRequestQuotationCustomerActivity.java
61d9b8721a03ce2b25db28a3bd9214c035276ee6
[]
no_license
uciarahito/ituitu
9cba446eacc89ff58c0304d91ec194e5fa67f862
5a0df909ab897e7b756eda8425844e04cd3cadcb
refs/heads/master
2021-05-03T22:31:42.079436
2016-12-30T04:31:27
2016-12-30T04:31:27
71,607,696
0
0
null
null
null
null
UTF-8
Java
false
false
24,093
java
package uci.develops.wiraenergimobile.activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import uci.develops.wiraenergimobile.R; import uci.develops.wiraenergimobile.adapter.CustomExpandableListAdapter; import uci.develops.wiraenergimobile.adapter.ItemRequestQuotationAdapter; import uci.develops.wiraenergimobile.fragment.navigation.NavigationManager; import uci.develops.wiraenergimobile.helper.DividerItemDecoration; import uci.develops.wiraenergimobile.helper.SharedPreferenceManager; import uci.develops.wiraenergimobile.model.ExpandableListDataSource; import uci.develops.wiraenergimobile.model.QuotationModel; import uci.develops.wiraenergimobile.model.UserXModel; import uci.develops.wiraenergimobile.response.UserResponse; import uci.develops.wiraenergimobile.service.RestClient; public class FormRequestQuotationCustomerActivity extends AppCompatActivity implements View.OnClickListener{ @BindView(R.id.imageTitleUp1) ImageView imageTitleUp1; @BindView(R.id.imageTitleUp2) ImageView imageTitleUp2; @BindView(R.id.imageTitle1) ImageView imageViewTitle1; @BindView(R.id.imageTitle2) ImageView imageViewTitle2; @BindView(R.id.linear_layout_title1) LinearLayout linearLayoutTitle1; @BindView(R.id.linear_layout_title2) LinearLayout linearLayoutTitle2; @BindView(R.id.linear_layout_content1) LinearLayout linearLayoutContent1; @BindView(R.id.linear_layout_content2) LinearLayout linearLayoutContent2; @BindView(R.id.linear_layout_container_quotation_shipping_address) LinearLayout linearLayoutContainer1; @BindView(R.id.linear_layout_container_quotation_billing_address) LinearLayout linearLayoutContainer2; @BindView(R.id.linear_layout_button_cancel) LinearLayout linearLayoutButtonCancel; @BindView(R.id.linear_layout_button_save_as_draft) LinearLayout linearLayoutButtonSaveAsDraft; @BindView(R.id.linear_layout_button_send) LinearLayout linearLayoutButtonSend; @BindView(R.id.editText_customer_note) EditText editText_customer_note; @BindView(R.id.button_add_item) Button button_add_item; @BindView(R.id.recycle_view) RecyclerView recyclerView; private ItemRequestQuotationAdapter itemRequestQuotationAdapter; boolean content1=false, content2=false; //utk nav drawer private DrawerLayout mDrawerLayout; private String[] items; private ExpandableListView mExpandableListView; private ExpandableListAdapter mExpandableListAdapter; private List<String> mExpandableListTitle; private NavigationManager mNavigationManager; private ActionBarDrawerToggle mDrawerToggle; private String mActivityTitle; private Map<String, List<String>> mExpandableListData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_form_request_quotation_customer); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ButterKnife.bind(this); initializeComponent(); navDrawer(); if (savedInstanceState == null) { selectFirstItemAsDefault(); } } private void initializeComponent(){ imageViewTitle1.setVisibility(View.VISIBLE); imageViewTitle2.setVisibility(View.VISIBLE); List<QuotationModel> quotationModelsList = new ArrayList<>(); itemRequestQuotationAdapter = new ItemRequestQuotationAdapter(FormRequestQuotationCustomerActivity.this, quotationModelsList); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(FormRequestQuotationCustomerActivity.this); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new DividerItemDecoration(FormRequestQuotationCustomerActivity.this, LinearLayoutManager.VERTICAL)); recyclerView.setAdapter(itemRequestQuotationAdapter); linearLayoutTitle1.setOnClickListener(this); linearLayoutTitle2.setOnClickListener(this); button_add_item.setOnClickListener(this); } @Override public void onClick(View v) { if (v == button_add_item){ showDialogAddItem(); } if(v == linearLayoutTitle1){ if(!content1){ imageViewTitle1.setVisibility(View.GONE); imageTitleUp1.setVisibility(View.VISIBLE); linearLayoutContent1.setVisibility(View.VISIBLE); linearLayoutContainer1.setVisibility(View.VISIBLE); content1=true; } else { imageViewTitle1.setVisibility(View.VISIBLE); imageTitleUp1.setVisibility(View.GONE); linearLayoutContent1.setVisibility(View.GONE); linearLayoutContainer1.setVisibility(View.GONE); content1=false; } } if(v == linearLayoutTitle2){ if(!content2){ imageViewTitle2.setVisibility(View.GONE); imageTitleUp2.setVisibility(View.VISIBLE); linearLayoutContent2.setVisibility(View.VISIBLE); linearLayoutContainer2.setVisibility(View.VISIBLE); content2=true; } else { imageViewTitle2.setVisibility(View.VISIBLE); imageTitleUp2.setVisibility(View.GONE); linearLayoutContent2.setVisibility(View.GONE); linearLayoutContainer2.setVisibility(View.GONE); content2=false; } } } //utk dialog add item private Spinner spinner_item, spinner_unit; private EditText editText_send_date, editText_quantity, editText_notes; private DatePickerDialog datePickerDialog; private Button button_save, button_cancel; Dialog dialog_add_item; private void showDialogAddItem() { dialog_add_item = new Dialog(FormRequestQuotationCustomerActivity.this); dialog_add_item.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog_add_item.setContentView(R.layout.custom_dialog_form_req_item_quotation_customer); spinner_item = ButterKnife.findById(dialog_add_item, R.id.spinner_item); spinner_unit = ButterKnife.findById(dialog_add_item, R.id.spinner_unit); editText_send_date = ButterKnife.findById(dialog_add_item, R.id.editText_send_date); editText_quantity = ButterKnife.findById(dialog_add_item, R.id.editText_quantity); editText_notes = ButterKnife.findById(dialog_add_item, R.id.editText_notes); button_save = ButterKnife.findById(dialog_add_item, R.id.button_save); button_cancel = ButterKnife.findById(dialog_add_item, R.id.button_cancel); List<String> listItem = new ArrayList<String>(); listItem.add("PCS"); listItem.add("Militer"); listItem.add("Liter"); listItem.add("Barrel"); ArrayAdapter<String> itemAdapter = new ArrayAdapter<String>(FormRequestQuotationCustomerActivity.this, R.layout.spinner_item, listItem); itemAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item); spinner_item.setAdapter(itemAdapter); List<String> listUnit = new ArrayList<String>(); listUnit.add("Kertas A4 Putih"); listUnit.add("Tinta Epson"); listUnit.add("Laptop Asus"); listUnit.add("Solar"); ArrayAdapter<String> unitAdapter = new ArrayAdapter<String>(FormRequestQuotationCustomerActivity.this, R.layout.spinner_item, listUnit); unitAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item); spinner_unit.setAdapter(unitAdapter); editText_send_date.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //utk send date final Calendar calendar = Calendar.getInstance(); int mYear = calendar.get(Calendar.YEAR); // current year int mMonth = calendar.get(Calendar.MONTH); // current month int mDay = calendar.get(Calendar.DAY_OF_MONTH); // current day // date picker dialog datePickerDialog = new DatePickerDialog(FormRequestQuotationCustomerActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // set day of month , month and year value in the edit text editText_send_date.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year); } }, mYear, mMonth, mDay); datePickerDialog.show(); } }); button_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog_add_item.dismiss(); } }); button_save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog_add_item.dismiss(); } }); DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager windowmanager = (WindowManager) FormRequestQuotationCustomerActivity.this.getSystemService(FormRequestQuotationCustomerActivity.this.WINDOW_SERVICE); windowmanager.getDefaultDisplay().getMetrics(displayMetrics); int deviceWidth = displayMetrics.widthPixels; int deviceHeight = displayMetrics.heightPixels; dialog_add_item.getWindow().setLayout(deviceWidth - 20, WindowManager.LayoutParams.WRAP_CONTENT); dialog_add_item.setCancelable(true); dialog_add_item.show(); } @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_main, 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(); Intent intentLogin, intentRegister; if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } private void selectFirstItemAsDefault() { if (mNavigationManager != null) { //String firstActionMovie = getResources().getStringArray(R.array.actionFilms)[0]; //mNavigationManager.showFragmentAction(firstActionMovie); //getSupportActionBar().setTitle(firstActionMovie); } } public void navDrawer() { mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mActivityTitle = getTitle().toString(); mExpandableListView = (ExpandableListView) mDrawerLayout.findViewById(R.id.navList); initItems(); LayoutInflater inflater = getLayoutInflater(); View listHeaderView; listHeaderView = inflater.inflate(R.layout.nav_header, null, false); mExpandableListView.addHeaderView(listHeaderView); ImageView imageView_profile = (ImageView) listHeaderView.findViewById(R.id.imageView_profile); final TextView textView_name = (TextView) listHeaderView.findViewById(R.id.textView_name); imageView_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("admin")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, ListCustomerActivity.class); startActivity(intent); } else if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("customer")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, FormCustomerActivity.class); startActivity(intent); } } }); Call<UserResponse> userResponseCall = RestClient.getRestClient().getUser("Bearer " + new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "token"), Integer.parseInt(new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "user_id"))); userResponseCall.enqueue(new Callback<UserResponse>() { @Override public void onResponse(Call<UserResponse> call, Response<UserResponse> response) { if (response.isSuccessful()) { String name = ""; UserXModel userXModel = new UserXModel(); userXModel = response.body().getData(); textView_name.setText(userXModel.getName() == null ? "" : userXModel.getName()); } } @Override public void onFailure(Call<UserResponse> call, Throwable t) { } }); mExpandableListData = ExpandableListDataSource.getData(this); List<String> rootMenu = new ArrayList<>(); if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("admin")) { rootMenu.add("Dashboard"); rootMenu.add("Customer"); rootMenu.add("Purchasing"); rootMenu.add("Sales"); rootMenu.add("Logout"); } else if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("customer")) { rootMenu.add("Dashboard"); rootMenu.add("Profile"); rootMenu.add("Sales"); rootMenu.add("Logout"); } else if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("")) { rootMenu.add("Logout"); } else if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("expedition")) { rootMenu.add("Dashboard"); rootMenu.add("Profile"); rootMenu.add("Delivery Order"); rootMenu.add("Logout"); } mExpandableListTitle = rootMenu; addDrawerItems(); setupDrawer(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } private void initItems() { items = ExpandableListDataSource.getArrayTitle(FormRequestQuotationCustomerActivity.this); } private void addDrawerItems() { mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData); mExpandableListView.setAdapter(mExpandableListAdapter); mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition)))) .get(childPosition).toString(); getSupportActionBar().setTitle(selectedItem); Toast.makeText(FormRequestQuotationCustomerActivity.this, "" + selectedItem, Toast.LENGTH_SHORT).show(); /* if (items[0].equals(mExpandableListTitle.get(groupPosition))) { mNavigationManager.showFragmentNavPurchasing(selectedItem); } else if (items[1].equals(mExpandableListTitle.get(groupPosition))) { mNavigationManager.showFragmentNavSales(selectedItem); } else { throw new IllegalArgumentException("Not supported fragment type"); }*/ //utk menu purchasing if (selectedItem.equals("Purchase Order [PO]")) { Log.e("Cekkkkkk", selectedItem + "qqqqqqqqqqqqqqqq"); Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, PurchaseOrderActivity.class); startActivity(intent); } else if (selectedItem.equals("Good Received [GR]")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, GoodReceivedActivity.class); startActivity(intent); } //utk menu sales if (selectedItem.equals("Quotation")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, SalesQuotationAdminActivity.class); startActivity(intent); } else if (selectedItem.equals("Sales Order [SO]")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, SalesOrderActivity.class); startActivity(intent); } else if (selectedItem.equals("Delivery Order [DO]")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, DeliveryOrderActivity.class); startActivity(intent); } else if (selectedItem.equals("Invoice")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, InvoiceActivity.class); startActivity(intent); } else if (selectedItem.equals("Payment")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, PaymentActivity.class); startActivity(intent); } mDrawerLayout.closeDrawer(GravityCompat.START); return false; } }); mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { String selected_item = getResources().getStringArray(R.array.general)[groupPosition]; if(new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("admin")){ selected_item = getResources().getStringArray(R.array.general)[groupPosition]; } else if(new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("customer")){ selected_item = getResources().getStringArray(R.array.general_customer)[groupPosition]; } else if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("expedition")){ selected_item = getResources().getStringArray(R.array.general_expedition)[groupPosition]; } else if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("")){ selected_item = getResources().getStringArray(R.array.general_guest)[groupPosition]; } if (selected_item.equals("Logout")) { logout(); } else if (selected_item.equals("Dashboard")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, HomeActivity.class); startActivity(intent); finish(); } else if (selected_item.equals("Customer")) { if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("admin")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, HomeActivity.class); startActivity(intent); } } else if (selected_item.equals("Profile")) { if (new SharedPreferenceManager().getPreferences(FormRequestQuotationCustomerActivity.this, "roles").equals("customer")) { Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, FormCustomerActivity.class); startActivity(intent); } } return false; } }); } private void logout() { new SharedPreferenceManager().setPreferences(FormRequestQuotationCustomerActivity.this, "is_login", ""); new SharedPreferenceManager().setPreferences(FormRequestQuotationCustomerActivity.this, "token", ""); new SharedPreferenceManager().setPreferences(FormRequestQuotationCustomerActivity.this, "customer_decode", ""); new SharedPreferenceManager().setPreferences(FormRequestQuotationCustomerActivity.this, "roles", ""); Intent intent = new Intent(FormRequestQuotationCustomerActivity.this, LoginActivity.class); startActivity(intent); finish(); } private void setupDrawer() { mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getSupportActionBar().setTitle(R.string.dashboard); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); getSupportActionBar().setTitle(mActivityTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerLayout.setDrawerListener(mDrawerToggle); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } }
[ "arahitolubis@gmail.com" ]
arahitolubis@gmail.com
a121028bf4b1d36afa47f4408ad50c22e0106f39
07b10fd7757e5b7a1da57cf700c17375db7f817f
/ImageViewEx/app/src/androidTest/java/com/example/kuno/imageviewex/ExampleInstrumentedTest.java
48977c8316af44b2a9371b156c13970625e6f9cb
[]
no_license
kuno2582/Android
485ac86dc0025a06bc7129309cc21a97216309fa
471be0d74ca609daabd0e1941d8b10f11fe1a4e4
refs/heads/master
2021-01-19T13:55:42.215374
2017-02-19T01:57:10
2017-02-19T01:57:10
82,427,800
0
0
null
null
null
null
UTF-8
Java
false
false
760
java
package com.example.kuno.imageviewex; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.kuno.imageviewex", appContext.getPackageName()); } }
[ "kuno9411@gmail.com" ]
kuno9411@gmail.com
521d2f379fef8318848e986d628f87b9ea0f77a8
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/23/23_7a64e55ffee1f77e5ef710d2e90dfd0e90510e61/DefaultOptimizer/23_7a64e55ffee1f77e5ef710d2e90dfd0e90510e61_DefaultOptimizer_t.java
12edd87d8ff891370f6b3dae95fb02ae750ef173
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
7,755
java
package com.shsrobotics.reinforcementlearning.optimizers; import com.shsrobotics.reinforcementlearning.util.DataPoint; /** * Optimize coordinates based on a Pattern Search algorithm. To use this class, * classes must extend it and provide a {@code double f(double[] input)} method. * Method calls should be made to {@code minimize()} and {@code maximize()} * only. Other members are public only for extension and implementation * purposes. * <p/> * @author Team 2412. */ public abstract class DefaultOptimizer implements Optimizer { /** * The number of variables to optimize. Data dimensions. */ private final int n; /** * How many times to run the algorithm */ private final int iterations; /** * Minimum variable values. Used to choose random starting points. */ private final double[] minimums; /** * Maximum Variable values. Used to choose random starting points. */ private final double[] maximums; /** * Step size for Pattern Search algorithm. Defaults to ten percent of * average variable range. */ private double[] PatternSearchStep; /** * Stores the default search step size. Defaults to a quarter of average * variable range, for a total range of a quarter of the search size. */ private double[] InitialStep; /** * Default step size fraction. */ private double stepSize = 0.25; /** * Create an optimizer. * <p/> * @param dimension the number of variables. * @param iterations how precise to maximize. * @param minimums the minimum domain values. * @param maximums the maximum domain values. */ public DefaultOptimizer(int iterations, double[] minimums, double[] maximums) { this.n = minimums.length; this.iterations = iterations; this.minimums = minimums; this.maximums = maximums; PatternSearchStep = new double[n]; InitialStep = new double[n]; //find step size for (int variable = 0; variable < n; variable++) { InitialStep[variable] = stepSize * (maximums[variable] - minimums[variable]); // twenty-five percent of the range } } @Override public final double[] maximize() { PatternSearchStep = InitialStep.clone(); return psOptimize(true); } @Override public final double[] minimize() { PatternSearchStep = InitialStep.clone(); return psOptimize(false); } /** * Uses a Pattern Search algorithm to find the coordinates that maximize the * function. * <p/> * @param maximize whether or not to maximize or minimize. If set to true, * the method will maximize. * @return the maximized coordinates. */ private double[] psOptimize(boolean maximize) { /* * Pattern vertices. Center is stored in 0, Left(k) is stored in k + 1, * and Right(k) is stored in (k + 1) + n. */ Point[] vertices = new Point[2 * n + 1]; int length = vertices.length; // center point placed randomly double[] center = rands(); for (int vertex = 0; vertex < length; vertex++) { if (vertex == 0) { vertices[vertex] = new Point(center, f(center)); } else { vertices[vertex] = new Point(center, 0.0); // saves computation time, as these are recalculated immediately } } // each variable for (int k = 0; k < n; k++) { int leftPoint = k + 1; int rightPoint = k + 1 + n; vertices[leftPoint].increment(k, -PatternSearchStep[k]); vertices[leftPoint].update(); vertices[rightPoint].increment(k, PatternSearchStep[k]); vertices[rightPoint].update(); } for (int i = 0; i < iterations; i++) { double best = vertices[0].value(); // best value int bestIndex = 0; // index of best value (currently center) for (int vertex = 1; vertex < length; vertex++) { if (better(vertices[vertex].value(), best, maximize)) { best = vertices[vertex].value(); bestIndex = vertex; } } if (bestIndex == 0) { // scale pattern for (int k = 0; k < n; k++) { PatternSearchStep[k] /= 2; // halve search size. int leftPoint = k + 1; int rightPoint = k + 1 + n; vertices[leftPoint].increment(k, PatternSearchStep[k]); // opposite direction vertices[leftPoint].update(); vertices[rightPoint].increment(k, -PatternSearchStep[k]); // opposite direction vertices[rightPoint].update(); } } else { // move pattern int variable = (bestIndex - 1) % n; // the variable to change int direction = (bestIndex - 1 - n >= 0) ? 1 : -1; // which way to move int oppositeVertex; // find which vertex index corresponds to the opposite vertex if (direction == 1) { oppositeVertex = variable + 1; } else { oppositeVertex = variable + 1 + n; } double change = direction * PatternSearchStep[variable]; // difference between best and center for (int vertex = 0; vertex < length; vertex++) { vertices[vertex].increment(variable, change); // save re-evaluation of function if (vertex == 0) { vertices[vertex].setValue(vertices[bestIndex].value()); } else if (vertex == oppositeVertex) { vertices[vertex].setValue(vertices[0].value()); } else { vertices[vertex].update(); // for new values } } } } return vertices[0].coordinates(); } /** * A data point. Used for optimization. */ public class Point extends DataPoint { /** * Create a point. * <p/> * @param coordinates the action coordinates. * @param value the Q-Value from the coordinates. */ public Point(double[] coordinates, double value) { super(coordinates, value); } /** * The data coordinates. */ public double[] coordinates() { return super.getInputs(); } /** * The data dependent variable (output). */ public double value() { return super.getOutputs()[0]; } /** * Update the {@code value} variable. */ public void update() { super.setOutput(0, f(super.getInputs())); } /** * Set the {@code value} variable. If the value is known, save the time * updating it. */ public void setValue(double value) { super.setOutput(0, value); } /** * Increment a coordinate by a specified amount. A call to * {@code update} is recommended afterwards. * <p/> * @param k the coordinate variable to change. * @param amount the amount to increment by. */ public void increment(int k, double amount) { double[] newCoordinates = super.getInputs().clone(); double newCoordinate = newCoordinates[k] + amount; if (newCoordinate > minimums[k] && newCoordinate < maximums[k]) { //in bounds setInput(k, newCoordinate); } } } /** * Find which double is better. Whether or not a variable is better is * determined by the maximize parameter. * <p/> * @param a the first value to test. * @param b the second value to test. * @param maximize whether or not to test if {@code a > b}. If false, tests * for * {@code a < b}. * @return True if {@code a} is better than {@code b}. */ private boolean better(double a, double b, boolean maximize) { if (maximize) { return a > b; } else { return a < b; } } /** * Fill an array with random values. * <p/> * @return The array. */ double[] rands() { double[] toReturn = new double[n]; double rangeScale = 2 * stepSize; for (int i = 0; i < n; i++) { double range = (maximums[i] - minimums[i]) * rangeScale; toReturn[i] = Math.random() * range + minimums[i] + range / 2; // generate random number in range } return toReturn; } @Override public abstract double f(double[] input); }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
396b5431b4956fd8de8a5efee59fea729518d49f
3e2eada3e92d3fa709f51e52be0dd78ba84bf1dc
/src/java/edu/cmu/ml/gnat/ground/EntityLink.java
17893706c8dbe4fca7a06afdd5693f2423371bdb
[ "Apache-2.0" ]
permissive
TeamCohen/Gnat
9eaceae0d513f0a0275a89e661308db2f6d4222f
908c4f2951dc585db848c14916e6d06f52e8c6a0
refs/heads/master
2021-01-17T14:22:02.393661
2017-09-12T17:46:30
2017-09-12T17:46:30
44,189,721
5
2
null
null
null
null
UTF-8
Java
false
false
859
java
package edu.cmu.ml.gnat.ground; public class EntityLink { private static final char TAB = '\t'; private String title; private String enType; private double score; private String mention; public String toString() { StringBuilder sb = new StringBuilder(title); sb.append(TAB).append(enType); sb.append(TAB).append(score); sb.append(TAB).append(mention); return sb.toString(); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getEnType() { return enType; } public void setEnType(String enType) { this.enType = enType; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public String getMention() { return mention; } public void setMention(String mention) { this.mention = mention; } }
[ "krivard@cs.cmu.edu" ]
krivard@cs.cmu.edu
29dfbeb789396504a8c023039931f4797fa15ab5
bb90881cb311a48b85847e492521f1b2d94302a2
/diverta2019/Main.java
47dfb28d1dce0474057f1e97dba410c3368895b5
[]
no_license
feiteng/atcoder
fc9c4c4f3224e8d7da8a8e8c4c5a972967a12ea1
0594b16ef455470e45a536771d87fa772cd23dc2
refs/heads/master
2020-12-11T20:39:30.043574
2020-02-28T16:45:38
2020-02-28T16:45:38
233,954,690
0
0
null
null
null
null
UTF-8
Java
false
false
7,356
java
// import java.math.*; import java.util.*; import java.io.*; public class Main { static BufferedReader in; static PrintWriter out = new PrintWriter(System.out); static String file = "../in"; static int test = 0; // 0 for local testing, 1 for std input static int inf = 1_000_000; void swap(int[]ary, int i, int j) { int t = ary[i]; ary[i] = ary[j]; ary[j] = t; } String[] split() throws Exception { return in.readLine().split(" "); } int readInt() throws Exception { return Integer.valueOf(in.readLine()); } int[] toIntArray() throws Exception { String[] sp = split(); int n = sp.length; int[] ary = new int[n]; for(int i = 0; i < n; i++) ary[i] = Integer.valueOf(sp[i]); return ary; } String reverse(String str) { return new StringBuilder(str).reverse().toString(); } public static void main(String[] args) throws Exception { int _k = Integer.valueOf("1"); if(test > 0) in = new BufferedReader(new InputStreamReader(System.in)); else in = new BufferedReader(new FileReader(file)); if(test < 0) {String[] str = in.readLine().split(" ");} /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ // System.out.println((-100 + 0) / 2); new Main().d(); out.flush(); } int mod = 1_000_000_007; long pow(long a, int pow) { long res = 1; while(pow > 0) { if(pow % 2 != 0) { res *= a; res %= mod; } a = a * a; a %= mod; pow /= 2; } return res; } long comb(int n, int k) { if(n < 0 || k < 0 || k > n) return 0; return (((f[n] * ff[k]) % mod) * f[n - k]) % mod; } long[] f = new long[2_000_010], ff = new long[2_000_010]; void f() throws Exception { } void e2(int n, int k) { for(int i = 0; i <= n; i++) { int a = i; int c = 0; while(a > 0) { if(a % 10 != 0) c++; a /= 10; } if(c == k) System.out.println(i); } } long ehelper(String str, int k) { int idx = 0; while(str.charAt(idx) == '0') idx++; str = str.substring(idx); char[] chs = str.toCharArray(); int n = chs.length; if(n < k) { // System.out.println(0); return 0; } long sum = 0; if(k == 1) { sum += chs[0] - '0'; sum += (n - 1) * 9; } if(k == 2) { int val = chs[0] - '0'; sum += (n - 1) * (n - 2) / 2 * 81; for(int i = 1; i < val; i++) { sum += (n - 1) * 9; } for(int i = 1; i < n; i++) { if(chs[i] != '0') { sum += chs[i] - '0'; sum += 9 * (n - i - 1); break; } } } if(k == 3) { int val = chs[0] - '0'; sum += (n - 1) * (n - 2) * (n - 3) / 6 * 729; for(int i = 1; i < val; i++) { sum += (n - 1) * (n - 2) / 2 * 81; } // System.out.println("..." +sum); sum += ehelper(str.substring(1), k - 1); } return sum; } void e() throws Exception { String str = in.readLine(); int k = readInt(); // e2(Integer.valueOf(str), k); System.out.println(ehelper(str, k)); } long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } void d() throws Exception { long n = Long.valueOf(in.readLine()); long sum = 0; for(long i = 1; i * i <= n; i++) { if(n % i == 0) { long r = n / i - 1; if(r == 0) continue; if(n / r == n % r) { sum += r; } } } out.println(sum); } int bs(int[] ary, long t) { int m = ary.length; int n = m; int count = 0; for(int i = 0; i < m - 1; i++) { // for each row // System.out.println(i); int lo = i + 1, hi = n - 1; long p1 = (long) ary[i]; while(lo < hi) { if(p1 > 0) { int mid = (lo + hi) / 2; long prod = p1 * ary[mid]; if(prod < t) lo = mid + 1; else hi = mid; } else { int mid = (lo + hi + 1) / 2; long prod = p1 * ary[mid]; if(prod < t) hi = mid - 1; else lo = mid; } } if(p1 == 0) { if(t > 0) count += n - i - 1; } else if(p1 < 0) { if(p1 * ary[lo] >= t) lo++; count += n - lo; // System.out.printf("%d %d %d \n", ary[i], lo, count); } else { // >= 0 if(ary[lo] * p1 > t) lo--; else if(ary[lo] * p1 < t) lo++; count += lo - i; // System.out.printf("%d %d %d\n", ary[i], i, lo - i); } } return count; } void c() throws Exception { long n = Long.valueOf(in.readLine()); int count = dfs(0, n, false); out.println(count); } int dfs(long val, long cap, boolean flag){ if(val > cap) return 0; // System.out.println(val); int re = 0; if(!flag) { long val2 = val; int c = 0; while(val2 > 0) { long rem = val2 % 10; val2 /= 10; if(rem == 3) c |= 1 << 0; if(rem == 5) c |= 1 << 1; if(rem == 7) c |= 1 << 2; } if(c == 7) { flag = true; } } if(flag) re++; re += dfs(val * 10 + 3, cap, flag); re += dfs(val * 10 + 5, cap, flag); re += dfs(val * 10 + 7, cap, flag); return re; } boolean containsDigit(int n, int set) { while(n > 0) { int r = n % 10; n /= 10; if((set & (1 << r)) != 0) return true; } return false; } void b() throws Exception { } void a() throws Exception { int[] ary = toIntArray(); Arrays.sort(ary); if(ary[0] == 5 && ary[1] == 5 && ary[2] == 7) { out.println("YES"); } else out.println("NO"); } }
[ "li.feiteng@gmail.com" ]
li.feiteng@gmail.com
927ce16e43232c27652e6ab50aec445c66b11b33
b01c9e3cc3bcf8c3a0d89cdef14f2e42936e62e3
/HelloSpringMVC09/src/main/java/com/tranvanbinh/service/CustomerService.java
58bf2517a3b444c6f49513851e0f2d50f5887e5b
[]
no_license
TranVanBinh29081998/TranVanBinh
15f5a76a97f48d317e2ff3b6459433b518b9e73c
73de811c2835f51e309fd4e30c9173f080eae1e1
refs/heads/master
2022-12-26T14:30:25.680611
2020-10-10T11:34:19
2020-10-10T11:34:19
300,857,874
0
0
null
null
null
null
UTF-8
Java
false
false
815
java
package com.tranvanbinh.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.tranvanbinh.dao.CustomerDAO; import com.tranvanbinh.entities.Customer; @Service @Transactional public class CustomerService { @Autowired private CustomerDAO customerDAO; public List<Customer> findAll() { return customerDAO. findAll(); } public Customer findById(int id) { return customerDAO. findById(id); } public void save(Customer customer) { customerDAO.save(customer); } public void update(Customer customer) { customerDAO.update(customer); } public void delete(int id) { customerDAO.delete(id); } }
[ "BINH@LAPTOP-8IMI94OR" ]
BINH@LAPTOP-8IMI94OR
4de45e0e79372ba1e650a25a5462679f8bf97946
44dfc001e42b3e4bfb10bfdb2fc07bfea0385532
/src/main/java/br/gov/serpro/pgt/backend/service/package-info.java
aee1baee13c011896cd3a02d6c6620c76bae8fc4
[]
no_license
davigadelha/pgt-backend
b08027df5dc26153a97c9969789694d01aa39cd3
a41ca7967dcd8de39380d8a3e075ca99ea82b1d2
refs/heads/main
2023-03-14T17:38:11.511537
2021-03-22T19:39:07
2021-03-22T19:39:07
350,434,624
0
0
null
2021-03-22T17:46:57
2021-03-22T17:39:53
Java
UTF-8
Java
false
false
75
java
/** * Service layer beans. */ package br.gov.serpro.pgt.backend.service;
[ "jhipster-bot@jhipster.tech" ]
jhipster-bot@jhipster.tech
fefca27f0ba0495f824ae99a932fe39cc3d653de
0edf2a73fb49ec5f2242865f2896ec4048ce79cd
/demo/src/main/java/com/example/demo/MainVerticle.java
d62cb52e87ba8e9f3136a3ed4c73c17d65c0c896
[]
no_license
rajeshcode/javacodes
ed1b0badff9023b622b6aee9c48712f9f7a46548
65f1f367d9ea09eb93ba566e7313a827c0c5e389
refs/heads/master
2021-01-10T05:38:47.786071
2018-05-30T07:07:57
2018-05-30T07:07:57
52,620,702
0
0
null
null
null
null
UTF-8
Java
false
false
541
java
package com.example.demo; import io.vertx.core.AbstractVerticle; public class MainVerticle extends AbstractVerticle { public static void main(String ... args) { } // @Override // public void start() throws Exception { // vertx.createHttpServer().requestHandler(req -> { // req.response() // .putHeader("content-type", "text/plain") // .end("Hello from Vert.x!"); // }).listen(8081); // System.out.println("HTTP server started on port 8080"); // } }
[ "rajec@ebay.com" ]
rajec@ebay.com
aea3057e127dda9a06b25bd8538d16ac930cf032
071a9fa7cfee0d1bf784f6591cd8d07c6b2a2495
/corpus/norm-class/sling/2409.java
117cfdc9d8cdcf80694789fecc911cde5ced102a
[ "MIT" ]
permissive
masud-technope/ACER-Replication-Package-ASE2017
41a7603117f01382e7e16f2f6ae899e6ff3ad6bb
cb7318a729eb1403004d451a164c851af2d81f7a
refs/heads/master
2021-06-21T02:19:43.602864
2021-02-13T20:44:09
2021-02-13T20:44:09
187,748,164
0
0
null
null
null
null
UTF-8
Java
false
false
1,256
java
licensed apache software foundation asf contributor license agreements notice file distributed work additional copyright ownership asf licenses file apache license version license file compliance license copy license http apache org licenses license required applicable law agreed writing software distributed license distributed basis warranties conditions kind express implied license specific language governing permissions limitations license org apache sling osgi obr java print writer printwriter java util map org osgi framework version package capability packagecapability capability string package name packagename version version package capability packagecapability map entry entry package name packagename string entry get key getkey string string map entry get value getvalue version version version parse version parseversion string get package name getpackagename package name packagename version get version getversion version serialize print writer printwriter string indent capability org apache felix upnp extra control ler controller version version capability print indent println capability print p printp indent package name packagename print p printp indent version version version to string tostring print indent println capability
[ "masudcseku@gmail.com" ]
masudcseku@gmail.com
803e08205b0d630a58d8561d85ccaeb991989926
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_ca3084f361acdab99b0e19e872302abd222708ae/Core/2_ca3084f361acdab99b0e19e872302abd222708ae_Core_t.java
80c02d47ebcac17ab7dd9e5b3f3771c711b607e5
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
31,548
java
/* * Sone - Core.java - Copyright © 2010 David Roden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.pterodactylus.sone.core; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.pterodactylus.sone.core.Options.DefaultOption; import net.pterodactylus.sone.core.Options.Option; import net.pterodactylus.sone.core.Options.OptionWatcher; import net.pterodactylus.sone.data.Post; import net.pterodactylus.sone.data.Profile; import net.pterodactylus.sone.data.Reply; import net.pterodactylus.sone.data.Sone; import net.pterodactylus.sone.freenet.wot.Identity; import net.pterodactylus.sone.freenet.wot.IdentityListener; import net.pterodactylus.sone.freenet.wot.IdentityManager; import net.pterodactylus.sone.freenet.wot.OwnIdentity; import net.pterodactylus.util.config.Configuration; import net.pterodactylus.util.config.ConfigurationException; import net.pterodactylus.util.logging.Logging; import net.pterodactylus.util.number.Numbers; import freenet.keys.FreenetURI; /** * The Sone core. * * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a> */ public class Core implements IdentityListener { /** * Enumeration for the possible states of a {@link Sone}. * * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a> */ public enum SoneStatus { /** The Sone is unknown, i.e. not yet downloaded. */ unknown, /** The Sone is idle, i.e. not being downloaded or inserted. */ idle, /** The Sone is currently being inserted. */ inserting, /** The Sone is currently being downloaded. */ downloading, } /** The logger. */ private static final Logger logger = Logging.getLogger(Core.class); /** The options. */ private final Options options = new Options(); /** The configuration. */ private final Configuration configuration; /** The identity manager. */ private final IdentityManager identityManager; /** Interface to freenet. */ private final FreenetInterface freenetInterface; /** The Sone downloader. */ private final SoneDownloader soneDownloader; /** The Sones’ statuses. */ /* synchronize access on itself. */ private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>(); /** Sone inserters. */ /* synchronize access on this on localSones. */ private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>(); /** All local Sones. */ /* synchronize access on this on itself. */ private Map<String, Sone> localSones = new HashMap<String, Sone>(); /** All remote Sones. */ /* synchronize access on this on itself. */ private Map<String, Sone> remoteSones = new HashMap<String, Sone>(); /** All posts. */ private Map<String, Post> posts = new HashMap<String, Post>(); /** All replies. */ private Map<String, Reply> replies = new HashMap<String, Reply>(); /** * Creates a new core. * * @param configuration * The configuration of the core * @param freenetInterface * The freenet interface * @param identityManager * The identity manager */ public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) { this.configuration = configuration; this.freenetInterface = freenetInterface; this.identityManager = identityManager; this.soneDownloader = new SoneDownloader(this, freenetInterface); } // // ACCESSORS // /** * Returns the options used by the core. * * @return The options of the core */ public Options getOptions() { return options; } /** * Returns the identity manager used by the core. * * @return The identity manager */ public IdentityManager getIdentityManager() { return identityManager; } /** * Returns the status of the given Sone. * * @param sone * The Sone to get the status for * @return The status of the Sone */ public SoneStatus getSoneStatus(Sone sone) { synchronized (soneStatuses) { return soneStatuses.get(sone); } } /** * Sets the status of the given Sone. * * @param sone * The Sone to set the status of * @param soneStatus * The status to set */ public void setSoneStatus(Sone sone, SoneStatus soneStatus) { synchronized (soneStatuses) { soneStatuses.put(sone, soneStatus); } } /** * Returns all Sones, remote and local. * * @return All Sones */ public Set<Sone> getSones() { Set<Sone> allSones = new HashSet<Sone>(); allSones.addAll(getLocalSones()); allSones.addAll(getRemoteSones()); return allSones; } /** * Returns the Sone with the given ID, regardless whether it’s local or * remote. * * @param id * The ID of the Sone to get * @return The Sone with the given ID, or {@code null} if there is no such * Sone */ public Sone getSone(String id) { if (isLocalSone(id)) { return getLocalSone(id); } return getRemoteSone(id); } /** * Returns whether the given Sone is a local Sone. * * @param sone * The Sone to check for its locality * @return {@code true} if the given Sone is local, {@code false} otherwise */ public boolean isLocalSone(Sone sone) { synchronized (localSones) { return localSones.containsKey(sone.getId()); } } /** * Returns whether the given ID is the ID of a local Sone. * * @param id * The Sone ID to check for its locality * @return {@code true} if the given ID is a local Sone, {@code false} * otherwise */ public boolean isLocalSone(String id) { synchronized (localSones) { return localSones.containsKey(id); } } /** * Returns all local Sones. * * @return All local Sones */ public Set<Sone> getLocalSones() { synchronized (localSones) { return new HashSet<Sone>(localSones.values()); } } /** * Returns the local Sone with the given ID. * * @param id * The ID of the Sone to get * @return The Sone with the given ID */ public Sone getLocalSone(String id) { synchronized (localSones) { Sone sone = localSones.get(id); if (sone == null) { sone = new Sone(id); localSones.put(id, sone); } return sone; } } /** * Returns all remote Sones. * * @return All remote Sones */ public Set<Sone> getRemoteSones() { synchronized (remoteSones) { return new HashSet<Sone>(remoteSones.values()); } } /** * Returns the remote Sone with the given ID. * * @param id * The ID of the remote Sone to get * @return The Sone with the given ID */ public Sone getRemoteSone(String id) { synchronized (remoteSones) { Sone sone = remoteSones.get(id); if (sone == null) { sone = new Sone(id); remoteSones.put(id, sone); } return sone; } } /** * Returns whether the given Sone is a remote Sone. * * @param sone * The Sone to check * @return {@code true} if the given Sone is a remote Sone, {@code false} * otherwise */ public boolean isRemoteSone(Sone sone) { synchronized (remoteSones) { return remoteSones.containsKey(sone.getId()); } } /** * Returns the post with the given ID. * * @param postId * The ID of the post to get * @return The post, or {@code null} if there is no such post */ public Post getPost(String postId) { synchronized (posts) { Post post = posts.get(postId); if (post == null) { post = new Post(postId); posts.put(postId, post); } return post; } } /** * Returns the reply with the given ID. * * @param replyId * The ID of the reply to get * @return The reply, or {@code null} if there is no such reply */ public Reply getReply(String replyId) { synchronized (replies) { Reply reply = replies.get(replyId); if (reply == null) { reply = new Reply(replyId); replies.put(replyId, reply); } return reply; } } /** * Returns all replies for the given post, order ascending by time. * * @param post * The post to get all replies for * @return All replies for the given post */ public List<Reply> getReplies(Post post) { Set<Sone> sones = getSones(); List<Reply> replies = new ArrayList<Reply>(); for (Sone sone : sones) { for (Reply reply : sone.getReplies()) { if (reply.getPost().equals(post)) { replies.add(reply); } } } Collections.sort(replies, Reply.TIME_COMPARATOR); return replies; } /** * Returns all Sones that have liked the given post. * * @param post * The post to get the liking Sones for * @return The Sones that like the given post */ public Set<Sone> getLikes(Post post) { Set<Sone> sones = new HashSet<Sone>(); for (Sone sone : getSones()) { if (sone.getLikedPostIds().contains(post.getId())) { sones.add(sone); } } return sones; } /** * Returns all Sones that have liked the given reply. * * @param reply * The reply to get the liking Sones for * @return The Sones that like the given reply */ public Set<Sone> getLikes(Reply reply) { Set<Sone> sones = new HashSet<Sone>(); for (Sone sone : getSones()) { if (sone.getLikedReplyIds().contains(reply.getId())) { sones.add(sone); } } return sones; } // // ACTIONS // /** * Adds a local Sone from the given ID which has to be the ID of an own * identity. * * @param id * The ID of an own identity to add a Sone for * @return The added (or already existing) Sone */ public Sone addLocalSone(String id) { synchronized (localSones) { if (localSones.containsKey(id)) { logger.log(Level.FINE, "Tried to add known local Sone: %s", id); return localSones.get(id); } OwnIdentity ownIdentity = identityManager.getOwnIdentity(id); if (ownIdentity == null) { logger.log(Level.INFO, "Invalid Sone ID: %s", id); return null; } return addLocalSone(ownIdentity); } } /** * Adds a local Sone from the given own identity. * * @param ownIdentity * The own identity to create a Sone from * @return The added (or already existing) Sone */ public Sone addLocalSone(OwnIdentity ownIdentity) { if (ownIdentity == null) { logger.log(Level.WARNING, "Given OwnIdentity is null!"); return null; } synchronized (localSones) { final Sone sone; try { sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri())); sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0)); } catch (MalformedURLException mue1) { logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1); return null; } /* TODO - load posts ’n stuff */ localSones.put(ownIdentity.getId(), sone); SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone); soneInserters.put(sone, soneInserter); soneInserter.start(); setSoneStatus(sone, SoneStatus.idle); loadSone(sone); return sone; } } /** * Creates a new Sone for the given own identity. * * @param ownIdentity * The own identity to create a Sone for * @return The created Sone */ public Sone createSone(OwnIdentity ownIdentity) { identityManager.addContext(ownIdentity, "Sone"); Sone sone = addLocalSone(ownIdentity); synchronized (sone) { /* mark as modified so that it gets inserted immediately. */ sone.setModificationCounter(sone.getModificationCounter() + 1); } return sone; } /** * Adds the Sone of the given identity. * * @param identity * The identity whose Sone to add * @return The added or already existing Sone */ public Sone addRemoteSone(Identity identity) { if (identity == null) { logger.log(Level.WARNING, "Given Identity is null!"); return null; } synchronized (remoteSones) { final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity); sone.setRequestUri(getSoneUri(identity.getRequestUri(), identity.getProperty("Sone.LatestEdition"))); remoteSones.put(identity.getId(), sone); soneDownloader.addSone(sone); new Thread(new Runnable() { @Override @SuppressWarnings("synthetic-access") public void run() { soneDownloader.fetchSone(sone); } }, "Sone Downloader").start(); setSoneStatus(sone, SoneStatus.idle); return sone; } } /** * Updates the stores Sone with the given Sone. * * @param sone * The updated Sone */ public void updateSone(Sone sone) { if (isRemoteSone(sone)) { Sone storedSone = getRemoteSone(sone.getId()); if (!(sone.getTime() > storedSone.getTime())) { logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone }); return; } synchronized (posts) { for (Post post : storedSone.getPosts()) { posts.remove(post.getId()); } for (Post post : sone.getPosts()) { posts.put(post.getId(), post); } } synchronized (replies) { for (Reply reply : storedSone.getReplies()) { replies.remove(reply.getId()); } for (Reply reply : sone.getReplies()) { replies.put(reply.getId(), reply); } } synchronized (storedSone) { storedSone.setTime(sone.getTime()); storedSone.setProfile(sone.getProfile()); storedSone.setPosts(sone.getPosts()); storedSone.setReplies(sone.getReplies()); storedSone.setLikePostIds(sone.getLikedPostIds()); storedSone.setLikeReplyIds(sone.getLikedReplyIds()); storedSone.setLatestEdition(sone.getRequestUri().getEdition()); } saveSone(storedSone); } } /** * Deletes the given Sone. This will remove the Sone from the * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter} * and remove the context from its identity. * * @param sone * The Sone to delete */ public void deleteSone(Sone sone) { if (!(sone.getIdentity() instanceof OwnIdentity)) { logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone); return; } synchronized (localSones) { if (!localSones.containsKey(sone.getId())) { logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone); return; } localSones.remove(sone.getId()); soneInserters.remove(sone).stop(); } identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone"); identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition"); try { configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null); } catch (ConfigurationException ce1) { logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1); } } /** * Loads and updates the given Sone from the configuration. If any error is * encountered, loading is aborted and the given Sone is not changed. * * @param sone * The Sone to load and update */ public void loadSone(Sone sone) { if (!isLocalSone(sone)) { logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone); return; } /* load Sone. */ String sonePrefix = "Sone/" + sone.getId(); Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null); if (soneTime == null) { logger.log(Level.INFO, "Could not load Sone because no Sone has been saved."); return; } long soneModificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0); /* load profile. */ Profile profile = new Profile(); profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null)); profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null)); profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null)); profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null)); profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null)); profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null)); /* load posts. */ Set<Post> posts = new HashSet<Post>(); while (true) { String postPrefix = sonePrefix + "/Posts/" + posts.size(); String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null); if (postId == null) { break; } long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0); String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null); if ((postTime == 0) || (postText == null)) { logger.log(Level.WARNING, "Invalid post found, aborting load!"); return; } posts.add(getPost(postId).setSone(sone).setTime(postTime).setText(postText)); } /* load replies. */ Set<Reply> replies = new HashSet<Reply>(); while (true) { String replyPrefix = sonePrefix + "/Replies/" + replies.size(); String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null); if (replyId == null) { break; } String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null); long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0); String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null); if ((postId == null) || (replyTime == 0) || (replyText == null)) { logger.log(Level.WARNING, "Invalid reply found, aborting load!"); return; } replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText)); } /* load post likes. */ Set<String> likedPostIds = new HashSet<String>(); while (true) { String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null); if (likedPostId == null) { break; } likedPostIds.add(likedPostId); } /* load reply likes. */ Set<String> likedReplyIds = new HashSet<String>(); while (true) { String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null); if (likedReplyId == null) { break; } likedReplyIds.add(likedReplyId); } /* load friends. */ Set<Sone> friends = new HashSet<Sone>(); while (true) { String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null); if (friendId == null) { break; } Boolean friendLocal = configuration.getBooleanValue(sonePrefix + "/Friends/" + friends.size() + "/Local").getValue(null); if (friendLocal == null) { logger.log(Level.WARNING, "Invalid friend found, aborting load!"); return; } friends.add(friendLocal ? getLocalSone(friendId) : getRemoteSone(friendId)); } /* if we’re still here, Sone was loaded successfully. */ synchronized (sone) { sone.setTime(soneTime); sone.setProfile(profile); sone.setPosts(posts); sone.setReplies(replies); sone.setLikePostIds(likedPostIds); sone.setLikeReplyIds(likedReplyIds); sone.setFriends(friends); sone.setModificationCounter(soneModificationCounter); } } /** * Saves the given Sone. This will persist all local settings for the given * Sone, such as the friends list and similar, private options. * * @param sone * The Sone to save */ public void saveSone(Sone sone) { if (!isLocalSone(sone)) { logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone); return; } if (!(sone.getIdentity() instanceof OwnIdentity)) { logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone); return; } logger.log(Level.INFO, "Saving Sone: %s", sone); identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition())); try { /* save Sone into configuration. */ String sonePrefix = "Sone/" + sone.getId(); configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime()); configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter()); /* save profile. */ Profile profile = sone.getProfile(); configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName()); configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName()); configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName()); configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay()); configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth()); configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear()); /* save posts. */ int postCounter = 0; for (Post post : sone.getPosts()) { String postPrefix = sonePrefix + "/Posts/" + postCounter++; configuration.getStringValue(postPrefix + "/ID").setValue(post.getId()); configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime()); configuration.getStringValue(postPrefix + "/Text").setValue(post.getText()); } configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null); /* save replies. */ int replyCounter = 0; for (Reply reply : sone.getReplies()) { String replyPrefix = sonePrefix + "/Replies/" + replyCounter++; configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId()); configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId()); configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime()); configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText()); } configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null); /* save post likes. */ int postLikeCounter = 0; for (String postId : sone.getLikedPostIds()) { configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId); } configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null); /* save reply likes. */ int replyLikeCounter = 0; for (String replyId : sone.getLikedReplyIds()) { configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId); } configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null); /* save friends. */ int friendCounter = 0; for (Sone friend : sone.getFriends()) { configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(friend.getId()); configuration.getBooleanValue(sonePrefix + "/Friends/" + friendCounter++ + "/Local").setValue(friend.getInsertUri() != null); } configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null); logger.log(Level.INFO, "Sone %s saved.", sone); } catch (ConfigurationException ce1) { logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1); } } /** * Creates a new post. * * @param sone * The Sone that creates the post * @param text * The text of the post */ public void createPost(Sone sone, String text) { createPost(sone, System.currentTimeMillis(), text); } /** * Creates a new post. * * @param sone * The Sone that creates the post * @param time * The time of the post * @param text * The text of the post */ public void createPost(Sone sone, long time, String text) { if (!isLocalSone(sone)) { logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone); return; } Post post = new Post(sone, time, text); synchronized (posts) { posts.put(post.getId(), post); } sone.addPost(post); saveSone(sone); } /** * Deletes the given post. * * @param post * The post to delete */ public void deletePost(Post post) { if (!isLocalSone(post.getSone())) { logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone()); return; } post.getSone().removePost(post); synchronized (posts) { posts.remove(post.getId()); } saveSone(post.getSone()); } /** * Creates a new reply. * * @param sone * The Sone that creates the reply * @param post * The post that this reply refers to * @param text * The text of the reply */ public void createReply(Sone sone, Post post, String text) { createReply(sone, post, System.currentTimeMillis(), text); } /** * Creates a new reply. * * @param sone * The Sone that creates the reply * @param post * The post that this reply refers to * @param time * The time of the reply * @param text * The text of the reply */ public void createReply(Sone sone, Post post, long time, String text) { if (!isLocalSone(sone)) { logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone); return; } Reply reply = new Reply(sone, post, System.currentTimeMillis(), text); synchronized (replies) { replies.put(reply.getId(), reply); } sone.addReply(reply); saveSone(sone); } /** * Deletes the given reply. * * @param reply * The reply to delete */ public void deleteReply(Reply reply) { Sone sone = reply.getSone(); if (!isLocalSone(sone)) { logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply); return; } synchronized (replies) { replies.remove(reply.getId()); } sone.removeReply(reply); saveSone(sone); } /** * Starts the core. */ public void start() { loadConfiguration(); } /** * Stops the core. */ public void stop() { synchronized (localSones) { for (SoneInserter soneInserter : soneInserters.values()) { soneInserter.stop(); } } saveConfiguration(); } // // PRIVATE METHODS // /** * Loads the configuration. */ @SuppressWarnings("unchecked") private void loadConfiguration() { /* create options. */ options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() { @Override public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) { SoneInserter.setInsertionDelay(newValue); } })); options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false)); options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false)); /* read options from configuration. */ options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null)); options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null)); boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get(); options.getBooleanOption("ClearOnNextRestart").set(null); options.getBooleanOption("ReallyClearOnNextRestart").set(null); if (clearConfiguration) { /* stop loading the configuration. */ return; } options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null)); } /** * Saves the current options. */ private void saveConfiguration() { /* store the options first. */ try { configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal()); configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal()); configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal()); } catch (ConfigurationException ce1) { logger.log(Level.SEVERE, "Could not store configuration!", ce1); } } /** * Generate a Sone URI from the given URI and latest edition. * * @param uriString * The URI to derive the Sone URI from * @param latestEditionString * The latest edition as a {@link String}, or {@code null} * @return The derived URI */ private FreenetURI getSoneUri(String uriString, String latestEditionString) { try { FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]).setSuggestedEdition(Numbers.safeParseLong(latestEditionString, (long) 0)); return uri; } catch (MalformedURLException mue1) { logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1); return null; } } // // INTERFACE IdentityListener // /** * {@inheritDoc} */ @Override public void ownIdentityAdded(OwnIdentity ownIdentity) { logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity); if (ownIdentity.hasContext("Sone")) { addLocalSone(ownIdentity); } } /** * {@inheritDoc} */ @Override public void ownIdentityRemoved(OwnIdentity ownIdentity) { /* TODO */ } /** * {@inheritDoc} */ @Override public void identityAdded(Identity identity) { logger.log(Level.FINEST, "Adding Identity: " + identity); addRemoteSone(identity); } /** * {@inheritDoc} */ @Override public void identityUpdated(Identity identity) { /* TODO */ } /** * {@inheritDoc} */ @Override public void identityRemoved(Identity identity) { /* TODO */ } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
a92d52d350cfde1a8947385b2e584b38ffc7e309
7abf1069a6023e1ec1812cb658ca4618ae37ba71
/ExceptionsDemo/src/codekamp/BalanceKhatam.java
db989b2db7b45e52163777560ab1eafa87f58320
[]
no_license
dux134/java_june
4e9bd75f3f10230553aafd7b8210ea22d599f6c4
9b1055ee0fd3b6b0e5c383a6bcc7a33beca08938
refs/heads/master
2020-03-14T13:21:10.080919
2017-07-07T08:26:34
2017-07-07T08:26:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
111
java
package codekamp; /** * Created by cerebro on 21/06/17. */ public class BalanceKhatam extends Exception { }
[ "101.prashant@gmail.com" ]
101.prashant@gmail.com
5dad65955029530ac01eb736cb340fa00aae7422
a1b0d7437af7c1543e313231162b92660217872a
/KKY/xlgLib/src/main/java/com/xlg/library/helper/ResourceIdHelper.java
fe2da6a23397af10cddf5bd0712ff7cb2d6056c7
[]
no_license
KaiKeYi/KKY-Android
3c05f99b36fdfacd0464bfc58dd50036ea5229da
bec87ef2fd3ae1647874fc23822fdf1d7a295dd9
refs/heads/master
2020-03-10T20:42:42.566789
2018-06-15T08:41:00
2018-06-15T08:41:00
129,575,856
0
0
null
null
null
null
UTF-8
Java
false
false
2,585
java
package com.xlg.library.helper; import android.content.Context; /** * @Author: Jason * @Time: 2018/4/20 15:09 * @Description: 根据资源的名字获取其ID值 */ public class ResourceIdHelper { public static int getIdByName(Context context, String className, String name) { String packageName = context.getPackageName(); Class r = null; int id = 0; try { r = Class.forName(packageName + ".R"); Class[] classes = r.getClasses(); Class desireClass = null; for (int i = 0; i < classes.length; ++i) { if (classes[i].getName().split("\\$")[1].equals(className)) { desireClass = classes[i]; break; } } if (desireClass != null) { id = desireClass.getField(name).getInt(desireClass); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return id; } public static int[] getIdsByName(Context context, String className, String name) { String packageName = context.getPackageName(); Class r = null; int[] ids = null; try { r = Class.forName(packageName + ".R"); Class[] classes = r.getClasses(); Class desireClass = null; for (int i = 0; i < classes.length; ++i) { if (classes[i].getName().split("\\$")[1].equals(className)) { desireClass = classes[i]; break; } } if ((desireClass != null) && (desireClass.getField(name).get(desireClass)) != null && (desireClass.getField(name).get(desireClass).getClass().isArray())) { ids = (int[]) desireClass.getField(name).get(desireClass); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return ids; } }
[ "1655661337@qq.com" ]
1655661337@qq.com
4860365becb06190e3190af87b247d729a009dd0
73bd1f3cc807decc6cc09a75b445dc8bd575f397
/src/test/java/Login/LoginTests.java
26782e95b3d37b10b72d43122f0e3377b08677eb
[]
no_license
Ebuwa/Facebook_UI_Automation
f7f41d3c455f23b208a21fa6721e25384a8dcac7
6e1ab5fee97ab611a333184ffba36a2ab5fa80d0
refs/heads/master
2022-12-22T04:39:04.280239
2020-09-26T22:04:55
2020-09-26T22:04:55
298,904,192
0
0
null
null
null
null
UTF-8
Java
false
false
1,406
java
package Login; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class LoginTests { //import the selenium webDriver private WebDriver driver; //import chromedriver public void setup() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "resources/chromedriver.exe"); driver = new ChromeDriver (); //input project URL = facebook Login URL driver.get ("https://www.facebook.com/"); //waiting globally driver.manage ().timeouts ().implicitlyWait (10, TimeUnit.SECONDS); //maximize the window driver.manage().window ().maximize (); //get page title System.out.println(driver.getTitle()); //Locate email address field driver.findElement (By.id("email")).sendKeys("osarenrenebuwa@gmail.com"); // Locate password field driver.findElement(By.id("pass")).sendKeys("Ebuwa_01"); //Click on the Log In button driver.findElement (By.linkText ("Log In")).click(); //wait Thread.sleep(10000); //close window driver.quit(); } //initiate the test run command public static void main(String args[]) throws InterruptedException { LoginTests test = new LoginTests(); test.setup(); } }
[ "osarenrenebuwa@gmail.com" ]
osarenrenebuwa@gmail.com
c182c497c339524788f83d7dd02f14ee4a8ee18b
21aaa004a9bae904c3dadfd46897ba76e458ad47
/json/src/main/java/org/openx/data/jsonserde/json/HTTP.java
0b0d140299967431dab19913c084a31e0b49c101
[ "BSD-3-Clause" ]
permissive
patrickdsouza/Hive-JSON-Serde-1
9e867220e80a49899286bfcd0d56d3693de31ae1
fc0f66c72306b0d3110bd4f34a60c986e7b13e26
refs/heads/master
2020-04-24T17:01:53.764932
2015-10-09T18:09:27
2015-10-09T20:37:13
172,131,782
0
0
NOASSERTION
2019-02-22T20:42:33
2019-02-22T20:42:33
null
UTF-8
Java
false
false
5,940
java
package org.openx.data.jsonserde.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * Convert an HTTP header to a JSONObject and back. * @author JSON.org * @version 2010-12-24 */ public class HTTP { /** Carriage return/line feed. */ public static final String CRLF = "\r\n"; /** * Convert an HTTP header string into a JSONObject. It can be a request * header or a response header. A request header will contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header will contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * In addition, the other parameters in the header will be captured, using * the HTTP field names as JSON names, so that <pre> * Date: Sun, 26 May 2002 18:06:04 GMT * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s * Cache-Control: no-cache</pre> * become * <pre>{... * Date: "Sun, 26 May 2002 18:06:04 GMT", * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", * "Cache-Control": "no-cache", * ...}</pre> * It does no further checking or conversion. It does not parse dates. * It does not do '%' transforms on URLs. * @param string An HTTP header string. * @return A JSONObject containing the elements and attributes * of the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); HTTPTokener x = new HTTPTokener(string); String token; token = x.nextToken(); if (token.toUpperCase().startsWith("HTTP")) { // Response jo.put("HTTP-Version", token); jo.put("Status-Code", x.nextToken()); jo.put("Reason-Phrase", x.nextTo('\0')); x.next(); } else { // Request jo.put("Method", token); jo.put("Request-URI", x.nextToken()); jo.put("HTTP-Version", x.nextToken()); } // Fields while (x.more()) { String name = x.nextTo(':'); x.next(':'); jo.put(name, x.nextTo('\0')); x.next(); } return jo; } /** * Convert a JSONObject into an HTTP header. A request header must contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header must contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. * @param jo A JSONObject * @return An HTTP header string. * @throws JSONException if the object does not contain enough * information. */ public static String toString(JSONObject jo) throws JSONException { Iterator keys = jo.keys(); String string; StringBuffer sb = new StringBuffer(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); sb.append(' '); sb.append(jo.getString("Status-Code")); sb.append(' '); sb.append(jo.getString("Reason-Phrase")); } else if (jo.has("Method") && jo.has("Request-URI")) { sb.append(jo.getString("Method")); sb.append(' '); sb.append('"'); sb.append(jo.getString("Request-URI")); sb.append('"'); sb.append(' '); sb.append(jo.getString("HTTP-Version")); } else { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); while (keys.hasNext()) { string = keys.next().toString(); if (!string.equals("HTTP-Version") && !string.equals("Status-Code") && !string.equals("Reason-Phrase") && !string.equals("Method") && !string.equals("Request-URI") && !jo.isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); sb.append(CRLF); } } sb.append(CRLF); return sb.toString(); } }
[ "rcongiu@yahoo.com" ]
rcongiu@yahoo.com
5cac69e92b947836119a7d1b455f31272a7f3f3b
2e5e17e1ac4d695dabb12b98e1fe95c8facb9038
/fecha-oop/src/Fecha.java
a89b1ff641540551eed7c3424c464683195aa2a8
[]
no_license
Artiaga2/1PAW
1a59d03f5380e85498e968e891625c29acaebd4b
88dee4d60d9fc19805009e937d8ade114af44df3
refs/heads/master
2021-01-11T15:46:54.229290
2017-05-26T16:59:03
2017-05-26T16:59:03
79,931,100
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
/** * Created by artiaga on 25/1/17. */ public class Fecha { private int day; private int month; private int year; public int getDay() { return day; } public void setDay(int day) { //This se va a referir a la instancia this.day = day; } public int getMonth() { return month; } public void setMonth(int month) { //This se va a referir a la instancia this.month = month; } public int getYear() { return year; } public void setYear(int year) { //This se va a referir a la instancia this.year = year; } }
[ "artiaga@Mac-mini-de-macmini19.local" ]
artiaga@Mac-mini-de-macmini19.local
94b3a7048a4f22c3bc8e462dfaafe55d8ee82ada
5372ef5ced99e82f90af01092c0339c2d2a66925
/src/main/java/com/woniu/dao/LogsMapper.java
087da64e6c85362ce39b100c2abde5bb3cf561d7
[]
no_license
Gitgzh/logistics
3bc1b47b74254de56b4bab228480a4dd3ec51394
523705e7d991daf6e66ee1e082e4df0d30d33f7f
refs/heads/master
2023-03-03T23:09:44.177459
2019-11-12T13:10:25
2019-11-12T13:10:25
219,985,478
0
1
null
2023-02-22T08:17:17
2019-11-06T11:53:20
Java
UTF-8
Java
false
false
808
java
package com.woniu.dao; import com.woniu.pojo.Logs; import com.woniu.pojo.LogsExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface LogsMapper { long countByExample(LogsExample example); int deleteByExample(LogsExample example); int deleteByPrimaryKey(Integer lid); int insert(Logs record); int insertSelective(Logs record); List<Logs> selectByExample(LogsExample example); Logs selectByPrimaryKey(Integer lid); int updateByExampleSelective(@Param("record") Logs record, @Param("example") LogsExample example); int updateByExample(@Param("record") Logs record, @Param("example") LogsExample example); int updateByPrimaryKeySelective(Logs record); int updateByPrimaryKey(Logs record); }
[ "Administrator@USER-20190723SX.lan" ]
Administrator@USER-20190723SX.lan
ce5cf063cff3f25ef0ea70535c9646f02257be9c
49d701cec422e4525b413ad11846dc74b03521ad
/src/main/com/laungee/proj/common/model/TbSmsAlumni.java
d00567b903ec21bda1a307a851a0d5d3a81ac3ba
[]
no_license
hehaiyang7133862/ALUMNI_FUND
b9e716b58a44fad7f13b77ebc0ad5dda7151b787
2cbd27392afcdbe14a12d8ed466e63866727eaf8
refs/heads/master
2021-01-01T03:55:54.458004
2016-05-09T03:03:57
2016-05-09T03:03:57
56,836,523
0
0
null
null
null
null
UTF-8
Java
false
false
1,866
java
package com.laungee.proj.common.model; import java.util.Date; /** * TbSmsAlumni entity. * * @author MyEclipse Persistence Tools */ public class TbSmsAlumni implements java.io.Serializable { // Fields private Long relId; private TbAlumni tbAlumni; private TbSmsGroup tbSmsGroup; private Long updateUser; private Date updateTime; private Long creationUser; private String creationTime; // Constructors public Long getCreationUser() { return creationUser; } public void setCreationUser(Long creationUser) { this.creationUser = creationUser; } public String getCreationTime() { return creationTime; } public void setCreationTime(String creationTime) { this.creationTime = creationTime; } // Constructors /** default constructor */ public TbSmsAlumni() { } /** full constructor */ public TbSmsAlumni(TbAlumni tbAlumni, TbSmsGroup tbSmsGroup, Long updateUser, Date updateTime) { this.tbAlumni = tbAlumni; this.tbSmsGroup = tbSmsGroup; this.updateUser = updateUser; this.updateTime = updateTime; } // Property accessors public Long getRelId() { return this.relId; } public void setRelId(Long relId) { this.relId = relId; } public TbAlumni getTbAlumni() { return this.tbAlumni; } public void setTbAlumni(TbAlumni tbAlumni) { this.tbAlumni = tbAlumni; } public TbSmsGroup getTbSmsGroup() { return this.tbSmsGroup; } public void setTbSmsGroup(TbSmsGroup tbSmsGroup) { this.tbSmsGroup = tbSmsGroup; } public Long getUpdateUser() { return this.updateUser; } public void setUpdateUser(Long updateUser) { this.updateUser = updateUser; } public Date getUpdateTime() { return this.updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
[ "hehaiyang7133862@163.com" ]
hehaiyang7133862@163.com
5f08b98bf4715f9b70c2a062d0ea7b31208e323b
2cd3d91de8983fcc1cd2894cdb9ae232ffbf4cb9
/src/main/java/com/example/demo/SpringBoot402ExApplication.java
585645397bfbf44c01be95167178c91fcfc20909
[]
no_license
jkneisler1/SpringBoot_402Ex
1a77185be55f6b360f04d62363873adbb19a31fa
1a4e219a2d297b0370862ba5fbe1bc294b003405
refs/heads/master
2020-07-08T09:24:34.187934
2019-08-21T17:23:26
2019-08-21T17:23:26
203,631,954
0
0
null
null
null
null
UTF-8
Java
false
false
339
java
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBoot402ExApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot402ExApplication.class, args); } }
[ "GBTC405002UR@MC.MONTGOMERYCOLLEGE.EDU" ]
GBTC405002UR@MC.MONTGOMERYCOLLEGE.EDU
557fa30df0988324a4834fa01fa0edefd22ae468
88aecbc4d0922238008df2e753408b428ad2d349
/src/main/java/guru/springframework/spring5webapp/controllers/AuthorController.java
6cd1b2a115b319c73162f3974f72b88b4b48805d
[]
no_license
chintoz/spring5webapp
cbe967e93f1a6df0bc617f1f9dd442b31bdcc7df
6160a98d01ac2237fd8da34602c4ce2ad99b9203
refs/heads/master
2022-12-09T10:14:47.247351
2020-09-29T23:33:17
2020-09-29T23:33:17
298,909,152
0
0
null
2020-09-29T23:33:18
2020-09-26T22:23:11
Java
UTF-8
Java
false
false
697
java
package guru.springframework.spring5webapp.controllers; import guru.springframework.spring5webapp.repositories.AuthorRepository; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AuthorController { private final AuthorRepository authorRepository; public AuthorController(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } @RequestMapping("/authors") public String getAuthors(Model model) { model.addAttribute("authors", authorRepository.findAll()); return "authors/list"; // View name } }
[ "jacintomena@gmail.com" ]
jacintomena@gmail.com
bf50e9f67d3b9e3c6cff8dcbc41df7fd2627d471
9b7e167039d81eb80cb47c99f936c943cf008096
/src/test/java/com/project/conference/registryapp/serviceImpl/AttendeeRegistryServiceImplTest.java
9236ab5fd57ddc224d061e8007e7cc540199762f
[]
no_license
rredy/registry-app
4842b6afdfc0804b0367c43a1976b56f2b6208a5
a3e0f03e2e537514c73938eb41896893c9dc25fb
refs/heads/master
2022-12-28T10:54:46.103362
2020-08-03T04:45:05
2020-08-03T04:45:05
284,562,997
0
0
null
2020-10-14T00:07:45
2020-08-02T23:55:37
Java
UTF-8
Java
false
false
1,614
java
package com.project.conference.registryapp.serviceImpl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.project.conference.registryapp.daoImpl.AttendeeDaoImpl; import com.project.conference.registryapp.model.Attendee; import com.project.conference.registryapp.model.SessionTalk; @SpringBootTest class AttendeeRegistryServiceImplTest { @Mock AttendeeDaoImpl attendeeDaoImpl; @Autowired AttendeeRegistryServiceImpl attendeeRegistryServiceImpl; @BeforeEach void setup() { attendeeDaoImpl = mock(AttendeeDaoImpl.class); } @Test void testRegisterAttendee() { Attendee attendee = new Attendee(); attendee.setId(1l); Mockito.when(attendeeDaoImpl.register(Mockito.any())).thenReturn("Success"); assertEquals("Success", attendeeRegistryServiceImpl.registerAttendee(attendee)); } @Test void testattendeetalksList() { Attendee attendee = new Attendee(); attendee.setId(1l); List<SessionTalk> response = new ArrayList<SessionTalk>(); SessionTalk talk = new SessionTalk(); talk.setId(1l); response.add(talk); Mockito.when(attendeeDaoImpl.getTalksList(1l)).thenReturn(response); assertEquals(Collections.EMPTY_LIST, attendeeRegistryServiceImpl.getAttendeeTalksList(1l)); } }
[ "ramasrmr@gmail.com" ]
ramasrmr@gmail.com
153b4a53d98666274d1ce9da8126fb2e767a5222
a1a9c39d6af10abdd3bd994c1a56b58fda60ad68
/bootstrap/bootstrap5.0.2/src/main/java/org/nova/html/bootstrap/Styling.java
ac7df92ec7c3332c02611456585fcc7c0e28127b
[ "MIT" ]
permissive
andrewtjew/nova
00d6b856e96eb12a975dc13f21361361fe2f6033
4c1ca8ca1066e1b9c7efc8e8f5247d649b1da9db
refs/heads/master
2023-08-20T10:41:20.614483
2023-08-18T18:43:53
2023-08-18T18:43:53
187,707,763
0
0
NOASSERTION
2023-04-12T14:56:30
2019-05-20T20:19:48
Java
UTF-8
Java
false
false
15,016
java
/******************************************************************************* * Copyright (C) 2017-2019 Kat Fung Tjew * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package org.nova.html.bootstrap; import org.nova.html.attributes.Style; import org.nova.html.bootstrap.classes.Align; import org.nova.html.bootstrap.classes.AlignItems; import org.nova.html.bootstrap.classes.AlignSelf; import org.nova.html.bootstrap.classes.BreakPoint; import org.nova.html.bootstrap.classes.Display; import org.nova.html.bootstrap.classes.Edge; import org.nova.html.bootstrap.classes.FW; import org.nova.html.bootstrap.classes.Flex; import org.nova.html.bootstrap.classes.Float_; import org.nova.html.bootstrap.classes.Justify; import org.nova.html.bootstrap.classes.Overflow; import org.nova.html.bootstrap.classes.Position; import org.nova.html.bootstrap.classes.Rounded; import org.nova.html.bootstrap.classes.Size; import org.nova.html.bootstrap.classes.StyleColor; import org.nova.html.bootstrap.classes.TextAlign; import org.nova.html.bootstrap.classes.Text; import org.nova.html.bootstrap.classes.Translate; import org.nova.html.elements.Composer; import org.nova.html.elements.TagElement; public interface Styling<ELEMENT> { // final private TagElement<?> element; public ELEMENT addClass(Object class_,Object...fragments); public TagElement<?> getElement(); // public default ELEMENT color(StyleColor value,boolean outline) // { // TagElement<?> element=getElement(); // if (element instanceof StyleComponent<?>) // { // StyleComponent<?> component=(StyleComponent<?>)element; // if (outline) // { // addClass(component.getComponentClass(),outline?"outline":null,value.toString()); // } // else // { // addClass(component.getComponentClass(),value.toString()); // } // } // // return (ELEMENT)this; // } // // @SuppressWarnings("unchecked") // public default ELEMENT color(StyleColor value) // { // return color(value,false); // } // public default ELEMENT addClass(Object class_,Object...fragments) // { // if (fragments!=null) // { // if (class_!=null) // { // StringBuilder sb=new StringBuilder(class_.toString()); // for (Object fragment:fragments) // { // if (fragment!=null) // { // sb.append('-').append(fragment); // } // } // this.element.addClass(sb.toString()); // } // } // return this; // } public default ELEMENT col(BreakPoint breakPoint,int columns) { if (breakPoint==BreakPoint.xs) { return addClass("col",columns); } return addClass("col",breakPoint,columns); } public default ELEMENT col(BreakPoint breakPoint) { if (breakPoint==BreakPoint.xs) { return addClass("col"); } return addClass("col",breakPoint); } public default ELEMENT col(int columns) { return addClass("col",columns); } public default ELEMENT col() { return addClass("col"); } public default ELEMENT col_form_label() { return addClass("col-form-label"); } public default ELEMENT row() { return addClass("row"); } public default ELEMENT float_(BreakPoint breakPoint,Float_ value) { return addClass("float",breakPoint,value); } public default ELEMENT form_range() { return addClass("form-range"); } public default ELEMENT form_check() { return addClass("form-check"); } public default ELEMENT form_check_label() { return addClass("form-check-label"); } public default ELEMENT form_check_inline() { return addClass("form-check-inline"); } public default ELEMENT form_switch() { return addClass("form-switch"); } public default ELEMENT form_select() { return addClass("form-select"); } public default ELEMENT form_label() { return addClass("form-label"); } public default ELEMENT form_text() { return addClass("form-text"); } public default ELEMENT form_control() { return addClass("form-control"); } public default ELEMENT form_control(Size size) { return addClass("form-control",size.toString()); } public default ELEMENT form_control(BreakPoint breakPoint) { return addClass("form-control",breakPoint); } public default ELEMENT invalid_feeback() { return addClass("invalid-feedback"); } public default ELEMENT valid_feeback() { return addClass("valid-feedback"); } public default ELEMENT bg(StyleColor value) { return addClass("bg",value); } public default ELEMENT bg_gradient(StyleColor value) { return addClass("bg","gradient",value); } public default ELEMENT text(StyleColor value) { return addClass("text",value); } public default ELEMENT text(TextAlign value) { return addClass("text",value); } public default ELEMENT text(BreakPoint breakPoint,TextAlign value) { return addClass("text",breakPoint,value); } public default ELEMENT text(Text value) { return addClass("text",value); } // public default ELEMENT font(Font value) // { // return addClass("fw",value); // } public default ELEMENT lead() { return addClass("lead"); } public default ELEMENT small() { return addClass("small"); } public default ELEMENT float_(Float_ value) { return addClass("float",value); } public default ELEMENT offset(int offset) { return addClass("offset",offset); } public default ELEMENT display(int size) { return addClass("display",size); } public default ELEMENT rounded() { return addClass("rounded"); } // public default ELEMENT rounded(int value) // { // return addClass("rounded",value); // } public default ELEMENT rounded(Rounded value) { return addClass("rounded",value); } public default ELEMENT rounded(Rounded value,boolean subtract) { return addClass("rounded",value,0); } public default ELEMENT border() { return addClass("border"); } public default ELEMENT border(Edge value) { return addClass("border",value); } public default ELEMENT border(Edge value,boolean substract) { if (substract) { return addClass("border",value,0); } else { return addClass("border",value); } } public default ELEMENT border(int size) { return addClass("border",size); } public default ELEMENT border(StyleColor color) { return addClass("border",color); } public default ELEMENT clearfix() { return addClass("clearfix"); } public default ELEMENT flex(Flex flex) { return addClass("flex",flex); } public default ELEMENT flex(Flex flex,int value) { return addClass("flex",flex,value); } public default ELEMENT flex(BreakPoint breakPoint,Flex flex) { return addClass("flex",breakPoint,flex); } public default ELEMENT align_self(AlignSelf value) { return addClass("align-self",value); } public default ELEMENT align_self(BreakPoint breakPoint,AlignSelf value) { return addClass("align-self",breakPoint,value); } public default ELEMENT align_items(AlignItems value) { return addClass("align-items",value); } public default ELEMENT align(Align value) { return addClass("align",value); } public default ELEMENT order(int value) { return addClass("order",value); } public default ELEMENT me(BreakPoint breakPoint,int value) { return addClass("me",breakPoint,value); } public default ELEMENT me(int value) { return addClass("me",value); } public default ELEMENT ms(int value) { return addClass("ms",value); } public default ELEMENT mt(int value) { return addClass("mt",value); } public default ELEMENT mb(int value) { return addClass("mb",value); } public default ELEMENT mx(int value) { return addClass("mx",value); } public default ELEMENT my(int value) { return addClass("my",value); } public default ELEMENT m(int value) { return addClass("m",value); } //---- public default ELEMENT mt(BreakPoint breakPoint,int value) { return addClass("mt",breakPoint,value); } public default ELEMENT mb(BreakPoint breakPoint,int value) { return addClass("mb",breakPoint,value); } public default ELEMENT mx(BreakPoint breakPoint,int value) { return addClass("mx",breakPoint,value); } public default ELEMENT my(BreakPoint breakPoint,int value) { return addClass("my",breakPoint,value); } public default ELEMENT m(BreakPoint breakPoint,int value) { return addClass("m",breakPoint,value); } public default ELEMENT mt_auto() { return addClass("mt","auto"); } public default ELEMENT mb_auto() { return addClass("mb","auto"); } public default ELEMENT mx_auto() { return addClass("mx","auto"); } public default ELEMENT my_auto() { return addClass("my","auto"); } public default ELEMENT me_auto() { return addClass("me","auto"); } public default ELEMENT ms_auto() { return addClass("ms","auto"); } public default ELEMENT pe(int value) { return addClass("pe",value); } public default ELEMENT ps(int value) { return addClass("ps",value); } public default ELEMENT pt(int value) { return addClass("pt",value); } public default ELEMENT pb(int value) { return addClass("pb",value); } public default ELEMENT px(int value) { return addClass("px",value); } public default ELEMENT py(int value) { return addClass("py",value); } public default ELEMENT p(int value) { return addClass("p",value); } public default ELEMENT pe_auto() { return addClass("pe","auto"); } public default ELEMENT ps_auto() { return addClass("ps","auto"); } public default ELEMENT pt_auto() { return addClass("pt","auto"); } public default ELEMENT pb_auto() { return addClass("pb","auto"); } public default ELEMENT px_auto() { return addClass("px","auto"); } public default ELEMENT py_auto() { return addClass("py","auto"); } public default ELEMENT d(Display display) { return addClass("d",display); } public default ELEMENT d(BreakPoint breakPoint,Display display) { return addClass("d",breakPoint,display); } public default ELEMENT w(int value) { return addClass("w",value); } public default ELEMENT mw(int value) { return addClass("mw",value); } public default ELEMENT h(int value) { return addClass("h",value); } public default ELEMENT h_auto() { return addClass("h","auto"); } public default ELEMENT mh(int value) { return addClass("mh",value); } public default ELEMENT position(Position value) { return addClass("position",value); } public default ELEMENT overflow(Overflow value) { return addClass("overflow",value); } public default ELEMENT justify_content(Justify value) { return addClass("justify-content",value); } public default ELEMENT justify_content(BreakPoint breakPoint,Justify value) { return addClass("justify-content",breakPoint,value); } public default ELEMENT fs(int value) { return addClass("fs",value); } public default ELEMENT fw(FW value) { return addClass("fw",value); } public default ELEMENT top(int value) { return addClass("top",value); } public default ELEMENT bottom(int value) { return addClass("bottom",value); } public default ELEMENT start(int value) { return addClass("start",value); } public default ELEMENT translate(Translate value) { return addClass("translate",value); } public default ELEMENT visually_hidden() { return addClass("visually-hidden"); } public default ELEMENT input_group() { return addClass("input-group"); } // public default ELEMENT input_group_append() // { // return addClass("input-group-append"); // } // public default ELEMENT input_group_prepend() // { // return addClass("input-group-prepend"); // } public default ELEMENT input_group_text() { return addClass("input-group-text"); } public default ELEMENT align_items(AlignSelf value) { return addClass("align-items",value); } // public default ELEMENT flex_wrap() // { // return addClass("flex-wrap"); // } // public default ELEMENT flex_wrap_reverse() // { // return addClass("flex-wrap-reverse"); // } }
[ "andrew_tjew@yahoo.com" ]
andrew_tjew@yahoo.com
49a4a4f51576e4084b30f774bfc53858a6fceda0
daf1ecc45238c23dcc6e510900294684f9aaec68
/src/main/java/za/co/entelect/challenge/domain/state/Weapon.java
d168b644018753afda971821e5abbb541dc2dd5e
[]
no_license
leonardseymore/entelect_2017
698e236b88b95b1f1aaad5fa7e9c677efc83907d
cb2c0fe1bbf85b6f1884de103cabab32a8882138
refs/heads/master
2021-06-17T09:36:39.179510
2017-05-25T13:38:30
2017-05-25T13:38:30
89,683,062
0
0
null
null
null
null
UTF-8
Java
false
false
217
java
package za.co.entelect.challenge.domain.state; import java.io.Serializable; public class Weapon implements Serializable { public WeaponType WeaponType; public enum WeaponType { SingleShot } }
[ "leonardseymore@gmail.com" ]
leonardseymore@gmail.com
3120b40ccb996f9eb47e373a54e639fb33c6d433
98ccbb4f41669dbdfcae08c3709a404131f54f05
/암기해둘것/src/누적합/수들의합4.java
200ff1e95cb8fcebf7d4e8c68ffc9f9edf27ee97
[ "MIT" ]
permissive
KimJaeHyun94/CodingTest
fee6f14b3320c85670bdab7e9dbe97f429a31d9c
f153879ac0ac1cf45de487afd9a4a94c9ffbe10d
refs/heads/main
2023-04-22T15:27:46.325475
2021-05-16T15:02:27
2021-05-16T15:02:27
330,885,734
0
0
null
null
null
null
UTF-8
Java
false
false
1,088
java
package 누적합; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class 수들의합4 { static int N, K; static int arr[], sum[]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); arr = new int[N + 1]; sum = new int[N + 1]; st = new StringTokenizer(br.readLine()); for (int i = 1; i <= N; i++) { arr[i] = Integer.parseInt(st.nextToken()); sum[i] = sum[i - 1] + arr[i]; //구간 합 구성 } HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 1); long ans = 0; for (int i = 1; i <= N; i++) { ans += map.getOrDefault(sum[i] - K, 0); //잇으면 갯수를 더해준다. map.put(sum[i], map.getOrDefault(sum[i], 0) + 1); } System.out.println(ans); } }
[ "ru6300@naver.com" ]
ru6300@naver.com
2e83c64d9b30bfabf77f28fc274992081605387a
18276d1601f8a253ee2a5f3e06a0f50843b87eef
/src/test/java/com/appslandia/common/base/TokenGeneratorTest.java
1c695c8bf3d87411ac13151f23a75afe1722a0ca
[ "MIT" ]
permissive
saroj-mandal/appslandia-common
af8a3414fac17774de5e11e0ef2fe7ca2f180e5b
fcae70e73ea694bf09b703cb2a95fef7b17d7fd6
refs/heads/master
2022-04-07T20:54:45.364953
2020-02-27T14:53:25
2020-02-27T14:53:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,591
java
// The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.common.base; import org.junit.Assert; import org.junit.Test; /** * * @author <a href="mailto:haducloc13@gmail.com">Loc Ha</a> * */ public class TokenGeneratorTest { @Test public void test() { for (int i = 1; i <= 1000; i++) { TokenGenerator impl = new TokenGenerator().setLength(i); String str = impl.generate(); Assert.assertEquals(str.length(), i); Assert.assertTrue(impl.verify(str)); } } }
[ "haducloc13@gmail.com" ]
haducloc13@gmail.com
c26e9e9e9692d5f460be85f7d67b8d82afbf1558
67ced3d75e62a8838e4e7f1ab9bb40a6f358b3a2
/src/main/java/com/dsa/segmenttree/HorribleQuerriesFromC.java
abba560b99023cca128d49eb1c3542f699213d5c
[]
no_license
sumitkjm/java-learning
a4719bc0fc0641839bc062da5c530d43a59769b0
451211146b7be2834d1857055e92d682872fdc0e
refs/heads/master
2023-05-02T16:51:18.067479
2021-06-06T13:29:41
2021-06-06T13:29:41
103,023,921
0
0
null
null
null
null
UTF-8
Java
false
false
5,158
java
package com.dsa.segmenttree; import java.util.Scanner; /** * Horrible Queries * Send Feedback * World is getting more evil and it's getting tougher to get into the Evil League of Evil. Since the legendary Bad Horse has retired, now you have to correctly answer the evil questions of Dr. Horrible, who has a PhD in horribleness (but not in Computer Science). You are given an array of N elements, which are initially all 0. After that you will be given C commands. They are - * * 0 p q v - you have to add v to all numbers in the range of p to q (inclusive), where p and q are two indexes of the array. * * 1 p q - output a line containing a single integer which is the sum of all the array elements between p and q (inclusive) * * Input * * In the first line you'll be given T, number of test cases. * * Each test case will start with N (N <= 100 000) and C (C <= 100 000). After that you'll be given C commands in the format as mentioned above. 1 <= p, q <= N and 1 <= v <= 10^7. * * Output * * Print the answers of the queries. * * Input: * * 1 * 8 6 * 0 2 4 26 * 0 4 8 80 * 0 4 5 20 * 1 8 8 * 0 5 7 14 * 1 4 8 * * Output: * * 80 * 508 */ public class HorribleQuerriesFromC { static int m = (int)Math.pow(10,9)+7; public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int j=1;j<=t;j++) { int n = in.nextInt(); // all element initially set to zero as per question to so need to read int c = in.nextInt(); long [] tree = new long[4*n]; long[] lazy = new long[4*n]; for (int i=0;i<c;i++) { int type = in.nextInt(); if(type == 0) { // 0 p q v - you have to add v to all numbers in the range of p to q (inclusive), where p and q are two indexes of the array. int p = in.nextInt(); int q = in.nextInt(); int v = in.nextInt(); updateSegmentTree(tree,lazy,0,n-1,1,p-1,q-1,v); } // 1 p q - output a line containing a single integer which is the sum of all the array elements between p and q (inclusive) if(type ==1) { int p = in.nextInt(); int q = in.nextInt(); System.out.println(searchSegmentTree(tree,lazy,0,n-1,1,p-1,q-1)); } } } } // update segment tree with increment value by inc public static void updateSegmentTree(long[]tree, long[] lazy, int low, int high, int treeIndex, int startR, int endR, int inc) { if(low>high) { // System.out.println("low>high,low="+low+",high="+high); return; } // first check if lazy tree has anything already pending to be added if(lazy[treeIndex]!=0) { // then increment tree[treeIndex] += (high-low+1)*lazy[treeIndex]; if (low != high) { lazy[2 * treeIndex] += lazy[treeIndex]; lazy[2 * treeIndex + 1] +=lazy[treeIndex]; } lazy[treeIndex] = 0; } // no overlap if(startR>high || endR<low) { return; } // complete overlap if(startR<=low&& high<=endR) { tree[treeIndex] +=(high-low+1) * inc; if(low != high) { lazy[2*treeIndex] +=inc; lazy[2*treeIndex+1] +=inc; } return; } // partial overlap int mid = (low+high)/2; updateSegmentTree(tree,lazy,low,mid,2*treeIndex,startR,endR,inc); updateSegmentTree(tree,lazy,mid+1,high,2*treeIndex+1,startR,endR,inc); tree[treeIndex] = tree[2*treeIndex] + tree[2*treeIndex+1]; } public static long searchSegmentTree(long[]tree, long[] lazy, int low, int high, int treeIndex, int searchS, int searchE) { // first check if lazy tree has anything already pending to be added // first check if lazy tree has anything already pending to be added if(lazy[treeIndex]!=0) { // then increment tree[treeIndex] += (high-low+1)*lazy[treeIndex]; if (low != high) { lazy[2 * treeIndex] += lazy[treeIndex]; lazy[2 * treeIndex + 1] +=lazy[treeIndex]; } lazy[treeIndex] = 0; } // Match if(searchE==high && searchS==low) { return tree[treeIndex]; } // if no match if(searchS>high||searchE<low) { return 0; } // partial overlap if((searchS>=low &&searchE<high)||(searchS>low &&searchE<=high)) { int mid = (low+high)/2; long sum1 = searchSegmentTree(tree,lazy,low,mid,2*treeIndex,searchS,searchE>mid?mid:searchE); long sum2 = searchSegmentTree(tree,lazy,mid+1,high,2*treeIndex+1,searchS<mid+1?mid+1:searchS,searchE); return sum1+sum2; } return tree[treeIndex]; } }
[ "skumar6@paypal.com" ]
skumar6@paypal.com
240c858bb5486f2c7d64777cc9b7a183d3e9b5a4
a2df6764e9f4350e0d9184efadb6c92c40d40212
/aliyun-java-sdk-aliyuncvc/src/main/java/com/aliyuncs/aliyuncvc/model/v20200330/CreateUserResponse.java
4f073d557b6162a9e4e4b3fdf4ec0b7e56bc0bdb
[ "Apache-2.0" ]
permissive
warriorsZXX/aliyun-openapi-java-sdk
567840c4bdd438d43be6bd21edde86585cd6274a
f8fd2b81a5f2cd46b1e31974ff6a7afed111a245
refs/heads/master
2022-12-06T15:45:20.418475
2020-08-20T08:37:31
2020-08-26T06:17:49
290,450,773
1
0
NOASSERTION
2020-08-26T09:15:48
2020-08-26T09:15:47
null
UTF-8
Java
false
false
1,963
java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.aliyuncvc.model.v20200330; import com.aliyuncs.AcsResponse; import com.aliyuncs.aliyuncvc.transform.v20200330.CreateUserResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CreateUserResponse extends AcsResponse { private Integer errorCode; private String message; private Boolean success; private String requestId; private String userId; public Integer getErrorCode() { return this.errorCode; } public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } @Override public CreateUserResponse getInstance(UnmarshallerContext context) { return CreateUserResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
b34e02a4d305e5fa0284482ea50f1cc2847a3d62
781d97f90bae49817eae4401c0b62c27eb71b04b
/main/java/com/light/privateMovies/dao/MovieDao.java
c2d6bc9e341c4063237b4f83f54b72faa02d2030
[]
no_license
fancylight/privateMovies
7632bc8851688ead05c3627b700679108bf99a4f
9d6a7077a39f77ea64c2204c03e60ca6fa15cdc4
refs/heads/master
2020-04-25T02:29:02.732105
2019-06-29T19:08:12
2019-06-29T19:08:12
172,440,857
0
0
null
null
null
null
UTF-8
Java
false
false
2,171
java
package com.light.privateMovies.dao; import com.light.privateMovies.dao.base.LightBaseDao; import com.light.privateMovies.pojo.Movie; import com.light.privateMovies.util.FileUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.stereotype.Repository; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @Repository public class MovieDao extends LightBaseDao<Movie> { public MovieDao() { this.clazz = Movie.class; } @Autowired public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } /** * @param name 电影名 * @return 电影 */ public Movie getMovieByMovieName(String name) { var m = new Movie(); m.setMovieName(name); var list = getListByExample(m); if (list.size() > 0) return list.get(0); m = null; return m; } /** * 仅仅获取电影名和path * * @return */ public Map<String, List<Movie>> getNameAndPath() { var list = getPartData(new String[]{"movieName", "localPath"}); return list.stream().collect(Collectors.groupingBy(Movie::getMovieName)); } //todo:删除操作要分情况,典型的文件夹应该是 模块/演员/作品名/作品,要排除不是这种情况 //解决方法1:将暴露在模块下的电影创建一个同名文件夹 public void delete(Movie movie, String modulePath, boolean simple) { super.delete(movie); //删除本地文件 try { String targetPath = new File(movie.getLocalPath()).getCanonicalPath(); if (simple) { new File(targetPath).delete(); return; } String dirPath = new File(targetPath + "/..").getCanonicalPath(); FileUtil.deleteDir(dirPath, targetPath, modulePath); } catch (IOException e) { e.printStackTrace(); } } }
[ "15529439929@163.com" ]
15529439929@163.com
ed94529dec99565d100e4e6d75e18a906394516b
8b04eb64502f63653b2f435e268019d42fd171e1
/core/src/test/java/io/grpc/internal/AbstractReadableBufferTest.java
46a66586d2d1a3cd66e88a49eaff3ad0764b68cd
[ "Apache-2.0" ]
permissive
grpc-nebula/grpc-nebula-java
de553e5d9d77dc28bb0ec78076d7dc5bd8caa41b
04f20585354e1994e70404535b048c9c188d5d95
refs/heads/master
2023-07-19T08:54:45.297237
2022-02-09T13:48:39
2022-02-09T13:48:39
188,228,592
140
63
Apache-2.0
2023-07-05T20:43:37
2019-05-23T12:20:14
Java
UTF-8
Java
false
false
1,720
java
/* * Copyright 2014 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.internal; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.stubbing.OngoingStubbing; /** * Tests for {@link AbstractReadableBuffer}. */ @RunWith(JUnit4.class) public class AbstractReadableBufferTest { @Mock private AbstractReadableBuffer buffer; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void readPositiveIntShouldSucceed() { mockBytes(0x7F, 0xEE, 0xDD, 0xCC); assertEquals(0x7FEEDDCC, buffer.readInt()); } @Test public void readNegativeIntShouldSucceed() { mockBytes(0xFF, 0xEE, 0xDD, 0xCC); assertEquals(0xFFEEDDCC, buffer.readInt()); } private void mockBytes(int... bytes) { when(buffer.readableBytes()).thenReturn(bytes.length); OngoingStubbing<Integer> stub = when(buffer.readUnsignedByte()); for (int b : bytes) { stub = stub.thenReturn(b); } } }
[ "cozyshu@qq.com" ]
cozyshu@qq.com
3ac25436a2b061386c2dba2cff25fd7a3b53c4a7
6d478c255a3a75a9743ef383a99aa5c86bb5506e
/bots/net_maclife_wechat_http_Bot_Emoji.java
4919df02928eae87fc252da70b22c6b6e2d18d80
[]
no_license
moontide/WeChatBotEngine
4da3cbe6c88eddc12cb103b146ddbb0bafc32ec9
afe338c7d550750c2023bac5fb566baa453cbf4b
refs/heads/master
2020-06-17T03:49:03.604547
2018-08-22T09:50:48
2018-08-22T09:50:48
75,043,614
178
61
null
null
null
null
UTF-8
Java
false
false
13,059
java
import java.io.*; import java.sql.*; import java.util.*; import org.apache.commons.lang3.*; import org.jsoup.*; import org.jsoup.nodes.*; import org.jsoup.select.*; import com.fasterxml.jackson.databind.*; /** * 通过 emoji 命令,来查询并显示 emoji 字符的 Bot。 * <p> * 注意:当在手机上发 emoji 表情时,比如:😞,web 端收到的是类似 <code>&lt;span class="emoji emoji1f612"&gt;&lt;/span&gt;</code> 这样的文字(难道微信担心 Web 版在不同浏览器下表现不一致?)。 * 手机微信上的 emoji 字符的显示,应该是(猜测)手机操作系统自己显示的,比如 android ios 用系统内置的 emoji 字体来显示(再说一遍,是猜测)。 * </p> * <p> * emoji 数据库是从 http://unicode.org/emoji/charts/full-emoji-list.html (这个 html 有 36M 大小!!!) 获取,然后通过本程序生成 SQL 脚本文件,然后执行该 SQL 脚本文件写入的。 * </p> * @author liuyan * */ public class net_maclife_wechat_http_Bot_Emoji extends net_maclife_wechat_http_Bot { @Override public int OnTextMessageReceived ( JsonNode jsonMessage, JsonNode jsonFrom, String sFromAccount, String sFromName, boolean isFromMe, JsonNode jsonTo, String sToAccount, String sToName, boolean isToMe, JsonNode jsonReplyTo, String sReplyToAccount, String sReplyToName, boolean isReplyToRoom, JsonNode jsonReplyTo_RoomMember, String sReplyToAccount_RoomMember, String sReplyToName_RoomMember, JsonNode jsonReplyTo_Person, String sReplyToAccount_Person, String sReplyToName_Person, String sContent, boolean isContentMentionedMe, boolean isContentMentionedMeFirst ) { List<String> listCommands = net_maclife_wechat_http_BotApp.GetConfig ().getList (String.class, "bot.emoji-test.commands"); if (listCommands==null || listCommands.isEmpty ()) // 如果未配置命令,则不处理 return net_maclife_wechat_http_BotEngine.BOT_CHAIN_PROCESS_MODE_MASK__CONTINUE; if (! net_maclife_wechat_http_BotApp.hasCommandPrefix (sContent)) { return net_maclife_wechat_http_BotEngine.BOT_CHAIN_PROCESS_MODE_MASK__CONTINUE; } sContent = net_maclife_wechat_http_BotApp.StripOutCommandPrefix (sContent); try { String[] arrayMessages = sContent.split ("\\s+", 2); if (arrayMessages==null || arrayMessages.length<1) return net_maclife_wechat_http_BotEngine.BOT_CHAIN_PROCESS_MODE_MASK__CONTINUE; String sCommandInputed = arrayMessages[0]; String sCommandParametersInputed = null; if (arrayMessages.length >= 2) sCommandParametersInputed = arrayMessages[1]; String[] arrayCommandOptions = sCommandInputed.split ("\\.+", 2); sCommandInputed = arrayCommandOptions[0]; String sCommandOptionsInputed = null; if (arrayCommandOptions.length >= 2) sCommandOptionsInputed = arrayCommandOptions[1]; // 命令行命令格式没问题,现在开始查询数据库 for (int i=0; i<listCommands.size (); i++) { String sCommand = listCommands.get (i); if (StringUtils.equalsIgnoreCase (sCommandInputed, sCommand)) { if (StringUtils.isEmpty (sCommandParametersInputed)) { SendTextMessage (sReplyToAccount, sReplyToName, sReplyToAccount_RoomMember, sReplyToName_RoomMember, GetName() + " 在查询时需要指定关键字(关键字可指定多个,若为多个,则只匹配包含所有关键字的)。\n\n用法:\n" + sCommand + "[.detail] <emoji 关键字>...\n\n比如:\n" + sCommand + " cat face"); return net_maclife_wechat_http_BotEngine.BOT_CHAIN_PROCESS_MODE_MASK__CONTINUE; } // 解析命令“选项”: .detail .详细 boolean bShowDetail = false; if (StringUtils.isNotEmpty (sCommandOptionsInputed)) { arrayCommandOptions = sCommandOptionsInputed.split ("\\.+"); for (String sCommandOption : arrayCommandOptions) { if (StringUtils.equalsIgnoreCase (sCommandOption, "detail") || StringUtils.equalsIgnoreCase (sCommandOption, "详细")) { bShowDetail = true; } } } try { String sResult = Query (sCommandParametersInputed, bShowDetail); if (StringUtils.isEmpty (sResult)) { SendTextMessage (sReplyToAccount, sReplyToName, sReplyToAccount_RoomMember, sReplyToName_RoomMember, "找不到关键字为 " + sCommandParametersInputed + " 的 emoji 字符"); return net_maclife_wechat_http_BotEngine.BOT_CHAIN_PROCESS_MODE_MASK__CONTINUE; } SendTextMessage (sReplyToAccount, sReplyToName, sReplyToAccount_RoomMember, sReplyToName_RoomMember, sResult); break; } catch (Exception e) { SendTextMessage (sReplyToAccount, sReplyToName, sReplyToAccount_RoomMember, sReplyToName_RoomMember, "查询出错: " + e); } } } } catch (Exception e) { e.printStackTrace (); } return net_maclife_wechat_http_BotEngine.BOT_CHAIN_PROCESS_MODE_MASK__PROCESSED | net_maclife_wechat_http_BotEngine.BOT_CHAIN_PROCESS_MODE_MASK__CONTINUE; } String Query (String sQuery, boolean bShowDetail) throws SQLException { String sTablePrefix = StringUtils.trimToEmpty (net_maclife_wechat_http_BotApp.GetConfig ().getString ("bot.emoji-test.jdbc.database-table.prefix")); net_maclife_wechat_http_BotApp.SetupDataSource (); java.sql.Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; StringBuilder sb = null; try { conn = net_maclife_wechat_http_BotApp.botDS.getConnection (); StringBuilder sbSQL = new StringBuilder ("SELECT * FROM " + sTablePrefix + "emoji e WHERE 1=1"); if (! StringUtils.containsIgnoreCase (sQuery, "*")) { String[] arrayKeywords = sQuery.split (" +"); for (String sKeyword : arrayKeywords) { // 这里先用这种方式查询,以后考虑将 tag_name 挪到单独的表中,1对多的关系,查询时只按照 “=”的匹配方式进行匹配,不会造成现在这种模糊匹配的方式带来的不想要的结果:比如,查 eat 会匹配到 meat repeat 等 sbSQL.append (" AND (tag_name=? OR tag_name LIKE ? OR tag_name LIKE ? OR 英文名称=? OR 英文名称 LIKE ? OR 英文名称 LIKE ?)"); } } stmt = conn.prepareStatement (sbSQL.toString ()); int nCol = 1; if (! StringUtils.containsIgnoreCase (sQuery, "*")) { String[] arrayKeywords = sQuery.split (" +"); for (String sKeyword : arrayKeywords) { stmt.setString (nCol++, sKeyword); stmt.setString (nCol++, "%" + sKeyword + " %"); stmt.setString (nCol++, "% " + sKeyword + "%"); stmt.setString (nCol++, sKeyword); stmt.setString (nCol++, "%" + sKeyword + " %"); stmt.setString (nCol++, "% " + sKeyword + "%"); } } rs = stmt.executeQuery (); sb = new StringBuilder (); while (rs.next ()) { if (bShowDetail) { sb.append ("--------------------\n"); sb.append ("字符: "); } sb.append (rs.getString ("emoji_char")); sb.append (' '); if (bShowDetail) { sb.append ("\n"); sb.append ("名称: "); sb.append (rs.getString ("英文名称")); sb.append ("\n"); sb.append ("关键字: "); sb.append (rs.getString ("tag_name")); sb.append ("\n"); //sb.append ("Unicode: "); //sb.append (rs.getString ("tag_name")); //sb.append ("\n"); //sb.append ("UTF-8: "); //sb.append (rs.getString ("tag_name")); //sb.append ("\n"); } //break; } } catch (SQLException e) { e.printStackTrace(); throw e; } finally { try { if (rs != null) rs.close (); if (stmt != null) stmt.close (); if (conn != null) conn.close (); } catch (SQLException e) { e.printStackTrace(); } } return sb==null ? null : sb.toString (); } public static void Usage () { System.out.println ("用法:"); System.out.println ("从 full-emoji-list.html 生成 .sql 入库 SQL 脚本:"); System.out.println (" java net_maclife_wechat_http_Bot_Emoji gensql <.html 文件名> [输出到 .sql 文件名]"); System.out.println (" 如果不指定 [输出到 .sql 文件名],则输出到当前目录下的 emoji-data.mysql.sql 文件中 (如果文件存在的话,则直接覆盖)"); System.out.println ("查询:"); System.out.println (" java net_maclife_wechat_http_Bot_Emoji <emoji 关键字>"); } public static String ExtractImageData (String sImageSrc) { return StringUtils.substring (StringUtils.remove (sImageSrc, "—"), "data:image/png;base64,".length ()); } public static void main (String[] args) throws IOException { if (args.length < 1) { Usage (); return; } String sAction = args[0]; if (StringUtils.equalsIgnoreCase (sAction, "gensql")) { if (args.length < 2) { Usage (); return; } File fHTML = new File (args[1]); File fSQL = new File (args.length >=3 ? args[2] : "emoji-data.mysql.sql"); FileWriter fwSQL = new FileWriter (fSQL); //fwSQL.write ("INSERT INTO emoji (sn, code, emoji_char, 浏览器显示图, Apple显示图, Google显示图, Twitter显示图, One显示图, Facebook显示图, FBM显示图, 三星显示图, Windows显示图, GMail显示图, SB显示图, DCM显示图, KDDI显示图, 英文名称, 日期, tag_name) VALUES\n"); Document docHTML = Jsoup.parse (fHTML, net_maclife_wechat_http_BotApp.utf8); Elements eEmojiTable = docHTML.select ("table"); Elements eRows = eEmojiTable.select ("tr"); int nEmojiRow = 0; for (Element eRow : eRows) { Elements eCols = eRow.select ("td"); if (eCols.isEmpty ()) // 这行是 标题行? th? continue; if ((nEmojiRow % 100) == 0) // 每 100 行数据出一个 INSERT,免得 MySQL 报错: ERROR 2006 (HY000) at line 1: MySQL server has gone away 。原因: MySQL 数据包有大小限制,虽然可以在配置文件中用 SET max_allowed_packet=nnnM 来解决,但还是成多个 INSERT 吧 { if (nEmojiRow != 0) fwSQL.write (";"); fwSQL.write ("\nINSERT INTO emoji (sn, code, emoji_char, 浏览器显示图, Apple显示图, Google显示图, Twitter显示图, EmojiOne显示图, Facebook显示图, FacebookMessenger显示图, Samsung显示图, Windows显示图, GMail显示图, SoftBank显示图, DoCoMo显示图, KDDI显示图, 英文名称, 日期, tag_name) VALUES\n"); } if ((nEmojiRow % 100) == 0) // 每个 INSERT 的第一条数据 fwSQL.write ("\t ("); else fwSQL.write ("\n\t, ("); nEmojiRow ++; int i=0; String s序号 = eCols.get (i++).text (); String sCode = eCols.get (i++).text (); String sChars = eCols.get (i++).text (); String s浏览器显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sApple显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sGoogle显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sTwitter显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sEmojiOne显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sFacebook显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sFacebookMessenger显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sSamsung显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sWindows显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sGMail显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sSoftBank显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sDoCoMo显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String sKDDI显示图 = ExtractImageData (eCols.get (i++).select ("img").attr ("src")); String s英文名称 = eCols.get (i++).text (); String s日期时间 = eCols.get (i++).text (); String s关键字 = eCols.get (i++).text (); fwSQL.write (s序号); fwSQL.write (", '" + sCode + "'"); fwSQL.write (", '" + sChars + "'"); fwSQL.write (", '" + s浏览器显示图 + "'"); fwSQL.write (", '" + sApple显示图 + "'"); fwSQL.write (", '" + sGoogle显示图 + "'"); fwSQL.write (", '" + sTwitter显示图 + "'"); fwSQL.write (", '" + sEmojiOne显示图 + "'"); fwSQL.write (", '" + sFacebook显示图 + "'"); fwSQL.write (", '" + sFacebookMessenger显示图 + "'"); fwSQL.write (", '" + sSamsung显示图 + "'"); fwSQL.write (", '" + sWindows显示图 + "'"); fwSQL.write (", '" + sGMail显示图 + "'"); fwSQL.write (", '" + sSoftBank显示图 + "'"); fwSQL.write (", '" + sDoCoMo显示图 + "'"); fwSQL.write (", '" + sKDDI显示图 + "'"); fwSQL.write (", '" + s英文名称 + "'"); fwSQL.write (", '" + s日期时间 + "'"); fwSQL.write (", '" + s关键字 + "'"); fwSQL.write (')'); System.out.println (sChars); } fwSQL.write (";"); fwSQL.close (); } } }
[ "lovetide@qq.com" ]
lovetide@qq.com
18fa5c387024ae301cfec7fccc341e5e48f6ee1d
09b3d003152aba413fc6075909c47655e7aaa617
/src/test/java/org/ejagruti/investcorp/classA.java
dbc5e22e72c2f021ed4217885c3223e2b049df0f
[]
no_license
sgulshetty/InvestCorpgit
0f129bc4e797e5b438a4d8f9df562cec132a9037
393b4caa28130972c1d44e2101a171944457814c
refs/heads/master
2021-05-02T03:43:12.197153
2018-02-09T12:10:06
2018-02-09T12:10:06
120,900,993
0
0
null
null
null
null
UTF-8
Java
false
false
119
java
package org.ejagruti.investcorp; public class classA { public static void main(String[] args) { } }
[ "s.gulshetty" ]
s.gulshetty
2bb353b906fecf67838252e9dc9d0438e8c4c53d
f9c1fb1d3163697d2ac7063cc3cd656e102ef9ce
/src/main/java/com/moon/office/excel/core/VarSetterIn.java
d44541926a797b92813d32f282c1a26921b0cb8b
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
pronebel/moon-util
64c1cf63daa6cbe6d86c914d568fa6b2f0444830
f7cc80add88542224a48c6b3e993b9588cec4682
refs/heads/master
2020-05-03T01:30:59.657773
2019-03-29T01:58:54
2019-03-29T01:58:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,517
java
package com.moon.office.excel.core; import com.moon.beans.BeanInfoUtil; import com.moon.beans.FieldDescriptor; import com.moon.enums.ArrayOperators; import com.moon.enums.ArraysEnum; import com.moon.util.compute.RunnerUtil; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * @author benshaoye */ class VarSetterIn implements VarSetter { private final static int NO_SIZE = -1; private final String[] keys; private final String expression; public VarSetterIn(String[] keys, String expression) { this.keys = keys; this.expression = expression; } @Override public boolean isIn() { return true; } /** * 工厂模式、 迭代器模式 * * @param centerMap * @param target * @return */ @Override public WorkCenterMap setVarAndRender(WorkCenterMap centerMap, CenterRenderer target) { Object data = RunnerUtil.run(expression, centerMap); if (data instanceof Collection) { renderCollect(centerMap, target, keys, data); } else if (data instanceof Map) { renderMap(centerMap, target, keys, data); } else if (data == null) { return centerMap; } else if (data.getClass().isArray()) { renderArray(centerMap, target, keys, data); } else if (data instanceof Iterator) { renderIterator(centerMap, target, keys, data); } else if (data instanceof Iterable) { renderIterable(centerMap, target, keys, data); } else if (data instanceof Number) { renderNumber(centerMap, target, keys, data); } else if (data instanceof ResultSet) { renderResultSet(centerMap, target, keys, data); } else if (data instanceof CharSequence) { renderSequence(centerMap, target, keys, data); } else { renderBean(centerMap, target, keys, data); } return centerMap; } private final static void renderSequence( WorkCenterMap center, CenterRenderer target, String[] keys, Object data ) { char[] chars = data.toString().toCharArray(); CenterRenderer[] children = target.getChildren(); final int size = chars.length, length = children.length; for (int i = 0; i < size; i++) { setVars(center, keys, chars[i], i, i, size, i == 0, i + 1 == size); renderWhen(center, target, children, length); } } private final static void renderResultSet( WorkCenterMap center, CenterRenderer target, String[] keys, Object data ) { try { ResultSet set = (ResultSet) data; CenterRenderer[] children = target.getChildren(); for (int i = 0, length = children.length, size = NO_SIZE; set.next(); i++) { setVars(center, keys, set, i, i, size, set.isFirst(), set.isLast()); renderWhen(center, target, children, length); } } catch (SQLException e) { throw new IllegalArgumentException(e); } } private final static void renderBean( WorkCenterMap center, CenterRenderer target, String[] keys, Object data ) { Map<String, FieldDescriptor> descriptorMap = BeanInfoUtil.getFieldDescriptorsMap(data.getClass()); CenterRenderer[] children = target.getChildren(); final int size = descriptorMap.size(), length = children.length; Set<Map.Entry<String, FieldDescriptor>> entries = descriptorMap.entrySet(); int outerIndex = 0; for (Map.Entry<String, FieldDescriptor> entry : entries) { setVars(center, keys, entry.getValue().getValueIfPresent(data, true), entry.getKey(), outerIndex, size, outerIndex == 0, outerIndex + 1 == size); renderWhen(center, target, children, length); outerIndex++; } } private final static void renderNumber( WorkCenterMap center, CenterRenderer target, String[] keys, Object data ) { CenterRenderer[] children = target.getChildren(); final int length = children.length, max = ((Number) data).intValue(); for (int index = 0; index < max; index++) { setVars(center, keys, index, index, index, max, index == 0, false); renderWhen(center, target, children, length); } } /** * size 不可预测,总是为 0, last 总是为 false * * @param center * @param target * @param keys * @param data */ private final static void renderIterator( WorkCenterMap center, CenterRenderer target, String[] keys, Object data ) { Iterator iterator = (Iterator) data; CenterRenderer[] children = target.getChildren(); final int length = children.length; for (int index = 0, size = NO_SIZE; iterator.hasNext(); index++) { setVars(center, keys, iterator.next(), index, index, size, index == 0, false); renderWhen(center, target, children, length); } } /** * size 不可预测,总是为 0, last 总是为 false * * @param center * @param target * @param keys * @param data */ private final static void renderIterable( WorkCenterMap center, CenterRenderer target, String[] keys, Object data ) { Iterable iterable = (Iterable) data; CenterRenderer[] children = target.getChildren(); final int length = children.length, size = NO_SIZE; int outerIndex = 0; for (Object item : iterable) { setVars(center, keys, item, outerIndex, outerIndex, size, outerIndex == 0, false); renderWhen(center, target, children, length); } } private final static void renderArray( WorkCenterMap centerMap, CenterRenderer target, String[] keys, Object data ) { ArrayOperators arrayType = ArraysEnum.getOrObjects(data); CenterRenderer[] children = target.getChildren(); final int size = arrayType.length(data), length = children.length; int index = 0; for (Object item; index < size; index++) { item = arrayType.get(data, index); setVars(centerMap, keys, item, index, index, size, index == 0, index + 1 == size); renderWhen(centerMap, target, children, length); } } private final static void renderCollect( WorkCenterMap centerMap, CenterRenderer target, String[] keys, Object data ) { Collection collect = (Collection) data; CenterRenderer[] children = target.getChildren(); final int size = collect.size(), length = children.length; int index = 0; for (Object item : collect) { setVars(centerMap, keys, item, index, index, size, index == 0, index + 1 == size); renderWhen(centerMap, target, children, length); index++; } } private final static void renderMap( WorkCenterMap centerMap, CenterRenderer target, String[] keys, Object data ) { Map map = (Map) data; int outerIndex = 0; CenterRenderer[] children = target.getChildren(); final int size = map.size(), length = children.length; Set<Map.Entry> entries = map.entrySet(); for (Map.Entry entry : entries) { setVars(centerMap, keys, entry.getValue(), entry.getKey(), outerIndex, size, outerIndex == 0, outerIndex + 1 == size); renderWhen(centerMap, target, children, length); outerIndex++; } } private final static void renderWhen( WorkCenterMap centerMap, CenterRenderer target, CenterRenderer[] children, int length ) { if (target.isWhen(centerMap)) { target.beforeRender(centerMap); for (int innerIndex = 0; innerIndex < length; innerIndex++) { children[innerIndex].render(centerMap); } target.afterRender(centerMap); } } /** * @param centerMap * @param keys * @param values value, key, index, size, first, last */ private final static void setVars(WorkCenterMap centerMap, String[] keys, Object... values) { for (int i = 0, len = Math.min(keys.length, values.length); i < len; i++) { centerMap.put(keys[i], values[i]); } } }
[ "xua744531854@163.com" ]
xua744531854@163.com
b59fec1091d73cbc35ff7ed37320f5b1945fa3cb
73f738bb7460d0e9f385d8b9016fc28be25c9660
/src/main/java/com/proj/rup/product/model/vo/Product_File.java
49431fd7258519e86a73d550a1e2376f6ecce315
[]
no_license
hyelin0111/roundUp
38de4480cf1f10ac5ea2725a2cf8ec0cff8e8665
ad1e6068e5887e90237aa4aa7cafcbbdda24f336
refs/heads/master
2020-04-09T04:31:57.316254
2018-12-02T08:29:04
2018-12-02T08:29:04
160,026,905
0
0
null
null
null
null
UTF-8
Java
false
false
1,678
java
package com.proj.rup.product.model.vo; import java.sql.Date; public class Product_File { private int productFileNo; private int productNo; private String originalFileName; private String renamedFileName; private Date fileRegDate; public Product_File() { super(); // TODO Auto-generated constructor stub } public Product_File(int productFileNo, int productNo, String originalFilename, String renamedFilename, Date fileRegDate) { super(); this.productFileNo = productFileNo; this.productNo = productNo; this.originalFileName = originalFilename; this.renamedFileName = renamedFilename; this.fileRegDate = fileRegDate; } public int getProductFileNo() { return productFileNo; } public void setProductFileNo(int productFileNo) { this.productFileNo = productFileNo; } public int getProductNo() { return productNo; } public void setProductNo(int productNo) { this.productNo = productNo; } public String getOriginalFilename() { return originalFileName; } public void setOriginalFilename(String originalFilename) { this.originalFileName = originalFilename; } public String getRenamedFilename() { return renamedFileName; } public void setRenamedFilename(String renamedFilename) { this.renamedFileName = renamedFilename; } public Date getFileRegDate() { return fileRegDate; } public void setFileRegDate(Date fileRegDate) { this.fileRegDate = fileRegDate; } @Override public String toString() { return "Product_File [productFileNo=" + productFileNo + ", productNo=" + productNo + ", originalFilename=" + originalFileName + ", renamedFilename=" + renamedFileName + ", fileRegDate=" + fileRegDate + "]"; } }
[ "sjgpfls@gmail.com" ]
sjgpfls@gmail.com
bf1caf9b485730b71954fd609993fb6c3467c9a7
732b7a7d2d84acc66d8d8190f46227de77faf8cc
/untitled/src/StrategieInterface/BruitStrategie.java
6c3eaeb535b95d90b0a2383552cd5f682fd057db
[]
no_license
OussamaH92/TD3COOL
f7caa0fdcb216c650585a14374fa8ca74b0edfa5
9830be02ade72f255c8506fd8b3afe0d65e8bef9
refs/heads/master
2023-08-27T10:17:30.568879
2021-11-09T10:12:44
2021-11-09T10:12:44
426,133,609
0
0
null
null
null
null
UTF-8
Java
false
false
90
java
package StrategieInterface; public interface BruitStrategie { void faireBruit(); }
[ "oussamahaddad92230@hotmail.com" ]
oussamahaddad92230@hotmail.com
5372dc8d65d47841bb7ab879f07f6bf4dfb4a7a8
fa93c9be2923e697fb8a2066f8fb65c7718cdec7
/sources/com/facebook/internal/FacebookInitProvider.java
b179874f57f0ad041d269ae7208ab2a817e917cd
[]
no_license
Auch-Auch/avito_source
b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b
76fdcc5b7e036c57ecc193e790b0582481768cdc
refs/heads/master
2023-05-06T01:32:43.014668
2021-05-25T10:19:22
2021-05-25T10:19:22
370,650,685
0
0
null
null
null
null
UTF-8
Java
false
false
1,326
java
package com.facebook.internal; import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import com.facebook.FacebookSdk; public final class FacebookInitProvider extends ContentProvider { public static final String a = FacebookInitProvider.class.getSimpleName(); @Override // android.content.ContentProvider public int delete(Uri uri, String str, String[] strArr) { return 0; } @Override // android.content.ContentProvider public String getType(Uri uri) { return null; } @Override // android.content.ContentProvider public Uri insert(Uri uri, ContentValues contentValues) { return null; } @Override // android.content.ContentProvider public boolean onCreate() { try { FacebookSdk.sdkInitialize(getContext()); return false; } catch (Exception unused) { return false; } } @Override // android.content.ContentProvider public Cursor query(Uri uri, String[] strArr, String str, String[] strArr2, String str2) { return null; } @Override // android.content.ContentProvider public int update(Uri uri, ContentValues contentValues, String str, String[] strArr) { return 0; } }
[ "auchhunter@gmail.com" ]
auchhunter@gmail.com
becab0aaf51968b3f1bb9cad925588436a1ed591
37b007be6212f8c4293bf513cd1d432ff2ced7e7
/DadoActivity/app/src/main/java/dadosactivity/estudos/com/dadoactivity/MainActivity.java
6da9d2dbdcf224ea948734bf33400e351ab37a1c
[]
no_license
dantasslucas/AndroidStudioProjects
dca4c3166d7de6924e46b248248d97dc21821f8c
9d8e4662abb6692dbb625ba9d5f4ba06ffd5e990
refs/heads/master
2021-05-08T20:32:12.592824
2018-01-31T00:00:26
2018-01-31T00:00:26
119,611,180
0
0
null
null
null
null
UTF-8
Java
false
false
1,051
java
package dadosactivity.estudos.com.dadoactivity; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private Button btn_dados; private EditText txt_nome; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_dados = findViewById(R.id.btn_dadosId); txt_nome = findViewById(R.id.txt_nomeId); btn_dados.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String nome = txt_nome.getText().toString(); Intent intent = new Intent(getApplicationContext(),SegundaActivity.class); intent.putExtra("nome",nome); startActivity(intent); } }); } }
[ "dantas.lucas1994@gmail.com" ]
dantas.lucas1994@gmail.com
e83508fd00003fd5afcaa4b70184222b5277fb11
bd2fdc99f3d3efd8c8f88012288624bc5bfba2b8
/src/main/java/com/demo/induction/services/LogServiceImp.java
f1d5c6ef33dff16c1820f5d8fd944d112b8d777c
[]
no_license
realpacific/transaction-processor
27a3780c36572a447b6499afaa81b63873752f28
628ba42d930e402ac79c2c18775c0fdee195ae41
refs/heads/master
2022-01-22T11:39:59.867326
2019-08-30T12:54:10
2019-08-30T12:54:10
197,561,162
0
0
null
null
null
null
UTF-8
Java
false
false
947
java
package com.demo.induction.services; import com.demo.induction.db.LogRepository; import com.demo.induction.entity.Log; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import java.util.Optional; @Service @AllArgsConstructor public class LogServiceImp implements LogService { private final LogRepository repository; @Override public Optional<Log> getLogByName(String name) { return repository.findById(name); } @Override public void incrementLogHitCount(String name) { Optional<Log> logOptional = repository.findById(name); if (logOptional.isPresent()) { Log oldLog = logOptional.get(); oldLog.setCount(oldLog.getCount() + 1); repository.save(oldLog); } else { repository.save(new Log(name, 1)); } repository.findById(name).ifPresent(s -> System.out.println("HIT COUNTED: " + s)); } }
[ "prashant.barahi@clusus.com" ]
prashant.barahi@clusus.com
01016be67a2fe5a49ad10305300497dce7085462
08f4c7ff8222b06b99c660aa8b090c842da8ecc7
/src/test/java/org/testory/plumbing/inject/ArrayMaker.java
199360c430a350c08e9fc841aa6d2fec8962669a
[ "Apache-2.0" ]
permissive
philipparndt/jsolid
2ddbf09785afb973be44637890e54444f055c3e0
8a36643d489c693c0f7033d3b331ec1988b3893c
refs/heads/master
2023-04-09T21:21:00.120328
2020-07-11T09:26:00
2020-07-11T09:26:08
278,824,317
0
0
Apache-2.0
2023-04-04T00:27:20
2020-07-11T08:52:53
Java
UTF-8
Java
false
false
914
java
package org.testory.plumbing.inject; import static org.testory.plumbing.PlumbingException.check; import java.lang.reflect.Array; import org.testory.plumbing.Maker; public class ArrayMaker implements Maker { private final Maker maker; private ArrayMaker(Maker maker) { this.maker = maker; } public static Maker singletonArray(Maker maker) { check(maker != null); return new ArrayMaker(maker); } public <T> T make(Class<T> type, String name) { check(type != null); check(name != null); return type.isArray() ? makeArray(type, name) : maker.make(type, name); } private <T> T makeArray(Class<T> arrayType, String name) { Class<?> componentType = arrayType.getComponentType(); Object array = Array.newInstance(componentType, 1); Object element = make(componentType, name + "[0]"); Array.set(array, 0, element); return (T) array; } }
[ "2f.mail@gmx.de" ]
2f.mail@gmx.de
38d47a450fe2aa5138746f75f00a9c8d0994325d
5ba099b059c2b37b58fbc2a4864390bbf28c7a9a
/hr-payroll/src/main/java/com/coursems/hrpayroll/services/PaymentService.java
9ce924aafc9a63976214b67b16b305c768b8ca76
[]
no_license
guilhermeSobral/ms-course
bdd23e4b98fdc7c368546d8d4bc7d01c2776b1ca
d715f4709345197bef675f6578d171c575482605
refs/heads/master
2023-01-30T07:49:36.821950
2020-11-28T22:03:44
2020-11-28T22:03:44
315,781,520
0
0
null
null
null
null
UTF-8
Java
false
false
534
java
package com.coursems.hrpayroll.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.coursems.hrpayroll.clients.WorkerFeignClient; import com.coursems.hrpayroll.entities.Payment; @Service public class PaymentService { @Autowired private WorkerFeignClient client; public Payment getPayment(Long workerId, Integer days) { var worker = client.findWorker(workerId).getBody(); return new Payment(worker.getName(), worker.getDailyIncome(), 10); } }
[ "guilhermesbarros13@gmail.com" ]
guilhermesbarros13@gmail.com
47101034a751193bf92017bf8fa20312d7999d75
d749904db4d394d6375de4b5e8f44856cd5c5f84
/BashSoft/src/main/java/com/company/commands/ChangeAbsolutePathCommand.java
1872742a81f1b08f759236c14c00eff2c4f57517
[]
no_license
SimonaMitrenova/BashSoft
4fd8b584b5e38d18b93ee8ef3e61fdf1964a694d
79ca9a451f7aea191af8b690d338938311e17a79
refs/heads/master
2021-01-19T02:27:59.003402
2016-07-31T18:19:19
2016-07-31T18:19:19
61,833,018
0
1
null
null
null
null
UTF-8
Java
false
false
840
java
package com.company.commands; import com.company.annotations.Alias; import com.company.annotations.Inject; import com.company.commands.contracts.Executable; import com.company.exceptions.InvalidInputException; import com.company.io.contracts.DirectoryManager; @Alias(value = "cdabs") public class ChangeAbsolutePathCommand extends Command implements Executable { @Inject private DirectoryManager ioManager; public ChangeAbsolutePathCommand(String input, String[] data) { super(input, data); } @Override public void execute() throws Exception { String[] data = this.getData(); if (data.length != 2) { throw new InvalidInputException(this.getInput()); } String absolutePath = data[1]; this.ioManager.changeCurrentDirAbsolutePath(absolutePath); } }
[ "simona.mitrenova@gmail.com" ]
simona.mitrenova@gmail.com
d27ee6462af0aa70787b13cf450e9af2604be109
e5ab3582344176b5b65cb2dfe10a34d9a3be69aa
/dyclink/src/main/java/edu/columbia/psl/cc/util/TraceAnalyzer.java
0650082d57532a64aaaa9c60f4da462bda9e54e8
[ "MIT" ]
permissive
Programming-Systems-Lab/dyclink
642eaef28ad6baa688a607c94f11801ee90036d0
80c8d97eb2db2592f524717cfe94bdf7947ec8f9
refs/heads/master
2020-04-10T13:31:00.253664
2018-07-04T11:55:11
2018-07-04T11:55:11
60,430,252
11
6
null
2018-05-09T03:15:22
2016-06-04T21:07:27
Java
UTF-8
Java
false
false
20,810
java
package edu.columbia.psl.cc.util; import java.io.BufferedWriter; import java.io.Console; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.gson.reflect.TypeToken; import edu.columbia.psl.cc.config.MIBConfiguration; import edu.columbia.psl.cc.pojo.GraphTemplate; import edu.columbia.psl.cc.pojo.InstNode; public class TraceAnalyzer { public static String graphRepo = null; private static TypeToken<GraphTemplate> graphToken = new TypeToken<GraphTemplate>(){}; private static String header = "target,tid,t_start,t_trace,tLOC,sub,sid,s_centroid,s_strace,sLOC,inst_size,similarity"; private static String summaryHeader = "Insts,Similarity,# Clones,LOC,LOC/Clone"; public static File searchFile(List<String> possibleDirs, String fileName) { final String fileEnd = ":" + fileName + ".json"; FilenameFilter ff = new FilenameFilter() { @Override public boolean accept(File dir, String name) { // TODO Auto-generated method stub return name.endsWith(fileEnd); } }; for (String dir: possibleDirs) { File f = new File(dir); File[] files = f.listFiles(ff); if (files.length > 0) { return files[0]; } } return null; } public MethodTrace constructLineTrace(Collection<InstNode> insts, boolean clean) { MethodTrace mt = new MethodTrace(); HashMap<String, TreeSet<Integer>> lineTraceMap = new HashMap<String, TreeSet<Integer>>(); HashMap<String, TreeSet<Integer>> instTraceMap = new HashMap<String, TreeSet<Integer>>(); for (InstNode inst: insts) { String methodName = inst.getFromMethod(); if (lineTraceMap.containsKey(methodName)) { lineTraceMap.get(methodName).add(inst.getLinenumber()); instTraceMap.get(methodName).add(inst.getIdx()); } else { TreeSet<Integer> lineTrace = new TreeSet<Integer>(); lineTrace.add(inst.getLinenumber()); lineTraceMap.put(methodName, lineTrace); TreeSet<Integer> instTrace = new TreeSet<Integer>(); instTrace.add(inst.getIdx()); instTraceMap.put(methodName, instTrace); } } if (clean) { int gapLimit = 15; for (String methodName: lineTraceMap.keySet()) { TreeSet<Integer> lineTrace = lineTraceMap.get(methodName); List<Integer> lineBackup = new ArrayList<Integer>(lineTrace); int curNumber = -1; int mid = lineBackup.size()/2; int start = 0; int end = lineBackup.size(); for (int i = mid; i >= 0; i--) { int tmp = lineBackup.get(i); if (curNumber == -1) { curNumber = tmp; } else { int gap = curNumber - tmp; if (gap > gapLimit) { start = i + 1; System.out.println("Break start: " + start); break ; } curNumber = tmp; } } curNumber = -1; for (int i = mid; i < lineBackup.size(); i++) { int tmp = lineBackup.get(i); if (curNumber == -1) { curNumber = tmp; } else { int gap = tmp - curNumber; if (gap > gapLimit) { end = i; System.out.println("Break end: " + end); break ; } curNumber = tmp; } } lineTrace.clear(); lineTrace.addAll(lineBackup.subList(start, end)); System.out.println("Start: " + start); System.out.println("End: " + end); System.out.println("Original line trace: " + lineBackup); System.out.println("Filtered line trace: " + lineTrace); } } int sum = 0; int instSum = 0; for (String methodName: lineTraceMap.keySet()) { int lineNum = lineTraceMap.get(methodName).size(); sum += lineNum; int instNum = instTraceMap.get(methodName).size(); instSum += instNum; } mt.unitTrace = lineTraceMap; mt.unitInstTrace = instTraceMap; mt.lineSum = sum; mt.instSum = instSum; return mt; } public void combineMap(HashMap<String, TreeSet<Integer>> toAdd, HashMap<String, TreeSet<Integer>> recorder) { for (String addKey: toAdd.keySet()) { TreeSet<Integer> addVal = toAdd.get(addKey); if (!recorder.containsKey(addKey)) { recorder.put(addKey, addVal); } else { TreeSet<Integer> currentVal = recorder.get(addKey); currentVal.addAll(addVal); } } } public int sumUp(HashMap<String, TreeSet<Integer>> toSum) { int sum = 0; for (String key: toSum.keySet()) { sum += toSum.get(key).size(); } return sum; } public void analyzeResult(String url, String username, String password, int compId, int instThreshold, double simThreshold) { try { Class.forName("com.mysql.jdbc.Driver"); Connection connect = DriverManager.getConnection(url, username, password); String compQuery = "SELECT * FROM comp_table " + " WHERE comp_id = " + compId; PreparedStatement compStmt = connect.prepareStatement(compQuery); ResultSet compResult = compStmt.executeQuery(); String lib1 = null, lib2 = null; if (compResult.first()) { lib1 = compResult.getString("lib1"); lib2 = compResult.getString("lib2"); } else { System.err.println("Empty comparison query result"); System.exit(-1); } List<String> possibleDirs = new ArrayList<String>(); possibleDirs.add(graphRepo + lib1); possibleDirs.add(graphRepo + lib2); System.out.println("Possible graph locations: " + possibleDirs); /*String query = "SELECT rt.* FROM result_table rt " + "INNER JOIN (SELECT sub, sid, target, MAX(similarity) as sim " + "FROM result_table " + "WHERE comp_id=? and seg_size >=20 and target NOT LIKE '%ejml%' and sub NOT LIKE '%ejml%'" + "GROUP BY sub, sid, target) max_rec " + "ON rt.sub = max_rec.sub and rt.sid = max_rec.sid and rt.target = max_rec.target and rt.similarity = max_rec.sim " + "ORDER BY rt.sub, rt.sid, rt.target, rt.tid, rt.similarity;";*/ String query = "SELECT rt.* FROM result_table2 rt " + "INNER JOIN (SELECT sub, target, MAX(similarity) as sim " + "FROM result_table2 " + "WHERE comp_id=? and seg_size >=? and similarity >= ? " + "GROUP BY sub, target) max_rec " + "ON rt.sub = max_rec.sub and rt.target = max_rec.target and rt.similarity = max_rec.sim and rt.seg_size >= ? " + "WHERE comp_id=? " + "ORDER BY rt.sub, rt.sid, rt.target, rt.tid, rt.s_trace, rt.t_trace;"; System.out.println("Inst threshold: " + instThreshold); System.out.println("Similarity threshold: " + simThreshold); PreparedStatement pStmt = connect.prepareStatement(query); pStmt.setInt(1, compId); pStmt.setInt(2, instThreshold); pStmt.setDouble(3, simThreshold); pStmt.setInt(4, instThreshold); pStmt.setInt(5, compId); ResultSet result = pStmt.executeQuery(); HashMap<String, GraphTemplate> graphCache = new HashMap<String, GraphTemplate>(); //TreeMap<TraceObject, Double> traceMap = new TreeMap<TraceObject, Double>(traceSorter); HashMap<TreeSet<String>, TraceObject> traceMap = new HashMap<TreeSet<String>, TraceObject>(); double totalCloneLines = 0; int totalCloneNum = 0; StringBuilder sb = new StringBuilder(); sb.append(header + "\n"); while (result.next()) { totalCloneNum++; //Get graph object String subId = result.getString("sid").replace("-", ":"); String subName = result.getString("sub"); String subTrace = result.getString("s_trace"); String sCentroidInst = result.getString("s_centroid"); String targetId = result.getString("tid").replace("-", ":"); String targetName = result.getString("target"); String targetTrace = result.getString("t_trace"); String tStartInst = result.getString("t_start"); int segSize = result.getInt("seg_size"); double similarity = result.getDouble("similarity"); //double staticSimilarity = result.getDouble("static_dist"); TreeSet<String> traceKey = new TreeSet<String>(); traceKey.add(subName); traceKey.add(targetName); TraceObject traceObject = null; if (traceMap.containsKey(traceKey)) { traceObject = traceMap.get(traceKey); } else { traceObject = new TraceObject(); traceMap.put(traceKey, traceObject); } GraphTemplate subGraph = null; if (!graphCache.containsKey(subId)) { File subFile = searchFile(possibleDirs, subId); //System.out.println("Test id: " + subId); subGraph = GsonManager.readJsonGeneric(subFile, graphToken); //System.out.println("Test graph name: " + subGraph.getMethodName()); GraphConstructor reconstructor = new GraphConstructor(); reconstructor.reconstructGraph(subGraph, false); reconstructor.cleanObjInit(subGraph); MethodTrace mt = this.constructLineTrace(subGraph.getInstPool(), false); subGraph.methodTrace = mt; graphCache.put(subId, subGraph); } else { subGraph = graphCache.get(subId); } GraphTemplate targetGraph = null; if (!graphCache.containsKey(targetId)) { //System.out.println("Target id: " + targetId); File targetFile = searchFile(possibleDirs, targetId); targetGraph = GsonManager.readJsonGeneric(targetFile, graphToken); GraphConstructor reconstructor = new GraphConstructor(); reconstructor.reconstructGraph(targetGraph, false); reconstructor.cleanObjInit(targetGraph); MethodTrace mt = this.constructLineTrace(targetGraph.getInstPool(), false); targetGraph.methodTrace = mt; //System.out.println("Target graph name: " + targetGraph.getMethodName()); graphCache.put(targetId, targetGraph); } else { targetGraph = graphCache.get(targetId); } List<InstNode> segments = GraphUtil.sortInstPool(targetGraph.getInstPool(), true); int counter = 0; boolean startRecord = false; List<InstNode> requiredSegments = new ArrayList<InstNode>(); for (InstNode s: segments) { if (s.toString().equals(tStartInst)) { startRecord = true; } if (startRecord) { //targetTrace.add(s.callerLine); requiredSegments.add(s); counter++; if (counter == segSize) { break ; } } } System.out.println("Seg size: " + segSize); System.out.println("Real size: " + requiredSegments.size()); MethodTrace targetSegTrace = this.constructLineTrace(requiredSegments, false); double cloneLines = ((double)(subGraph.methodTrace.lineSum + targetSegTrace.lineSum))/2; totalCloneLines += cloneLines; //String mapKey = subName + "-" + subTrace + "-" + targetName + "-" + targetTrace; String subTargetKey = subName + "-" + targetName; if (traceObject.graphMap.containsKey(subTargetKey)) { HashMap<String, GraphTuple> lineTraceMap = traceObject.graphMap.get(subTargetKey); String lineTraceKey = subTrace + "-" + targetTrace; if (lineTraceMap.containsKey(lineTraceKey)) { GraphTuple gt = lineTraceMap.get(lineTraceKey); int currentTotalLine = gt.getTotalLinenumber(); int challenge = subGraph.methodTrace.lineSum + targetSegTrace.lineSum; if (challenge > currentTotalLine) { gt = new GraphTuple(); gt.sub = subName; gt.subTrace = subTrace; gt.repSubId = subId; gt.subCentroidInst = sCentroidInst; gt.subMethodTrace = subGraph.methodTrace; gt.target = targetName; gt.targetTrace = targetTrace; gt.repTargetId = targetId; gt.targetStartInst = tStartInst; gt.targetMethodTrace = targetSegTrace; gt.instSize = segSize; gt.similarity = similarity; lineTraceMap.put(lineTraceKey, gt); traceObject.maxSim = similarity; } } else { GraphTuple gt = new GraphTuple(); gt.sub = subName; gt.subTrace = subTrace; gt.repSubId = subId; gt.subCentroidInst = sCentroidInst; gt.subMethodTrace = subGraph.methodTrace; gt.target = targetName; gt.targetTrace = targetTrace; gt.repTargetId = targetId; gt.targetStartInst = tStartInst; gt.targetMethodTrace = targetSegTrace; gt.instSize = segSize; gt.similarity = similarity; lineTraceMap.put(lineTraceKey, gt); traceObject.maxSim = similarity; } } else if (traceObject.graphMap.size() == 0 || (similarity > traceObject.maxSim)){ traceObject.graphMap.clear(); HashMap<String, GraphTuple> lineTraceMap = new HashMap<String, GraphTuple>(); String lineTraceKey = subTrace + "-" + targetTrace; GraphTuple gt = new GraphTuple(); gt.sub = subName; gt.subTrace = subTrace; gt.repSubId = subId; gt.subCentroidInst = sCentroidInst; gt.subMethodTrace = subGraph.methodTrace; gt.target = targetName; gt.targetTrace = targetTrace; gt.repTargetId = targetId; gt.targetStartInst = tStartInst; gt.targetMethodTrace = targetSegTrace; gt.instSize = segSize; gt.similarity = similarity; lineTraceMap.put(lineTraceKey, gt); traceObject.graphMap.put(subTargetKey, lineTraceMap); traceObject.maxSim = similarity; System.out.println("Sub target key: " + subTargetKey); System.out.println("Line trace key: " + lineTraceKey); System.out.println("Target seg trace size: " + targetSegTrace.unitInstTrace.size()); } } for (TreeSet<String> methodTup: traceMap.keySet()) { System.out.println("Method pair: " + methodTup); TraceObject to = traceMap.get(methodTup); //System.out.println("Clone types #: " + to.graphMap.size()); //Only 1 key left: sub + target or target + sub for (String subTargetKey: to.graphMap.keySet()) { System.out.println("Sub-target key: " + subTargetKey); HashMap<String, GraphTuple> cloneTraceMap = to.graphMap.get(subTargetKey); for (String lineTraceRep: cloneTraceMap.keySet()) { GraphTuple gt = cloneTraceMap.get(lineTraceRep); StringBuilder rawData = new StringBuilder(); rawData.append(gt.target + ","); rawData.append(gt.repTargetId + ","); rawData.append(gt.targetStartInst + ","); rawData.append(gt.targetMethodTrace.unitTrace.toString().replace(",", ":") + ","); rawData.append(gt.targetMethodTrace.lineSum + ","); rawData.append(gt.sub + ","); rawData.append(gt.repSubId + ","); rawData.append(gt.subCentroidInst + ","); rawData.append(gt.subMethodTrace.unitTrace.toString().replace(",", ":") + ","); rawData.append(gt.subMethodTrace.lineSum + ","); rawData.append(gt.instSize + ","); rawData.append(gt.similarity + "\n"); sb.append(rawData.toString()); } } System.out.println(); } double avgLinePerClone = totalCloneLines/totalCloneNum; System.out.println("Clone number: " + totalCloneNum); System.out.println("Line number: " + totalCloneLines); System.out.println("Avg. line/clone: " + avgLinePerClone); sb.append("\n"); sb.append(summaryHeader + "\n"); sb.append(instThreshold + "," + simThreshold + "," + totalCloneNum + "," + totalCloneLines + "," + avgLinePerClone + "\n"); String compName = lib1 + "-" + lib2 + "-" + simThreshold + "-" + instThreshold; File f = new File(MIBConfiguration.getInstance().getResultDir() + "/" + compName + ".csv"); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.append(sb.toString()); bw.flush(); bw.close(); /*StringBuilder sb = new StringBuilder(); sb.append(header + "\n"); for (TreeSet<String> methods: traceMap.keySet()) { StringBuilder methodPair = new StringBuilder(); TraceObject to = traceMap.get(methods); for (String method: methods) { methodPair.append(method + "-"); } sb.append(methodPair.substring(0, methodPair.length()) + ","); sb.append(instThreshold + ","); double avgSeg = to.getAvgSegSize(); sb.append(avgSeg + ","); sb.append(simThreshold + ","); double avgSim = to.getAvgSim(); sb.append(avgSim + ","); int lineSum = 0; for (String methodName: to.methodsTraceMap.keySet()) { MethodTrace mt = to.methodsTraceMap.get(methodName); lineSum += mt.lineSum; } double avgLine = ((double)lineSum)/to.methodsTraceMap.size(); sb.append(avgLine + "\n"); System.out.println("Method pair: " + methodPair.toString()); System.out.println("Method rep: " + to.rep); System.out.println("Method trace:"); for (String m: to.methodsTraceMap.keySet()) { System.out.println(m); System.out.println(to.methodsTraceMap.get(m).unitTrace); } System.out.println(); } String compName = lib1 + "-" + lib2; File f = new File(MIBConfiguration.getInstance().getResultDir() + "/" + compName + ".csv"); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.append(sb.toString()); bw.flush(); bw.close();*/ compStmt.close(); pStmt.close(); connect.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { Console console = System.console(); if (console == null) { System.err.println("Null console"); System.exit(1); } System.out.println("Base repository:"); graphRepo = console.readLine(); System.out.println("Start comp id:"); int startId = Integer.valueOf(console.readLine()); System.out.println("End comp id:"); int endId = Integer.valueOf(console.readLine()); final String url = MIBConfiguration.getInstance().getDburl(); final String username = MIBConfiguration.getInstance().getDbusername(); System.out.println("DB URL: " + url); char[] passArray = console.readPassword("DB password: "); final String password = new String(passArray); System.out.println("Instruction threshold:"); final int instThreshold = Integer.valueOf(console.readLine()); System.out.println("Similarity threshold:"); final double simThreshold = Double.valueOf(console.readLine()); int parallelFactor = Runtime.getRuntime().availableProcessors(); ExecutorService traceExecutor = Executors.newFixedThreadPool(parallelFactor); for (int i = startId; i <= endId; i++) { final int compId = i; traceExecutor.submit(new Runnable() { @Override public void run() { TraceAnalyzer ta = new TraceAnalyzer(); ta.analyzeResult(url, username, password, compId, instThreshold, simThreshold); } }); } traceExecutor.shutdown(); while (!traceExecutor.isTerminated()); System.out.println("Trace analysis ends"); } public static class TraceObject { //public HashMap<String, GraphTuple> graphMap = new HashMap<String, GraphTuple>(); public HashMap<String, HashMap<String, GraphTuple>> graphMap = new HashMap<String, HashMap<String, GraphTuple>>(); public double maxSim; } public static class MethodTrace { public HashMap<String, TreeSet<Integer>> unitTrace; public HashMap<String, TreeSet<Integer>> unitInstTrace; public int lineSum; public int instSum; } public static class GraphTuple { public String sub; public String repSubId; public String subCentroidInst; public String target; public String repTargetId; public String targetStartInst; public String subTrace; public String targetTrace; private MethodTrace subMethodTrace; private MethodTrace targetMethodTrace; private int instSize; private double similarity; public void setSubMethodTrace(MethodTrace subMethodTrace) { this.subMethodTrace = subMethodTrace; } public MethodTrace getSubMethodTrace() { return this.subMethodTrace; } public void setTargetMethodTrace(MethodTrace targetMethodTrace) { this.targetMethodTrace = targetMethodTrace; } public MethodTrace getTargetMethodTrace() { return this.targetMethodTrace; } public int getTotalLinenumber() { return subMethodTrace.lineSum + targetMethodTrace.lineSum; } @Override public String toString() { return sub + "-" + subTrace + "-" + target + "-" + targetTrace; } @Override public boolean equals(Object o) { if (!(o instanceof GraphTuple)) return false; GraphTuple tmp = (GraphTuple)o; if (tmp.toString().equals(this.toString())) { return true; } else { return false; } } @Override public int hashCode() { return this.toString().hashCode(); } } }
[ "fs2455@columbia.edu" ]
fs2455@columbia.edu
34ea779942d04aee0627901f0458c6ab30b67eea
2ecb5a5120fdd128c8c4463264ca8f26ea08ffe1
/src/main/java/com/goel/projectboard/web/ProjectTaskController.java
2227ee0648d1fbd11226b69a53a4dd7140dd9a6e
[]
no_license
goel4ever/project-board-api
e48d7def1b9d2ecf1352a6e61db6f86c2f0fc775
7ce11139eb8618525b154b46b6a3df5ebe92e493
refs/heads/master
2020-09-07T16:37:52.426634
2019-11-11T06:52:18
2019-11-11T06:52:18
220,846,841
0
0
null
null
null
null
UTF-8
Java
false
false
2,304
java
package com.goel.projectboard.web; import com.goel.projectboard.domain.ProjectTask; import com.goel.projectboard.service.ProjectTaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/api/board") @CrossOrigin public class ProjectTaskController { @Autowired private ProjectTaskService projectTaskService; @PostMapping("") public ResponseEntity<?> addProjectTaskToBoard(@Valid @RequestBody ProjectTask projectTask, BindingResult result) { if (result.hasErrors()) { Map<String, String> errorMap = new HashMap<>(); for(FieldError error : result.getFieldErrors()) { errorMap.put(error.getField(), error.getDefaultMessage()); } return new ResponseEntity<>(errorMap, HttpStatus.BAD_REQUEST); } ProjectTask newProjectTask = projectTaskService.saveOrUpdateProjectTask(projectTask); return new ResponseEntity<>(newProjectTask, HttpStatus.CREATED); } @PostMapping("/ext") public ResponseEntity<?> addProjectTaskToBoardExtension(@Valid @RequestBody ProjectTask projectTask) { ProjectTask newProjectTask = projectTaskService.saveOrUpdateProjectTask(projectTask); return new ResponseEntity<ProjectTask>(newProjectTask, HttpStatus.CREATED); } @GetMapping("/all") public Iterable<ProjectTask> getAllProjectTasks() { return projectTaskService.findAllProjectTasks(); } @GetMapping("/{id}") public ResponseEntity<?> getProjectTask(@PathVariable Long id) { ProjectTask projectTask = projectTaskService.findProjectTaskById(id); return new ResponseEntity<>(projectTask, HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<?> deleteProjectTask(@PathVariable Long id) { ProjectTask projectTask = projectTaskService.deleteProjectTaskById(id); return new ResponseEntity<>(projectTask, HttpStatus.OK); } }
[ "anshul@zenabi.com" ]
anshul@zenabi.com
08859195db8f3443af9147d9d5a3ad14af195bea
13f937f75987ad2185c51ca4b1cd013d3e647e1e
/DMI/Claim Processing Automation/cpa_v2.0/main/src/com/aghit/task/util/DbcpUtil.java
76f62117437b448f1c445ba4a407812d806c0b84
[]
no_license
hwlsniper/DMI
30644374b35b2ed8bb297634311a71d0f1b0eb91
b6ac5f1eac635485bb4db14437aa3444e582be84
refs/heads/master
2020-03-19T16:44:33.828781
2018-05-22T05:38:52
2018-05-22T05:38:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,591
java
package com.aghit.task.util; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DbcpUtil { private static DbcpUtil du = new DbcpUtil(); private DataSource DS; private Log log = LogFactory.getLog(DbcpUtil.class); public DbcpUtil() { try { this.init(); } catch (IOException e) { log.error("初始化数据源失败," + e.getMessage()); } } public static DbcpUtil getInstance() { return du; } private void init() throws IOException { Properties p = new Properties(); p.load(DbcpUtil.class.getResourceAsStream("/jdbc.properties")); BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(p.getProperty("jdbc.driverClassName")); ds.setUsername(p.getProperty("jdbc.username")); ds.setPassword(p.getProperty("jdbc.password")); ds.setUrl(p.getProperty("jdbc.url")); DS = ds; } public DataSource getDataSource() { return DS; } /** * 从数据源获得一个连接 * * @throws SQLException */ public Connection getConn() throws SQLException { try { return DS.getConnection(); } catch (SQLException e) { throw new SQLException("获取数据库连接出错," + e.getMessage()); } } public void shutdownDataSource() throws SQLException { BasicDataSource bds = (BasicDataSource) DS; bds.close(); } }
[ "33211781+thekeygithub@users.noreply.github.com" ]
33211781+thekeygithub@users.noreply.github.com
3e1e809513cda55967bc410752926924fe61031f
f385f550bad08460fa38c56207a7aeaa3e127cae
/gpconnect-core/src/main/java/uk/gov/hscic/location/search/DefaultLocationSearchFactory.java
d52677414358c6a0cb37934b7f17d9c72a10ac87
[ "Apache-2.0" ]
permissive
digideskio/gpconnect
e7fff0890c8ada34bc5704d1b8badd0e0afe045a
47ee03aed9fce9d81ae773bf17103ad9f0c5c2e9
refs/heads/master
2021-01-12T11:22:25.697217
2016-11-04T15:59:03
2016-11-04T15:59:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
520
java
package uk.gov.hscic.location.search; import uk.gov.hscic.common.repo.AbstractRepositoryFactory; import org.springframework.stereotype.Service; @Service public class DefaultLocationSearchFactory extends AbstractRepositoryFactory<LocationSearch> implements LocationSearchFactory { @Override protected LocationSearch defaultRepository() { return new NotConfiguredLocationSearch(); } @Override protected Class<LocationSearch> repositoryClass() { return LocationSearch.class; } }
[ "will.weatherill@answerconsulting.com" ]
will.weatherill@answerconsulting.com
47c309643d857adec3bb5f475d18de6f1ee28f11
0bf9879f7e43dc6f69dd7003a833ffe66224abb5
/src/test/java/gov/usgs/wma/waterdata/TSDataTypeFactory.java
ae996e35f7d2b52559b9efedae0fb1e4755a8ef0
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
usgs/aqts-ts-type-router
d6df88a0fe8cb869bbb9a0fee220d65281850de9
586798449ebd1ab5301724ff4f1208c0ba221995
refs/heads/master
2021-08-19T00:54:23.655841
2021-01-15T15:52:35
2021-01-15T15:52:35
237,274,319
3
6
NOASSERTION
2021-07-28T10:45:19
2020-01-30T18:09:12
Java
UTF-8
Java
false
false
856
java
package gov.usgs.wma.waterdata; import java.sql.Types; import org.dbunit.dataset.datatype.DataType; import org.dbunit.dataset.datatype.DataTypeException; import org.dbunit.ext.postgresql.PostgresqlDataTypeFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TSDataTypeFactory extends PostgresqlDataTypeFactory { private static final Logger logger = LoggerFactory.getLogger(TSDataTypeFactory.class); public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException { logger.debug("createDataType(sqlType={}, sqlTypeName={})", String.valueOf(sqlType), sqlTypeName); if (sqlType == Types.OTHER && ("json".equals(sqlTypeName) || "jsonb".equals(sqlTypeName))) { return new JsonType(); // support PostgreSQL json/jsonb } else { return super.createDataType(sqlType, sqlTypeName); } } }
[ "drsteini@contractor.usgs.gov" ]
drsteini@contractor.usgs.gov
f7e7735ab8e4cc79bcc9702244828becc990ced7
803aaa7937a003ac3d3aed4c03153f232caf8390
/part5/security/server/basic-test/src/main/java/com/sp/fc/web/controller/HomeController.java
bcaa3992dfc655bd0b616d0cb612e53b47931491
[]
no_license
manbalboy/java-another-level
88fe5079b1b3654d4f36b7c4decfe09305c77831
79d8f6a2b061240be50eb5fc162d8c1363cf34f0
refs/heads/main
2023-09-01T05:16:10.873937
2021-10-13T13:40:25
2021-10-13T13:40:25
406,363,450
0
0
null
2021-10-11T11:01:20
2021-09-14T12:45:36
Java
UTF-8
Java
false
false
1,243
java
package com.sp.fc.web.controller; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeController { @GetMapping("/") public String index() { return "홈페이지"; } @GetMapping("/auth") public Authentication auth() { return SecurityContextHolder.getContext().getAuthentication(); } @PreAuthorize("hasAnyAuthority('ROLE_USER')") @GetMapping("/user") public SecurityMessage user() { return SecurityMessage.builder() .auth(SecurityContextHolder.getContext().getAuthentication()) .message("User 정보") .build(); } @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") @GetMapping("/admin") public SecurityMessage admin() { return SecurityMessage.builder() .auth(SecurityContextHolder.getContext().getAuthentication()) .message("관리자 정보") .build(); } }
[ "manbalboy@hanmail.net" ]
manbalboy@hanmail.net
312f92451024fecbdfa72e3aec0a532eed855b3c
2bb4e097a7c9f9fa748df940a9b7a2c5c624dd57
/taoliyuan/common/src/main/java/com/king/utils/XmlUtil.java
6ae91cdac5c58bfb566e1dccb954381c5365427e
[]
no_license
jsqfengbao/xiaoyouhui
55a8d5d9f989279323f41fe7e2cdde0fbee81348
ae332eaf1d9ba8442b6f6c799ee8889980de3929
refs/heads/master
2022-11-20T03:06:55.094849
2019-04-21T10:42:41
2019-04-21T10:42:41
182,510,540
2
1
null
2022-11-16T04:43:09
2019-04-21T08:46:59
Java
UTF-8
Java
false
false
6,715
java
package com.king.utils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; /** * xml相关的工具类 * * @author yang.y */ @SuppressWarnings("unchecked") public class XmlUtil { /** * xml字符串转换成bean对象 * * @param xmlStr xml字符串 * @param clazz 待转换的class * @return 转换后的对象 */ public static Object xmlStrToBean(String xmlStr, Class clazz) { Object obj = null; try { // 将xml格式的数据转换成Map对象 Map<String, Object> map = xmlStrToMap(xmlStr); // 将map对象的数据转换成Bean对象 obj = mapToBean(map, clazz); } catch (Exception e) { e.printStackTrace(); } return obj; } /** * 将xml格式的字符串转换成Map对象 * * @param xmlStr xml格式的字符串 * @return Map对象 * @throws Exception 异常 */ public static Map<String, Object> xmlStrToMap(String xmlStr) throws Exception { if (StringUtils.isNullOrEmpty(xmlStr)) { return null; } Map<String, Object> map = new HashMap<String, Object>(); // 将xml格式的字符串转换成Document对象 Document doc = DocumentHelper.parseText(xmlStr); // 获取根节点 Element root = doc.getRootElement(); // 获取根节点下的所有元素 List children = root.elements(); // 循环所有子元素 if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { Element child = (Element) children.get(i); map.put(child.getName(), child.getTextTrim()); } } return map; } /** * 将xml格式字符串转换成Bean对象 * 多级子节点递归遍历 * * @param xmlStr * @param clazz * @return * @throws Exception */ public static Object xmlStrToJavaBean(String xmlStr, Class clazz) { if (StringUtils.isNullOrEmpty(xmlStr)) { return null; } Object obj = null; Map<String, Object> map = new HashMap<String, Object>(); // 将xml格式的字符串转换成Document对象 Document doc; try { doc = DocumentHelper.parseText(xmlStr); // 获取根节点 Element root = doc.getRootElement(); map = elementToMap(root, map); // 将map对象的数据转换成Bean对象 obj = mapToBean(map, clazz); } catch (Exception e) { e.printStackTrace(); } return obj; } /** * 递归遍历xml子节点,转换Map * * @param element * @param map * @return */ public static Map<String, Object> elementToMap(Element element, Map<String, Object> map) { if (element == null || map == null) return null; List children = element.elements(); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { Element child = (Element) children.get(i); if (child.elements() != null && child.elements().size() > 0) elementToMap(child, map); else map.put(child.getName(), child.getTextTrim()); } } return map; } /** * 将Map对象通过反射机制转换成Bean对象 * * @param map 存放数据的map对象 * @param clazz 待转换的class * @return 转换后的Bean对象 * @throws Exception 异常 */ public static Object mapToBean(Map<String, Object> map, Class clazz) throws Exception { Object obj = clazz.newInstance(); if (map != null && map.size() > 0) { for (Map.Entry<String, Object> entry : map.entrySet()) { String propertyName = entry.getKey(); Object value = entry.getValue(); String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); Field field = getClassField(clazz, propertyName); if (field != null) { Class fieldTypeClass = field.getType(); value = convertValType(value, fieldTypeClass); clazz.getMethod(setMethodName, field.getType()).invoke(obj, value); } } } return obj; } /** * 将Object类型的值,转换成bean对象属性里对应的类型值 * * @param value Object对象值 * @param fieldTypeClass 属性的类型 * @return 转换后的值 */ private static Object convertValType(Object value, Class fieldTypeClass) { Object retVal = null; if (Long.class.getName().equals(fieldTypeClass.getName()) || long.class.getName().equals(fieldTypeClass.getName())) { retVal = Long.parseLong(value.toString()); } else if (Integer.class.getName().equals(fieldTypeClass.getName()) || int.class.getName().equals(fieldTypeClass.getName())) { retVal = Integer.parseInt(value.toString()); } else if (Float.class.getName().equals(fieldTypeClass.getName()) || float.class.getName().equals(fieldTypeClass.getName())) { retVal = Float.parseFloat(value.toString()); } else if (Double.class.getName().equals(fieldTypeClass.getName()) || double.class.getName().equals(fieldTypeClass.getName())) { retVal = Double.parseDouble(value.toString()); } else { retVal = value; } return retVal; } /** * 获取指定字段名称查找在class中的对应的Field对象(包括查找父类) * * @param clazz 指定的class * @param fieldName 字段名称 * @return Field对象 */ private static Field getClassField(Class clazz, String fieldName) { if (Object.class.getName().equals(clazz.getName())) { return null; } Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { if (field.getName().equals(fieldName)) { return field; } } Class superClass = clazz.getSuperclass(); if (superClass != null) {// 简单的递归一下 return getClassField(superClass, fieldName); } return null; } }
[ "jsqfengbao@qq.com" ]
jsqfengbao@qq.com
468b1c9a05338f21cd6b8583c378dbb3c0cda0a4
5f806b2fa65fb3b7b0f5eae98a223413e592d513
/app/src/main/java/com/wordofmouth/Activities/ActivityAbout.java
089e04ecd576d82fa3f1566d1990ed522200931b
[]
no_license
kirilhristov91/WordOfMouth
03404d686e8cbd49919dc80b08e486a328cf8aa4
ca2a787cb843cdeee13bc83a1d6aca4db4f11b04
refs/heads/master
2021-01-10T08:25:27.282544
2016-03-28T21:55:01
2016-03-28T21:55:01
46,728,188
0
0
null
null
null
null
UTF-8
Java
false
false
1,182
java
package com.wordofmouth.Activities; import android.os.Bundle; import android.widget.TextView; import com.wordofmouth.R; public class ActivityAbout extends BaseActivity { TextView aboutText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); aboutText = (TextView) findViewById(R.id.aboutText); String about = "Word Of Mouth is a mobile application that allows users to share their interests with each other." + " Here users manage 'shared' lists of interests with people they know and trust." + " Users can create a list with a specific topic like 'Favourite movies', add items to it and invite people " + "- who they know would like watching movies - to manage the list. Each joined user will then be able to add new" + " items to the list, rate the existing items and invite more people to join. It is easy, so try it and enjoy!"; aboutText.setText(about); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
[ "kirilhristov91@gmail.com" ]
kirilhristov91@gmail.com
c6c33b9afed7cdffd615517ae08fa30e77bfab38
1f7d4d753dbfa4f571f191dca5fbadc15d3c6b5a
/src/BeatBox.java
3c9cf19fa78d969e8dc30c932d44340f95fa5091
[]
no_license
nummyn0rih/BeatBox
0b2f8184adf24bcb0c822eee76b817c8507e39c5
3b677b4242a3a3b1934091ea44e31e83f3ded4d9
refs/heads/master
2020-04-12T03:03:20.777036
2018-12-18T08:46:03
2018-12-18T08:46:03
162,262,383
0
0
null
null
null
null
UTF-8
Java
false
false
5,365
java
import javax.sound.midi.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class BeatBox { JPanel mainPanel; ArrayList<JCheckBox> checkboxList; Sequencer sequencer; Sequence sequence; Track track; JFrame theFrame; String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", "Open Hi-Hat", "Acoustic Snare", "Crash Cymbal", "Hand Clap", "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", "Cowbell", "Vibraslap", "Low-mid Tom", "High Agogo", "Open Hi Conga"}; int[] instruments = {35, 42, 46, 38, 49, 39, 50, 60, 70, 72, 64, 56, 58, 47, 67, 63}; public static void main(String[] args) { new BeatBox().buildGUI(); } public void buildGUI() { theFrame = new JFrame("Cyber BeatBox"); theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); BorderLayout layout = new BorderLayout(); JPanel background = new JPanel(layout); background.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); checkboxList = new ArrayList<JCheckBox>(); Box buttonBox = new Box(BoxLayout.Y_AXIS); JButton start = new JButton("Start"); start.addActionListener(new MyStartListener()); buttonBox.add(start); JButton stop = new JButton("Start"); stop.addActionListener(new MyStopListener()); buttonBox.add(stop); JButton upTempo = new JButton("Start"); upTempo.addActionListener(new MyUpTempoListener()); buttonBox.add(upTempo); JButton downTempo = new JButton("Start"); downTempo.addActionListener(new MyDownTempoListener()); buttonBox.add(downTempo); Box nameBox = new Box(BoxLayout.Y_AXIS); for (int i = 0; i < 16; i++) { nameBox.add(new Label(instrumentNames[i])); } background.add(BorderLayout.EAST, buttonBox); background.add(BorderLayout.WEST, nameBox); theFrame.getContentPane().add(background); GridLayout grid = new GridLayout(16,16); grid.setVgap(1); grid.setHgap(2); mainPanel = new JPanel(grid); background.add(BorderLayout.CENTER, mainPanel); for (int i=0; i<256; i++) { JCheckBox c = new JCheckBox(); c.setSelected(false); checkboxList.add(c); mainPanel.add(c); } setUpMidi(); theFrame.setBounds(50, 50, 300, 300); theFrame.pack(); theFrame.setVisible(true); } public void setUpMidi() { try { sequencer = MidiSystem.getSequencer(); sequencer.open(); sequence = new Sequence(Sequence.PPQ,4); track = sequence.createTrack(); sequencer.setTempoInBPM(120); } catch (Exception e) {e.printStackTrace();} } public void buildTrackAndStart() { int[] trackList = null; sequence.deleteTrack(track); track = sequence.createTrack(); for (int i=0; i<16; i++) { trackList = new int[16]; int key = instruments[i]; for (int j=0; j<16; j++) { JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i)); if (jc.isSelected()) { trackList[j] = key; } else { trackList[j] = 0; } } makeTracks(trackList); track.add(makeEvent(176, 1, 127, 0, 16)); } track.add(makeEvent(192, 9, 1, 0, 15)); try { sequencer.setSequence(sequence); sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY); sequencer.start(); sequencer.setTempoInBPM(120); } catch (Exception e) {e.printStackTrace();} } public class MyStartListener implements ActionListener { public void actionPerformed(ActionEvent a) { buildTrackAndStart(); } } public class MyStopListener implements ActionListener { public void actionPerformed(ActionEvent a) { sequencer.stop(); } } public class MyUpTempoListener implements ActionListener { public void actionPerformed(ActionEvent a) { float tempoFactor = sequencer.getTempoFactor(); sequencer.setTempoFactor((float)(tempoFactor * 1.03)); } } public class MyDownTempoListener implements ActionListener { public void actionPerformed(ActionEvent a) { float tempoFactor = sequencer.getTempoFactor(); sequencer.setTempoFactor((float)(tempoFactor * .97)); } } public void makeTracks(int[] list) { for (int i=0; i<16; i++) { int key = list[i]; if (key != 0) { track.add(makeEvent(144, 9, key, 100, i)); track.add(makeEvent(128, 9, key, 100, i+1)); } } } public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { MidiEvent event = null; try { ShortMessage a = new ShortMessage(); a.setMessage(comd, chan, one, two); event = new MidiEvent(a, tick); } catch (Exception e) {e.printStackTrace();} return event; } }
[ "nummyn0rih@gmail.com" ]
nummyn0rih@gmail.com
26cc63f14b6bae2adb592f03096407e23acbdb8a
68be71ffdaedab6ce1fa4a2416ff87b051637e1d
/src/main/java/com/itzmeds/adfs/client/response/saml/EndpointReference.java
f29be934950e70c0caba0c17785175efbc4014e8
[ "Apache-2.0" ]
permissive
rakeshgowdan/adfs-auth-client
35f5fd61c4d1671990517c248067fc9a0b05dafb
48389c478505f29c3e0e1540ea0bc45f3f6544ca
refs/heads/master
2023-05-27T11:24:27.637344
2018-05-09T13:32:21
2018-05-09T13:32:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,869
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.03.20 at 12:43:08 PM IST // package com.itzmeds.adfs.client.response.saml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "address" }) @XmlRootElement(name = "EndpointReference", namespace = "http://www.w3.org/2005/08/addressing") public class EndpointReference { @XmlElement(name = "Address", namespace = "http://www.w3.org/2005/08/addressing", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String address; /** * Gets the value of the address property. * * @return * possible object is * {@link String } * */ public String getAddress() { return address; } /** * Sets the value of the address property. * * @param value * allowed object is * {@link String } * */ public void setAddress(String value) { this.address = value; } }
[ "itzmedinesh@gmailcom" ]
itzmedinesh@gmailcom
e798d26be680dabac80ee089317d9c1de7b5d0c9
8cb2721bb5d2c25d731ff0086c5fd31092a8da28
/src/main/java/io/chiragpatel/data/streams/throttler/InputStreamThrottler.java
47eba7addf56e07a37abdfd2df10fb14c45ea422
[]
no_license
chipat/throttled-inputstream
44f7392e1b986e4930a82b58428ac3bfc1093022
52c3a2437b89244814601f7d72a86a8498216c4e
refs/heads/master
2018-12-29T05:12:41.030411
2014-09-04T13:32:51
2014-09-04T13:32:51
23,663,525
0
1
null
null
null
null
UTF-8
Java
false
false
303
java
package io.chiragpatel.data.streams.throttler; import java.io.IOException; import java.io.InputStream; /** * Created by Chirag Patel * User: softpsy * Date: 8/29/14 * Time: 12:53 PM */ public interface InputStreamThrottler { void notifyRead(int size); void throttle(long maxWaitTime); }
[ "cpatel001@softwarepsychology.com" ]
cpatel001@softwarepsychology.com
efdaab0210f640440a571799aa6da6a8c45cd47c
d6416d7c97ff4421077b62a26074c6cebab8ae87
/app/src/androidTest/java/com/wwzl/smartportal/ExampleInstrumentedTest.java
75c6a88f8795071d8a46a8c9a4bdac510f29c94a
[]
no_license
zhangcongmin/Android_Common
c22fc25e337c370d35daf6e677f98f34c4e264e8
e7bcfd7107876ad8c35a3e45047c2da1d6339542
refs/heads/master
2021-01-03T05:17:12.592953
2020-02-18T10:01:37
2020-02-18T10:01:37
239,937,880
0
0
null
null
null
null
UTF-8
Java
false
false
711
java
package com.wwzl.smartportal; import android.content.Context; import androidx.test.InstrumentationRegistry; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.wwzl.smartportal", appContext.getPackageName()); } }
[ "721449251@qq.com" ]
721449251@qq.com
05d23f3a938c89f53dd69dc319102935449ee2ee
0c95f0c819535897d74504fb5875b4afb07ae867
/AndroidWrapperProject/app/src/main/java/io/branch/unity/BranchUnityWrapper.java
bb43d3d868b0dbe19b132eaa09526e032b04972b
[ "MIT" ]
permissive
raulpereztangelo/unity-branch-deep-linking-attribution
d0a2ac1b1e0d75af1d3832d2a41b6592e72c9dca
9cf2dd5c55a53360d710b83c4fe8a0cb5940d527
refs/heads/master
2020-05-28T01:52:40.140753
2019-05-27T13:23:18
2019-05-27T13:23:18
188,847,376
0
0
MIT
2019-05-27T13:23:19
2019-05-27T13:20:53
Objective-C
UTF-8
Java
false
false
35,244
java
package io.branch.unity; import android.app.Activity; import android.content.Context; import android.util.Log; import com.unity3d.player.UnityPlayer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Console; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Logger; import java.util.Iterator; import io.branch.indexing.BranchUniversalObject; import io.branch.referral.BranchUtil; import io.branch.referral.util.BRANCH_STANDARD_EVENT; import io.branch.referral.util.ContentMetadata; import io.branch.referral.util.CurrencyType; import io.branch.referral.util.LinkProperties; import io.branch.referral.Branch; import io.branch.referral.BranchError; import io.branch.referral.SharingHelper; import io.branch.referral.Defines; import io.branch.referral.util.ShareSheetStyle; import io.branch.referral.util.BranchEvent; /** * Created by grahammueller on 3/25/15. */ public class BranchUnityWrapper { public static void setBranchKey(String branchKey) { _branchKey = branchKey; } private static Branch.ShareLinkBuilder linkBuilder = null; /** * InitSession methods */ public static void getAutoInstance() { Activity unityActivity = UnityPlayer.currentActivity; Branch.getAutoInstance(unityActivity.getApplicationContext()); } public static void initSession() { Activity unityActivity = UnityPlayer.currentActivity; Branch.getInstance(unityActivity.getApplicationContext(), _branchKey).initSessionWithData(unityActivity.getIntent().getData(), unityActivity); } public static void initSession(boolean isReferrable) { Activity unityActivity = UnityPlayer.currentActivity; // No congruent API here, so borrowing from initSession(callback, referrable, data) method Branch.getInstance(unityActivity.getApplicationContext(), _branchKey).initSession((Branch.BranchReferralInitListener) null, isReferrable, unityActivity.getIntent().getData(), unityActivity); } public static void initSession(String callbackId) { Activity unityActivity = UnityPlayer.currentActivity; Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).initSession(new BranchReferralInitListenerUnityCallback(callbackId), unityActivity.getIntent().getData(), unityActivity); } public static void initSession(String callbackId, boolean isReferrable) { Activity unityActivity = UnityPlayer.currentActivity; Branch.getInstance(unityActivity.getApplicationContext(), _branchKey).initSession(new BranchReferralInitListenerUnityCallback(callbackId), isReferrable, unityActivity.getIntent().getData(), unityActivity); } public static void initSessionWithUniversalObjectCallback(String callbackId) { Activity unityActivity = UnityPlayer.currentActivity; Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).initSession(new BranchUniversalReferralInitListenerUnityCallback(callbackId), unityActivity.getIntent().getData(), unityActivity); } /** * Session Item methods */ public static String getFirstReferringBranchUniversalObject() { BranchUniversalObject branchUniversalObject = null; Branch branchInstance = Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey); if (branchInstance != null && branchInstance.getFirstReferringParams() != null) { JSONObject firstParam = branchInstance.getFirstReferringParams(); try { if (firstParam.has("+clicked_branch_link") && firstParam.getBoolean("+clicked_branch_link")) { branchUniversalObject = BranchUniversalObject.createInstance(firstParam); } } catch (Exception ignore) { } } return _jsonObjectFromBranchUniversalObject(branchUniversalObject).toString(); } public static String getFirstReferringBranchLinkProperties() { LinkProperties linkProperties = null; Branch branchInstance = Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey); if (branchInstance != null && branchInstance.getFirstReferringParams() != null) { JSONObject firstParam = branchInstance.getFirstReferringParams(); try { if (firstParam.has("+clicked_branch_link") && firstParam.getBoolean("+clicked_branch_link")) { linkProperties = new LinkProperties(); if (firstParam.has("channel")) { linkProperties.setChannel(firstParam.getString("channel")); } if (firstParam.has("feature")) { linkProperties.setFeature(firstParam.getString("feature")); } if (firstParam.has("stage")) { linkProperties.setStage(firstParam.getString("stage")); } if (firstParam.has("duration")) { linkProperties.setDuration(firstParam.getInt("duration")); } if (firstParam.has("$match_duration")) { linkProperties.setDuration(firstParam.getInt("$match_duration")); } if (firstParam.has("tags")) { JSONArray tagsArray = firstParam.getJSONArray("tags"); for (int i = 0; i < tagsArray.length(); i++) { linkProperties.addTag(tagsArray.getString(i)); } } Iterator<String> keys = firstParam.keys(); while (keys.hasNext()) { String key = keys.next(); if (key.startsWith("$")) { linkProperties.addControlParameter(key, firstParam.getString(key)); } } } } catch (Exception ignore) { } } return _jsonObjectFromLinkProperties(linkProperties).toString(); } public static String getLatestReferringBranchUniversalObject() { BranchUniversalObject branchUniversalObject = null; Branch branchInstance = Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey); if (branchInstance != null && branchInstance.getLatestReferringParams() != null) { JSONObject latestParam = branchInstance.getLatestReferringParams(); try { if (latestParam.has("+clicked_branch_link") && latestParam.getBoolean("+clicked_branch_link")) { branchUniversalObject = BranchUniversalObject.createInstance(latestParam); } } catch (Exception ignore) { } } return _jsonObjectFromBranchUniversalObject(branchUniversalObject).toString(); } public static String getLatestReferringBranchLinkProperties() { LinkProperties linkProperties = null; Branch branchInstance = Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey); if (branchInstance != null && branchInstance.getLatestReferringParams() != null) { JSONObject latestParam = branchInstance.getLatestReferringParams(); try { if (latestParam.has("+clicked_branch_link") && latestParam.getBoolean("+clicked_branch_link")) { linkProperties = new LinkProperties(); if (latestParam.has("~channel")) { linkProperties.setChannel(latestParam.getString("~channel")); } if (latestParam.has("~feature")) { linkProperties.setFeature(latestParam.getString("~feature")); } if (latestParam.has("~stage")) { linkProperties.setStage(latestParam.getString("~stage")); } if (latestParam.has("~duration")) { linkProperties.setDuration(latestParam.getInt("~duration")); } if (latestParam.has("$match_duration")) { linkProperties.setDuration(latestParam.getInt("$match_duration")); } if (latestParam.has("~tags")) { JSONArray tagsArray = latestParam.getJSONArray("~tags"); for (int i = 0; i < tagsArray.length(); i++) { linkProperties.addTag(tagsArray.getString(i)); } } Iterator<String> keys = latestParam.keys(); while (keys.hasNext()) { String key = keys.next(); if (key.startsWith("$")) { linkProperties.addControlParameter(key, latestParam.getString(key)); } } } } catch (Exception ignore) { } } return _jsonObjectFromLinkProperties(linkProperties).toString(); } public static void resetUserSession() { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).resetUserSession(); } public static void setIdentity(String userId) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).setIdentity(userId); } public static void setIdentity(String userId, String callbackId) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).setIdentity(userId, new BranchReferralInitListenerUnityCallback(callbackId)); } public static void logout() { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).logout(); } /** * Configuration methods */ public static void setDebug() { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).enableSimulateInstalls(); } public static void setRetryInterval(int retryInterval) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).setRetryInterval(retryInterval); } public static void setMaxRetries(int maxRetries) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).setRetryCount(maxRetries); } public static void setNetworkTimeout(int timeout) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).setNetworkTimeout(timeout); } public static void registerView(String universalObjectDict) { try { BranchUniversalObject universalObject = _branchUniversalObjectFromJSONObject(new JSONObject(universalObjectDict)); Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).registerView(universalObject, null); } catch (JSONException jsone) { jsone.printStackTrace(); } } public static void listOnSpotlight(String universalObjectDict) { try { BranchUniversalObject universalObject = _branchUniversalObjectFromJSONObject(new JSONObject(universalObjectDict)); universalObject.listOnGoogleSearch(UnityPlayer.currentActivity.getApplicationContext()); } catch (JSONException jsone) { jsone.printStackTrace(); } } public static void setRequestMetadata(String key, String value) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).setRequestMetadata(key, value); } public static void accountForFacebookSDKPreventingAppLaunch() { } public static void setTrackingDisabled(boolean value) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).disableTracking(value); } /** * User Action methods */ public static void userCompletedAction(String action) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).userCompletedAction(action); } public static void userCompletedAction(String action, String stateDict) { try { JSONObject state = new JSONObject(stateDict); Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).userCompletedAction(action, state); } catch (JSONException jsone) { jsone.printStackTrace(); } } /** * Send Event methods */ public static void sendEvent(String eventData) { if (eventData.isEmpty()) { return; } try { BranchEvent event = null; JSONObject params = new JSONObject(eventData); if (params.has("event_name")) { // try to create standart event for (BRANCH_STANDARD_EVENT type : BRANCH_STANDARD_EVENT.values()) { if (type.getName().equals(params.getString("event_name"))) { event = new BranchEvent(type); break; } } // if standart event can't be created, let's create custom event if (event == null) { event = new BranchEvent(params.getString("event_name")); } } else { return; } if (params.has("transaction_id")) { event.setTransactionID(params.getString("transaction_id")); } if (params.has("affiliation")) { event.setAffiliation(params.getString("affiliation")); } if (params.has("coupon")) { event.setCoupon(params.getString("coupon")); } if (params.has("currency")) { event.setCurrency(CurrencyType.getValue(params.getString("currency"))); } if (params.has("tax")) { event.setTax(params.getDouble("tax")); } if (params.has("revenue")) { event.setRevenue(params.getDouble("revenue")); } if (params.has("description")) { event.setDescription(params.getString("description")); } if (params.has("shipping")) { event.setRevenue(params.getDouble("shipping")); } if (params.has("search_query")) { event.setSearchQuery(params.getString("search_query")); } if (params.has("custom_data")) { JSONObject dict = params.getJSONObject("custom_data"); Iterator<String> keys = dict.keys(); while (keys.hasNext()) { String key = keys.next(); event.addCustomDataProperty(key, dict.getString(key)); } } if (params.has("content_items")) { JSONArray array = params.getJSONArray("content_items"); for (int i = 0; i < array.length(); i++) { event.addContentItems( _branchUniversalObjectFromJSONObject(new JSONObject(array.get(i).toString())) ); } } // log event event.logEvent(UnityPlayer.currentActivity.getApplicationContext()); } catch (JSONException jsone) { jsone.printStackTrace(); } } /** * Credit methods */ public static void loadRewards(String callbackId) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).loadRewards(new BranchReferralInitListenerUnityCallback(callbackId)); } public static int getCredits() { return Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).getCredits(); } public static void redeemRewards(int count) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).redeemRewards(count); } public static int getCreditsForBucket(String bucket) { return Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).getCreditsForBucket(bucket); } public static void redeemRewards(String bucket, int count) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).redeemRewards(bucket, count); } public static void getCreditHistory(String callbackId) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).getCreditHistory(new BranchReferralInitListenerUnityCallback(callbackId)); } public static void getCreditHistory(String bucket, String callbackId) { Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).getCreditHistory(bucket, new BranchReferralInitListenerUnityCallback(callbackId)); } public static void getCreditHistory(String creditTransactionId, int length, int order, String callbackId) { Branch.CreditHistoryOrder creditHistoryOrder = order == 0 ? Branch.CreditHistoryOrder.kMostRecentFirst : Branch.CreditHistoryOrder.kLeastRecentFirst; Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).getCreditHistory(creditTransactionId, length, creditHistoryOrder, new BranchReferralInitListenerUnityCallback(callbackId)); } public static void getCreditHistory(String bucket, String creditTransactionId, int length, int order, String callbackId) { Branch.CreditHistoryOrder creditHistoryOrder = order == 0 ? Branch.CreditHistoryOrder.kMostRecentFirst : Branch.CreditHistoryOrder.kLeastRecentFirst; Branch.getInstance(UnityPlayer.currentActivity.getApplicationContext(), _branchKey).getCreditHistory(bucket, creditTransactionId, length, creditHistoryOrder, new BranchReferralInitListenerUnityCallback(callbackId)); } /** * Short URL Generation methods */ public static void getShortURLWithBranchUniversalObject(String universalObjectDict, String linkPropertiesDict, String callbackId) { try { BranchUniversalObject universalObject = _branchUniversalObjectFromJSONObject(new JSONObject(universalObjectDict)); LinkProperties linkProperties = _linkPropertiesFromJSONObject(new JSONObject(linkPropertiesDict)); universalObject.generateShortUrl(UnityPlayer.currentActivity.getApplicationContext(), linkProperties, new BranchReferralInitListenerUnityCallback(callbackId)); } catch (JSONException jsone) { jsone.printStackTrace(); } } /** * Share methods */ public static void shareLinkWithLinkProperties(String universalObjectDict, String linkPropertiesDict, String message, String callbackId) { try { BranchUniversalObject universalObject = _branchUniversalObjectFromJSONObject(new JSONObject(universalObjectDict)); LinkProperties linkProperties = _linkPropertiesFromJSONObject(new JSONObject(linkPropertiesDict)); ShareSheetStyle style = new ShareSheetStyle(UnityPlayer.currentActivity.getApplicationContext(), "", message); style.addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK); style.addPreferredSharingOption(SharingHelper.SHARE_WITH.TWITTER); style.addPreferredSharingOption(SharingHelper.SHARE_WITH.MESSAGE); style.addPreferredSharingOption(SharingHelper.SHARE_WITH.EMAIL); style.addPreferredSharingOption(SharingHelper.SHARE_WITH.FLICKR); style.addPreferredSharingOption(SharingHelper.SHARE_WITH.GOOGLE_DOC); style.addPreferredSharingOption(SharingHelper.SHARE_WITH.WHATS_APP); universalObject.showShareSheet(UnityPlayer.currentActivity, linkProperties, style, new BranchReferralInitListenerUnityCallback(callbackId)); } catch (JSONException jsone) { jsone.printStackTrace(); } } /** * Util methods */ private static Date _dateFromString(String dateString) { Date date = null; if (dateString.length() > 0) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); try { date = format.parse(dateString); } catch (ParseException pe) { pe.printStackTrace(); } } return date; } private static JSONObject _jsonObjectFromBranchUniversalObject(BranchUniversalObject obj) { JSONObject jsonObject = new JSONObject(); if (obj != null) { try { jsonObject.put(Defines.Jsonkey.CanonicalIdentifier.getKey(), obj.getCanonicalIdentifier()); jsonObject.put(Defines.Jsonkey.CanonicalUrl.getKey(), obj.getCanonicalUrl()); jsonObject.put(Defines.Jsonkey.ContentTitle.getKey(), obj.getTitle()); jsonObject.put(Defines.Jsonkey.ContentDesc.getKey(), obj.getDescription()); jsonObject.put(Defines.Jsonkey.ContentImgUrl.getKey(), obj.getImageUrl()); jsonObject.put(Defines.Jsonkey.PublicallyIndexable.getKey(), obj.isPublicallyIndexable() ? "0" : "1"); jsonObject.put(Defines.Jsonkey.LocallyIndexable.getKey(), obj.isLocallyIndexable() ? "0" : "1"); jsonObject.put(Defines.Jsonkey.ContentKeyWords.getKey(), new JSONArray(obj.getKeywords())); jsonObject.put(Defines.Jsonkey.ContentExpiryTime.getKey(), Long.toString(obj.getExpirationTime())); jsonObject.put("metadata", obj.getContentMetadata().convertToJson()); } catch (JSONException jsone) { jsone.printStackTrace(); } } return jsonObject; } private static JSONObject _jsonObjectFromLinkProperties(LinkProperties link) { JSONObject jsonObject = new JSONObject(); if (link != null) { try { jsonObject.put("~tags", new JSONArray(link.getTags())); jsonObject.put("~feature", link.getFeature()); jsonObject.put("~alias", link.getAlias()); jsonObject.put("~stage", link.getStage()); jsonObject.put("~duration", link.getMatchDuration()); jsonObject.put("~channel", link.getChannel()); jsonObject.put("control_params", new JSONObject(link.getControlParams())); } catch (JSONException jsone) { jsone.printStackTrace(); } } return jsonObject; } private static BranchUniversalObject _branchUniversalObjectFromJSONObject(JSONObject params) { BranchUniversalObject branchUniversalObject = new BranchUniversalObject(); try { if (params.has(Defines.Jsonkey.ContentTitle.getKey())) { branchUniversalObject.setTitle(params.getString(Defines.Jsonkey.ContentTitle.getKey())); } if (params.has(Defines.Jsonkey.CanonicalIdentifier.getKey())) { branchUniversalObject.setCanonicalIdentifier(params.getString(Defines.Jsonkey.CanonicalIdentifier.getKey())); } if (params.has(Defines.Jsonkey.CanonicalUrl.getKey())) { branchUniversalObject.setCanonicalUrl(params.getString(Defines.Jsonkey.CanonicalUrl.getKey())); } if (params.has(Defines.Jsonkey.ContentKeyWords.getKey())) { JSONArray keywordJsonArray = params.getJSONArray(Defines.Jsonkey.ContentKeyWords.getKey()); for (int i = 0; i < keywordJsonArray.length(); i++) { branchUniversalObject.addKeyWord(keywordJsonArray.get(i).toString()); } } if (params.has(Defines.Jsonkey.ContentDesc.getKey())) { branchUniversalObject.setContentDescription(params.getString(Defines.Jsonkey.ContentDesc.getKey())); } if (params.has(Defines.Jsonkey.ContentImgUrl.getKey())) { branchUniversalObject.setContentImageUrl(params.getString(Defines.Jsonkey.ContentImgUrl.getKey())); } if (params.has(Defines.Jsonkey.PublicallyIndexable.getKey())) { branchUniversalObject.setContentIndexingMode( params.getString(Defines.Jsonkey.PublicallyIndexable.getKey()).equals("0") ? BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC : BranchUniversalObject.CONTENT_INDEX_MODE.PRIVATE); } if (params.has(Defines.Jsonkey.LocallyIndexable.getKey())) { branchUniversalObject.setLocalIndexMode( params.getString(Defines.Jsonkey.LocallyIndexable.getKey()).equals("0") ? BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC : BranchUniversalObject.CONTENT_INDEX_MODE.PRIVATE); } if (params.has(Defines.Jsonkey.ContentExpiryTime.getKey())) { if (!params.getString(Defines.Jsonkey.ContentExpiryTime.getKey()).isEmpty()) { branchUniversalObject.setContentExpiration(new Date(Long.decode(params.getString(Defines.Jsonkey.ContentExpiryTime.getKey())))); } } if (params.has("metadata")) { JSONObject dict = new JSONObject(params.getString("metadata")); if (dict != null) { ContentMetadata cmd = ContentMetadata.createFromJson(new BranchUtil.JsonReader(dict)); if (cmd != null) { branchUniversalObject.setContentMetadata(cmd); } } } } catch (Exception ignore) { } return branchUniversalObject; } private static LinkProperties _linkPropertiesFromJSONObject(JSONObject params) { LinkProperties linkProperties = new LinkProperties(); try { if (params.has("~channel")) { linkProperties.setChannel(params.getString("~channel")); } if (params.has("~feature")) { linkProperties.setFeature(params.getString("~feature")); } if (params.has("~stage")) { linkProperties.setStage(params.getString("~stage")); } if (params.has("~duration")) { linkProperties.setDuration(Long.valueOf(params.getString("~duration")).intValue()); } if (params.has("~tags")) { JSONArray tagsArray = params.getJSONArray("~tags"); for (int i = 0; i < tagsArray.length(); i++) { linkProperties.addTag(tagsArray.getString(i)); } } if (params.has("control_params")) { JSONObject dict = params.getJSONObject("control_params"); Iterator<String> keys = dict.keys(); while (keys.hasNext()) { String key = keys.next(); linkProperties.addControlParameter(key, dict.getString(key)); } } } catch (Exception ignore) { } return linkProperties; } private static String _branchKey; /** * Callback for Unity */ private static class BranchReferralInitListenerUnityCallback implements Branch.BranchReferralInitListener, Branch.BranchReferralStateChangedListener, Branch.BranchListResponseListener, Branch.BranchLinkCreateListener, Branch.BranchLinkShareListener { public BranchReferralInitListenerUnityCallback(String callbackId) { _callbackId = callbackId; } @Override public void onInitFinished(JSONObject params, BranchError branchError) { _sendMessageWithWithBranchError("_asyncCallbackWithParams", branchError, "params", params); } @Override public void onStateChanged(boolean changed, BranchError branchError) { _sendMessageWithWithBranchError("_asyncCallbackWithStatus", branchError, "status", changed); } @Override public void onReceivingResponse(JSONArray list, BranchError branchError) { _sendMessageWithWithBranchError("_asyncCallbackWithList", branchError, "list", list); } @Override public void onLinkCreate(String url, BranchError branchError) { _sendMessageWithWithBranchError("_asyncCallbackWithUrl", branchError, "url", url); } @Override public void onShareLinkDialogLaunched() { } @Override public void onShareLinkDialogDismissed() { try { if (!_linkShared) { JSONObject params = new JSONObject(); params.put("sharedLink", ""); params.put("sharedChannel", ""); _sendMessageWithWithBranchError("_asyncCallbackWithParams", null, "params", params); } } catch (JSONException jsone) { jsone.printStackTrace(); } } @Override public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError branchError) { try { JSONObject params = new JSONObject(); params.put("sharedLink", sharedLink); params.put("sharedChannel", sharedChannel); _sendMessageWithWithBranchError("_asyncCallbackWithParams", branchError, "params", params); _linkShared = true; } catch (JSONException jsone) { jsone.printStackTrace(); } } @Override public void onChannelSelected(java.lang.String selectedChannel) { _sendMessageWithWithBranchError("_asyncCallbackWithParams", null, "selectedChannel", selectedChannel); _linkShared = true; } private void _sendMessageWithWithBranchError(String asyncCallbackMethod, BranchError branchError, String extraKey, Object extraValue) { try { JSONObject responseObject = new JSONObject(); responseObject.put("callbackId", _callbackId); responseObject.put(extraKey, extraValue); responseObject.put("error", branchError == null ? null : branchError.getMessage()); String respString = responseObject.toString(); UnityPlayer.UnitySendMessage("Branch", asyncCallbackMethod, respString); } catch (JSONException jsone) { // nothing to do here jsone.printStackTrace(); } } private String _callbackId; private Boolean _linkShared = false; } private static class BranchUniversalReferralInitListenerUnityCallback implements Branch.BranchUniversalReferralInitListener, Branch.BranchReferralStateChangedListener, Branch.BranchListResponseListener, Branch.BranchLinkCreateListener, Branch.BranchLinkShareListener { public BranchUniversalReferralInitListenerUnityCallback(String callbackId) { _callbackId = callbackId; } @Override public void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError branchError) { try { JSONObject params = new JSONObject(); params.put("universalObject", _jsonObjectFromBranchUniversalObject(branchUniversalObject)); params.put("linkProperties", _jsonObjectFromLinkProperties(linkProperties)); _sendMessageWithWithBranchError("_asyncCallbackWithBranchUniversalObject", branchError, "params", params); } catch (JSONException jsone) { jsone.printStackTrace(); } } @Override public void onStateChanged(boolean changed, BranchError branchError) { _sendMessageWithWithBranchError("_asyncCallbackWithStatus", branchError, "status", changed); } @Override public void onReceivingResponse(JSONArray list, BranchError branchError) { _sendMessageWithWithBranchError("_asyncCallbackWithList", branchError, "list", list); } @Override public void onLinkCreate(String url, BranchError branchError) { _sendMessageWithWithBranchError("_asyncCallbackWithUrl", branchError, "url", url); } @Override public void onShareLinkDialogLaunched() { } @Override public void onShareLinkDialogDismissed() { try { if (!_linkShared) { JSONObject params = new JSONObject(); params.put("sharedLink", ""); params.put("sharedChannel", ""); _sendMessageWithWithBranchError("_asyncCallbackWithParams", null, "params", params); } } catch (JSONException jsone) { jsone.printStackTrace(); } } @Override public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError branchError) { try { JSONObject params = new JSONObject(); params.put("sharedLink", sharedLink); params.put("sharedChannel", sharedChannel); _sendMessageWithWithBranchError("_asyncCallbackWithParams", branchError, "params", params); _linkShared = true; } catch (JSONException jsone) { jsone.printStackTrace(); } } @Override public void onChannelSelected(java.lang.String selectedChannel) { _sendMessageWithWithBranchError("_asyncCallbackWithParams", null, "selectedChannel", selectedChannel); _linkShared = true; } private void _sendMessageWithWithBranchError(String asyncCallbackMethod, BranchError branchError, String extraKey, Object extraValue) { try { JSONObject responseObject = new JSONObject(); responseObject.put("callbackId", _callbackId); responseObject.put(extraKey, extraValue); responseObject.put("error", branchError == null ? null : branchError.getMessage()); String respString = responseObject.toString(); UnityPlayer.UnitySendMessage("Branch", asyncCallbackMethod, respString); } catch (JSONException jsone) { // nothing to do here jsone.printStackTrace(); } } private String _callbackId; private Boolean _linkShared = false; } }
[ "anton1980@tut.by" ]
anton1980@tut.by
c33d891ec3953b144525911e8bc3fcb295e7e2d8
c03a28264a1da6aa935a87c6c4f84d4d28afe272
/Leetcode/src/medium/Q221_Maximal_Square.java
d0bb85eaaf3252b6f940dff33304d9cab8941f4a
[]
no_license
bbfeechen/Algorithm
d59731686f06d6f4d4c13d66a8963f190a84f361
87a158a608d842e53e13bccc73526aadd5d129b0
refs/heads/master
2021-04-30T22:35:03.499341
2019-05-03T07:26:15
2019-05-03T07:26:15
7,991,128
1
1
null
null
null
null
UTF-8
Java
false
false
1,318
java
package medium; public class Q221_Maximal_Square { public static int maximalSquare(char[][] matrix) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { return 0; } int m = matrix.length; int n = matrix[0].length; int[][] dp = new int[m][n]; for(int i = 0; i < m; i++) { dp[i][0] = Integer.valueOf(matrix[i][0] + ""); } for(int j = 0; j < n; j++) { dp[0][j] = Integer.valueOf(matrix[0][j] + ""); } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { if(matrix[i][j] == '1') { dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; } else { dp[i][j] = 0; } } } int max = Integer.MIN_VALUE; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { max = Math.max(max, dp[i][j]); } } return max * max; } public static void main(String[] args) { char[][] matrix = {{'1', '0', '1', '0', '0'}, {'1', '0', '1', '1', '1'}, {'1', '1', '1', '1', '1'}, {'1', '0', '0', '1', '0'}}; System.out.println(maximalSquare(matrix)); } }
[ "bbfeechen@gmail.com" ]
bbfeechen@gmail.com
f48e17a89e2e3d7eb057a202c11847fbd9417103
0860e7f8816b47ef86c64afba75b1964226a8425
/plugin.idea/src/com/microsoft/alm/plugin/idea/ui/authentication/DeviceFlowResponsePromptDialog.java
a55040ecea5c54f82073a6a986d2641ec0bf3413
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Paradox-Cascade/vso-intellij
0495831cdcbfb048111018dbcf67554e143811e5
893e1cdbb4df8997e87e02a5977cc41102c9c390
refs/heads/master
2021-01-20T16:09:33.069691
2016-05-25T18:34:38
2016-05-25T18:34:38
59,692,000
1
0
null
2016-05-25T19:33:29
2016-05-25T19:33:29
null
UTF-8
Java
false
false
1,701
java
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.alm.plugin.idea.ui.authentication; import com.microsoft.alm.auth.oauth.DeviceFlowResponse; import com.microsoft.alm.plugin.idea.resources.TfPluginBundle; import com.microsoft.alm.plugin.idea.ui.common.BaseDialogImpl; import org.jetbrains.annotations.Nullable; import javax.swing.JComponent; import javax.swing.JPanel; import java.awt.Dimension; import java.util.Collections; public class DeviceFlowResponsePromptDialog extends BaseDialogImpl { public static final String DEVICE_FLOW_PROMPT_DIALOG_CONTEXT = "DeviceFlowLogin"; private DeviceFlowResponsePromptForm deviceFlowResponsePromptForm; public DeviceFlowResponsePromptDialog(){ super(null, TfPluginBundle.message(TfPluginBundle.KEY_DEVICE_FLOW_PROMPT_TITLE), TfPluginBundle.message(TfPluginBundle.KEY_DEVICE_FLOW_PROMPT_CONTINUE_BUTTON), DEVICE_FLOW_PROMPT_DIALOG_CONTEXT, //feedback context false, Collections.<String, Object>emptyMap()); } public void setResponse(final DeviceFlowResponse response) { this.deviceFlowResponsePromptForm.setResponse(response); } @Nullable @Override protected JComponent createCenterPanel() { deviceFlowResponsePromptForm = new DeviceFlowResponsePromptForm(); final JPanel deviceFlowResponsePanel = deviceFlowResponsePromptForm.getContentPanel(); deviceFlowResponsePanel.setPreferredSize(new Dimension(360, 140)); return deviceFlowResponsePanel; } public void dismiss() { this.dispose(); } }
[ "yacao@microsoft.com" ]
yacao@microsoft.com
6d6d130ac4e068c1b5c10a9504890c5317eb428b
a69b31dacef1270b65110e2dcefc995017281888
/src/main/java/com/hryun/gtranslate/Translate.java
aec80676e40454ede21623c27a2891ad53856579
[]
no_license
leparlon/google-translate
037f71992439b2ae805bb7457f2598e6d249db77
d47b80f0149a9c0eac98de58b2852ba0e752e325
refs/heads/master
2021-01-22T01:55:34.187646
2014-09-02T19:19:27
2014-09-02T19:19:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,535
java
/** * @author Vinícius Egidio (vegidio@gmail.com) * @since Apr 28th 2014 * v1.0 */ package com.hryun.gtranslate; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Translate { private String sourceLang; private String destLang; private String sourceText; private String destText; public Translate() { initialize(); } private void initialize() { sourceLang = ""; destLang = ""; sourceText = ""; destText = ""; } public String execute() { destText = ""; // Check if we have all variables set if(sourceLang.isEmpty() || sourceText.isEmpty() || destLang.isEmpty()) { System.err.println("Missing parameters; please set the Source Language, Destination Language and the " + "Source Text first"); } else { execute(sourceText, sourceLang, destLang); } return destText; } public String execute(String text, String sl, String dl) { String regex, temp, params = null; StringBuilder translated = new StringBuilder(); Matcher matcher; Pattern pattern; // We initialize the variables first initialize(); sourceLang = sl; destLang = dl; sourceText = text; // URL enconding the text try { params = "q=" + URLEncoder.encode(text, "UTF-8"); } catch(UnsupportedEncodingException e) { e.printStackTrace(); } // Creating the URL String url = "https://translate.google.com/translate_a/single?client=t&sl=" + sourceLang + "&tl=" + destLang + "&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&dt=sw&ie=UTF-8&oe=UTF-8&prev=btn" + "&ssel=0&tsel=0"; // Get the JS String js = sendPost(url, params); // Parse the JS regex = "\\[\\[(.*?)\\]\\]"; pattern = Pattern.compile(regex); matcher = pattern.matcher(js); if(matcher.find()) { temp = matcher.group(1); regex = "\\[\"(.*?)\",\""; pattern = Pattern.compile(regex); matcher = pattern.matcher(temp); while(matcher.find()) translated.append(matcher.group(1)); destText = translated.toString(); // Removing unnecessary spaces destText = destText.replace(" .", ".") .replace(" ,", ",") .replace(" -", "-") .replace(" ;", ";") .replace(" :", ":") .replace("( ", "(") .replace(" )", ")"); } return destText; } private String sendPost(String urlString, String params) { String line; StringBuffer html = new StringBuffer(); try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); // Fake the User-Agent conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); // Setting the post parameters conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); // Check the HTTP response code if(conn.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); // Reading the HTML while((line = in.readLine()) != null) html.append(line.trim()); in.close(); } // Close the connection conn.disconnect(); } catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } return html.toString(); } /** * @return the sourceLang */ public String getSourceLang() { return sourceLang; } /** * @param sourceLang the sourceLang to set */ public void setSourceLang(String sourceLang) { this.sourceLang = sourceLang; } /** * @return the destLang */ public String getDestLang() { return destLang; } /** * @param destLang the destLang to set */ public void setDestLang(String destLang) { this.destLang = destLang; } /** * @return the sourceText */ public String getSourceText() { return sourceText; } /** * @param sourceText the sourceText to set */ public void setSourceText(String sourceText) { this.sourceText = sourceText; } /** * @return the destText */ public String getDestText() { return destText; } }
[ "vegidio@gmail.com" ]
vegidio@gmail.com
fa960455c6b3e3606a07eec312485dd081312af6
c0190c3c9af06ddef2a45a44eba76b19df3468f6
/src/main/java/eu/softelo/microservices/qbit/QBitApplication.java
6ff43f346e1178526f6609c897bb126285e0aae3
[]
no_license
damianbl/qbit
8fc0f7e0e2aafe16978337acf0f08ade25905142
b220cc7f34e91699841aa08bf3a091d50910bee4
refs/heads/master
2021-01-02T08:14:12.275494
2015-07-05T10:38:39
2015-07-05T10:38:39
38,565,334
0
0
null
null
null
null
UTF-8
Java
false
false
636
java
package eu.softelo.microservices.qbit; import eu.softelo.microservices.qbit.service.TodoService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class QBitApplication { public static void main(String[] args) { SpringApplication.run(QBitApplication.class, args); } @Bean public TodoService todoService() { return new TodoService(); } @Bean public DispatcherServlet dispatcherServlet() { return new DispatcherServlet(); } }
[ "damian.blazejewski@mobica.com" ]
damian.blazejewski@mobica.com
4657abaebc7c8023dd6ae89b2d4ab25501be8a0d
f9cdd0fb7c464464d29d48b4d617b04f094855e8
/BikeDriver/src/main/java/mx/com/labuena/bikedriver/data/BaseColumns.java
820ed57cb5606c5d4fa168a7b53f0888791b2bb6
[]
no_license
naushadqamar/Capstone-Project
503f494ba7b7659a0e5ff37645948b7548312694
8fcdc415ebe471a18fcc5a5aba612d3184ed57cc
refs/heads/master
2021-01-01T17:09:03.764368
2016-09-05T19:54:04
2016-09-05T19:54:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
341
java
package mx.com.labuena.bikedriver.data; /** * Base columns of a row. * Created by clemente on 7/30/15. */ public interface BaseColumns { /** * The unique id of a row. */ public static final String ID = "_id"; /** * The count of rows in a directory. */ public static final String _COUNT = "_count"; }
[ "morales.fernandez.clemente@gmail.com" ]
morales.fernandez.clemente@gmail.com
c32681cefa8763f37b85954fa43b69fea72e8bd7
6000edbe01f35679b1cf510575d547a6bb5e430c
/core/src/test/java/org/apache/logging/log4j/core/lookup/ContextMapLookupTest.java
4c5672a90f8cd2c5bac62bad7c2e11b6e816f220
[ "Apache-2.0" ]
permissive
JavaQualitasCorpus/log4j-2.0-beta
7cdd1a06e6b786bca3180c1fe1d077d0044b2b40
1aec5ba88965528ce8c3649b5d6f0136dc942c74
refs/heads/master
2023-08-12T09:29:17.392341
2020-06-02T18:02:37
2020-06-02T18:02:37
167,004,977
0
0
Apache-2.0
2022-12-16T01:21:49
2019-01-22T14:08:39
Java
UTF-8
Java
false
false
1,469
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.lookup; import org.apache.logging.log4j.ThreadContext; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * */ public class ContextMapLookupTest { private static final String TESTKEY = "TestKey"; private static final String TESTVAL = "TestValue"; @Test public void testLookup() { ThreadContext.put(TESTKEY, TESTVAL); final StrLookup lookup = new ContextMapLookup(); String value = lookup.lookup(TESTKEY); assertEquals(TESTVAL, value); value = lookup.lookup("BadKey"); assertNull(value); } }
[ "taibi@sonar-scheduler.rd.tut.fi" ]
taibi@sonar-scheduler.rd.tut.fi
16c79187ac969ee9765bb575f1fdeb828464b0f1
8e0042f0297ea1755cbdf5e19ae958aca4c917d3
/app/src/main/java/com/example/taqtile/myapplication/activities/MainActivity.java
7b0505a56fa2584dce23c36f1e5d7eb96ca133be
[]
no_license
jonatasvcosta/ProjectLayouts
85cd392696d8d09826f7d4e88cac362fc63def21
4fae29ab842313a3b4a7e08041053698ce30d6b5
refs/heads/master
2021-01-10T09:58:41.977310
2016-01-19T11:43:40
2016-01-19T11:43:40
49,948,683
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package com.example.taqtile.myapplication.activities; import android.os.Bundle; import com.example.taqtile.myapplication.R; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
[ "felipe.koji2@gmail.com" ]
felipe.koji2@gmail.com
7d48ebc5c76687ff050b0f382acfa1558ec9e087
c88db7a4526a4b54c88cc2c5ecf5262a6bc3c892
/app/src/main/java/com/gwmaster/wifilocater/Calculation/Point.java
52758ac048dff975b47682b1c6363137e82d5db0
[]
no_license
areszz/universityWork
bacfb8fa1b837b2f2bb9a736a44e11bd4a6f02b0
c45075d59de6ce25ee9c171dc8c7f03eb56d1af3
refs/heads/master
2023-06-19T01:36:00.896095
2021-07-22T12:10:15
2021-07-22T12:10:15
388,442,780
0
0
null
null
null
null
UTF-8
Java
false
false
799
java
package com.gwmaster.wifilocater.Calculation; public class Point { private AP AP1,AP2,AP3,AP4; private int id; private int x,y; public Point(int id,int x,int y){ this.id = id; this.x = x; this.y = y; } public Point() { } // public void setAP1(int AP1) { // this.AP1.level1 = AP1; // } // public void setAP2(int AP2) { // this.AP2 = AP2; // } // public void setAP3(int AP3) { // this.AP3 = AP3; // } // public void setAP4(int AP4) { // this.AP4 = AP4; // } // public int getAP1() { // return AP1; // } // public int getAP2() { // return AP2; // } // public int getAP3() { // return AP3; // } // public int getAP4() { // return AP4; // } }
[ "860288200@qq.com" ]
860288200@qq.com
855f0900fdd3483054550b7b0a178a97225eadbb
7afdb4413e4a3890407006b8ec06505f92ece3c0
/src/main/java/com/software/estudialo/entities/PasswordResetToken.java
64ea17672937bd02a3b1b9e87a1760fa976a9436
[]
no_license
jhorber95/java-elo
9839194c2dc826201e29c51076e975cbfad4e362
11a35338d6fd9656fcf275e45784eefde0723337
refs/heads/master
2023-01-11T02:49:55.658542
2019-12-02T00:26:27
2019-12-02T00:26:27
225,247,596
0
0
null
2022-12-31T04:42:10
2019-12-01T23:37:05
CSS
UTF-8
Java
false
false
1,071
java
package com.software.estudialo.entities; import java.util.Calendar; import java.util.Date; public class PasswordResetToken { private Long id; private String token; private Usuario user; private Date expiryDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Usuario getUser() { return user; } public void setUser(Usuario user) { this.user = user; } public Date getExpiryDate() { return expiryDate; } public void setExpiryDate(Date expiryDate) { this.expiryDate = expiryDate; } public void setExpiryDate(int minutes){ Calendar now = Calendar.getInstance(); now.add(Calendar.MINUTE, minutes); this.expiryDate = now.getTime(); } public boolean isExpired() { return new Date().after(this.expiryDate); } }
[ "jhorber95@gmail.com" ]
jhorber95@gmail.com
d06ccae625ae4af833e49410c04055b9da515402
91ea7fe5052cd92cfc92f75e97a1913e4cfef051
/app/src/main/java/com/example/mjd/imitate_jd/fragment/HomeFragment.java
4cbdedb79bee4b14ca2659cf0dfc83cb4201529c
[]
no_license
burlife/MyJd
c3d0c1e67b6cff54cc44667bf146c0f103847bfd
494b912ca9a167e85f77c9a3ba74f101e1482fe0
refs/heads/master
2020-03-26T17:53:39.707979
2018-08-18T03:15:03
2018-08-18T03:15:03
145,185,874
0
0
null
null
null
null
UTF-8
Java
false
false
10,824
java
package com.example.mjd.imitate_jd.fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; import com.example.mjd.imitate_jd.R; import com.example.mjd.imitate_jd.activity.BaseFragment; import com.example.mjd.imitate_jd.activity.SaoActivity; import com.example.mjd.imitate_jd.activity.SousuoActivity; import com.example.mjd.imitate_jd.activity.XiangqingActivity; import com.example.mjd.imitate_jd.mvp.classify.bean.Zean; import com.example.mjd.imitate_jd.mvp.home.adapter.HomMsAdapter; import com.example.mjd.imitate_jd.mvp.home.adapter.HomeTjAdapter; import com.example.mjd.imitate_jd.mvp.home.adapter.MyHomeVpAdapter; import com.example.mjd.imitate_jd.mvp.home.adapter.MyOneGvAdapter1; import com.example.mjd.imitate_jd.mvp.home.adapter.MyOneGvAdapter2; import com.example.mjd.imitate_jd.mvp.home.bean.HomeBean; import com.example.mjd.imitate_jd.bean.Xiangbean; import com.example.mjd.imitate_jd.mvp.home.presenter.HomePresenter; import com.example.mjd.imitate_jd.utils.Imagebanner; import com.example.mjd.imitate_jd.mvp.home.view.IHomeView; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.youth.banner.Banner; import java.sql.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; public class HomeFragment extends BaseFragment<HomePresenter> implements IHomeView { @BindView(R.id.one_bn) Banner oneBn; @BindView(R.id.one_sdv) SimpleDraweeView oneSdv; @BindView(R.id.one_vp) ViewPager onevp; TextView oneTvSecond; @BindView(R.id.one_xsqg) LinearLayout oneXsqg; @BindView(R.id.one_ms_recy) RecyclerView oneMsRecy; @BindView(R.id.one_tj_recy) RecyclerView oneTjRecy; Unbinder unbinder; List<GridView> listgv; GridView gv1; GridView gv2; MyHomeVpAdapter vpadapter; HomMsAdapter msAdapter; HomeTjAdapter tjAdapter; @BindView(R.id.one_vf) ViewFlipper oneVf; List<HomeBean.MiaoshaBean.ListBeanX> listms; List<HomeBean.TuijianBean.ListBean> listtj; EditText editText; private TextView miaosha_time; private TextView miaosha_shi; private TextView miaosha_minter; private TextView miaosha_second; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); setTime(); sendEmptyMessageDelayed(0, 1000); } }; private void setTime() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis()); String format = df.format(curDate); StringBuffer buffer = new StringBuffer(); String substring = format.substring(0, 11); buffer.append(substring); Log.d("ccc", substring); Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour % 2 == 0) { miaosha_time.setText(hour + "点场"); buffer.append((hour + 2)); buffer.append(":00:00"); } else { miaosha_time.setText((hour - 1) + "点场"); buffer.append((hour + 1)); buffer.append(":00:00"); } String totime = buffer.toString(); try { java.util.Date date = df.parse(totime); java.util.Date date1 = df.parse(format); long defferenttime = date.getTime() - date1.getTime(); long days = defferenttime / (1000 * 60 * 60 * 24); long hours = (defferenttime - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60); long minute = (defferenttime - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60); long seconds = defferenttime % 60000; long second = Math.round((float) seconds / 1000); miaosha_shi.setText("0" + hours + ""); if (minute >= 10) { miaosha_minter.setText(minute + ""); } else { miaosha_minter.setText("0" + minute + ""); } if (second >= 10) { miaosha_second.setText(second + ""); } else { miaosha_second.setText("0" + second + ""); } } catch (ParseException e) { e.printStackTrace(); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = View.inflate(getActivity(), R.layout.home_fragment, null); unbinder = ButterKnife.bind(this, view); ImageView sao=view.findViewById(R.id.sy_sao); sao.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new IntentIntegrator(getActivity()) .setCaptureActivity(SaoActivity.class) .initiateScan();//初始化扫描 } }); initData(); initgif(); initVP(); //实现跑马灯 initVF(); initClick(); miaosha_time = (TextView) view.findViewById(R.id.tv_miaosha_time); miaosha_shi = (TextView) view.findViewById(R.id.tv_miaosha_shi); miaosha_minter = (TextView) view.findViewById(R.id.tv_miaosha_minter); miaosha_second = (TextView) view.findViewById(R.id.tv_miaosha_second); handler.sendEmptyMessage(0); return view; } private void initClick() { } //实现跑马灯 private void initVF() { oneVf.addView(View.inflate(getActivity(), R.layout.fragment_one_vf_item, null)); oneVf.addView(View.inflate(getActivity(), R.layout.fragment_one_vf_item1, null)); oneVf.addView(View.inflate(getActivity(), R.layout.fragment_one_vf_item2, null)); } //显示京东超市的viewpager的页面 private void initVP() { listgv = new ArrayList<>(); gv1 = new GridView(getActivity()); gv1.setNumColumns(5); gv2 = new GridView(getActivity()); gv2.setNumColumns(5); listgv.add(gv1); listgv.add(gv2); vpadapter = new MyHomeVpAdapter(listgv, getActivity()); onevp.setAdapter(vpadapter); onevp.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { v.getParent().requestDisallowInterceptTouchEvent(true); return false; } }); presenter.showoneGV(); } private void initgif() { DraweeController con = Fresco.newDraweeControllerBuilder() .setUri(Uri.parse("res://" + getActivity().getPackageName() + "/" + R.mipmap.gif)) .setAutoPlayAnimations(true) .build(); oneSdv.setController(con); } private void initData() { listms = new ArrayList<>(); listtj = new ArrayList<>(); presenter.showoneBanner(); presenter.showoneGV(); } @Override public void createPresenter() { presenter = new HomePresenter(this, getActivity()); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Override public void setonebean(List<HomeBean.DataBean> list) { List<String> array = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { array.add(list.get(i).getIcon()); } oneBn.setImageLoader(new Imagebanner()); oneBn.setImages(array); oneBn.start(); } @Override public void setonemsbean(List<HomeBean.MiaoshaBean.ListBeanX> list) { listms = list; LinearLayoutManager mgr = new LinearLayoutManager(getActivity()); mgr.setOrientation(LinearLayoutManager.HORIZONTAL); oneMsRecy.setLayoutManager(mgr); msAdapter = new HomMsAdapter(list, getActivity()); oneMsRecy.setAdapter(msAdapter); msAdapter.setOnMsItemClickListener(new HomMsAdapter.OnMsItemClickListener() { @Override public void OnMsItemClick(int position) { Intent intent = new Intent(getActivity(), XiangqingActivity.class); intent.putExtra("id", listms.get(position).getPid()); startActivity(intent); } }); } @Override public void setonetjbean(List<HomeBean.TuijianBean.ListBean> list) { listtj = list; GridLayoutManager mgr = new GridLayoutManager(getActivity(), 2); oneTjRecy.setLayoutManager(mgr); tjAdapter = new HomeTjAdapter(list, getActivity()); oneTjRecy.setAdapter(tjAdapter); tjAdapter.setOnTjItemClickListener(new HomeTjAdapter.OnTjItemClickListener() { @Override public void OnTJItemClick(int position) { Intent intent = new Intent(getActivity(), XiangqingActivity.class); intent.putExtra("id", listtj.get(position).getPid()); startActivity(intent); } }); } //获取首页 @Override public void getVpData(List<Zean.DataBean> bean) { MyOneGvAdapter1 adapter1 = new MyOneGvAdapter1(bean, getActivity()); gv1.setAdapter(adapter1); MyOneGvAdapter2 adapter2 = new MyOneGvAdapter2(bean, getActivity()); gv2.setAdapter(adapter2); } @Override public void getxiangData(Xiangbean bean) { } @OnClick(R.id.sy_edname) public void onClick() { Intent intent = new Intent(getActivity(), SousuoActivity.class); startActivity(intent); } }
[ "253651654@qq.com" ]
253651654@qq.com
93d92441a2afe8d9adbf74c96ed81b60a46b68db
d2f1bfd51911e9dfd68bbf502eff7db2acb4061b
/cxf-2.6.2/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/common/ClientAccessToken.java
c3adf604d141d51348e3a84fe8790a100e79e2ed
[]
no_license
neuwerk/jaxws-cxf
fbf06c46ea0682549ff9b684806d56fe36a4e7ed
8dc9437e20b6ac728db38b444d61e3ab6a963556
refs/heads/master
2020-06-03T05:28:19.024915
2019-06-20T15:28:46
2019-06-20T15:28:46
191,460,489
0
0
null
2019-06-11T22:44:47
2019-06-11T22:44:47
null
UTF-8
Java
false
false
1,813
java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.rs.security.oauth2.common; /** * Represents the extended client view of {@link AccessToken}. * It may contain the actual scope value assigned to the access token, * the refresh token key, and other properties such as when this token * will expire, etc. */ public class ClientAccessToken extends AccessToken { private String scope; public ClientAccessToken(String tokenType, String tokenKey) { super(tokenType, tokenKey); } /** * Sets the actual scope assigned to the access token. * For example, it can be down-scoped in which case the client * may need to adjust the way it works with the end user. * @param approvedScope the actual scope */ public void setApprovedScope(String approvedScope) { this.scope = approvedScope; } /** * Gets the actual scope assigned to the access token. * @return the scope */ public String getApprovedScope() { return scope; } }
[ "tjjohnso@us.ibm.com" ]
tjjohnso@us.ibm.com
d744aab4a7ec637485ef41edb853ece0dfa31a37
baffff1bc6454352780e1262aac507f668853bfb
/src/main/java/com/boubei/tss/dm/DataExport.java
3f556e0e875a14b1b05f240e31fbe6922bf11db1
[ "MIT" ]
permissive
bierguogai/boubei-tss
926c76c9aabef22db3d659488c6adb2d0710b219
9af9b9437f70d86f27026beb1a88215ecef4a893
refs/heads/master
2021-04-09T10:38:15.249177
2018-03-16T06:05:53
2018-03-16T06:06:12
125,503,070
2
0
null
2018-03-16T10:45:16
2018-03-16T10:45:15
null
UTF-8
Java
false
false
8,090
java
/* ================================================================== * Created [2016-3-5] by Jon.King * ================================================================== * TSS * ================================================================== * mailTo:boubei@163.com * Copyright (c) boubei.com, 2015-2018 * ================================================================== */ package com.boubei.tss.dm; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.boubei.tss.dm.ext.query.AbstractExportSO; import com.boubei.tss.dm.ext.query.AbstractVO; import com.boubei.tss.framework.exception.BusinessException; import com.boubei.tss.util.EasyUtils; import com.boubei.tss.util.FileHelper; public class DataExport { public static final String CSV_CHAR_SET = "GBK"; static Logger log = Logger.getLogger(DataExport.class); public static String getExportPath() { return DMUtil.getExportPath().replace("\n", "") + "/export"; } /** * 将已经读取到缓存中的VOList分页展示给前台 */ public static Map<String, Object> getDataByPage(List<? extends AbstractVO> voList, int page, int rows ) { Map<String, Object> rlt = new HashMap<String, Object>(); rlt.put("total", voList.size()); page = Math.max(1, page); rows = Math.max(1, rows); int fromLine = (page - 1) * rows; int toLine = page * rows; if (fromLine <= voList.size()) { toLine = Math.min(voList.size(), toLine); rlt.put("rows", voList.subList(fromLine, toLine)); } if(voList.size() > 0) { rlt.put("headerNames", voList.get(0).displayHeaderNames()); } return rlt; } public static String exportCSV(List<Object[]> data, List<String> cnFields) { String basePath = getExportPath(); String exportFileName = System.currentTimeMillis() + ".csv"; String exportPath = basePath + "/" + exportFileName; DataExport._exportCSV(exportPath, convertList2Array(data), cnFields ); return exportFileName; } public static String exportCSV(List<? extends AbstractVO> voList, AbstractExportSO so) { String basePath = getExportPath(); String exportFileName = so.getExportFileName(); String exportPath = basePath + "/" + exportFileName; List<String> cnFields = null; if(voList != null && voList.size() > 0) { cnFields = voList.get(0).displayHeaderNames(); } Object[][] data = convertList2Array(AbstractVO.voList2Objects(voList)); _exportCSV(exportPath, data, cnFields ); return exportFileName; } /** 把 List<Object[]> 转换成 Object[][] 的 */ public static Object[][] convertList2Array(List<Object[]> list) { if (list == null || list.isEmpty()) { return new Object[0][0]; } int rowSize = list.size(); int columnSize = list.get(0).length; Object[][] rlt = new Object[rowSize][columnSize]; for (int i = 0; i < rowSize; i++) { Object[] tmpArrays = list.get(i); for (int j = 0; j < columnSize; j++) { rlt[i][j] = tmpArrays[j]; } } return rlt; } public static String exportCSVII(String fileName, Object[][] data, List<String> cnFields) { String basePath = getExportPath(); String exportPath = basePath + "/" + fileName; _exportCSV(exportPath, data, cnFields ); return fileName; } private static void _exportCSV(String path, Object[][] data, List<String> fields) { List<Object[]> list = new ArrayList<Object[]>(); for(Object[] temp : data) { list.add(temp); } DataExport.exportCSV(path, list, fields); } public static String exportCSV(String fileName, List<Map<String, Object>> data, List<String> fields) { List<Object[]> list = new ArrayList<Object[]>(); for (Map<String, Object> row : data) { list.add( row.values().toArray() ); } String exportPath = DataExport.getExportPath() + "/" + fileName; exportCSV(exportPath, list, fields); return exportPath; } public static void exportCSV(String path, Collection<Object[]> data, List<String> fields) { exportCSV(path, data, fields, CSV_CHAR_SET); } public static void exportCSV(String path, Collection<Object[]> data, List<String> fields, String charSet) { try { File file = FileHelper.createFile(path); boolean append = fields == null; OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file, append), charSet ); BufferedWriter fw = new BufferedWriter(write); if( !append ) { fw.write(EasyUtils.list2Str(fields)); // 表头 fw.write("\r\n"); } int index = 0; for (Object[] row : data) { List<Object> values = new ArrayList<Object>(); for(Object value : row) { String valueS = DMUtil.preCheatVal(value); values.add(valueS); } fw.write(EasyUtils.list2Str(values)); fw.write("\r\n"); if (index++ % 10000 == 0) { fw.flush(); // 每一万行输出一次 } } fw.flush(); fw.close(); } catch (IOException e) { throw new BusinessException("export csv error:" + path + ", " + e.getMessage()); } } // 共Web页面上的表格数据直接导出成csv调用 public static void exportCSV(String path, String data) { try { File file = FileHelper.createFile(path); OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), CSV_CHAR_SET ); BufferedWriter fw = new BufferedWriter(write); fw.write(data); fw.flush(); fw.close(); } catch (IOException e) { throw new BusinessException("export data error:" + path, e); } } /** * 使用http请求下载附件。 * @param sourceFilePath 导出文件路径 * @param exportName 导出名字 */ public static void downloadFileByHttp(HttpServletResponse response, String sourceFilePath) { File sourceFile = new File(sourceFilePath); if( !sourceFile.exists() ) { log.error("download file[" + sourceFilePath + "] not found."); return; } response.reset(); response.setCharacterEncoding("utf-8"); response.setContentType("application/octet-stream"); // 设置附件类型 response.setContentLength((int) sourceFile.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + EasyUtils.toUtf8String(sourceFile.getName()) + "\""); InputStream inStream = null; OutputStream outStream = null; try { outStream = response.getOutputStream(); inStream = new FileInputStream(sourceFilePath); int len = 0; byte[] b = new byte[1024]; while ((len = inStream.read(b)) != -1) { outStream.write(b, 0, len); outStream.flush(); } } catch (IOException e) { // throw new BusinessException("导出时发生IO异常!", e); } finally { sourceFile.delete(); // 删除导出目录下面的临时文件 FileHelper.closeSteam(inStream, outStream); } } }
[ "jinpujun@gmail.com" ]
jinpujun@gmail.com
cc77f06b064ec57b3ab8dcc939849e895552f101
5e3235edf3de262f4d10b9e9e1fcc3bd13d6b8b1
/Code Snippet Repository/Spring/Spring5689.java
62fb133edb640eb92fb903ae3178263dea225b20
[]
no_license
saber13812002/DeepCRM
3336a244d4852a364800af3181e03e868cf6f9f5
be3e5e50e34a042d5ba7259ff5ff75c08ab32bb9
refs/heads/master
2023-03-16T00:08:06.473699
2018-04-18T05:29:50
2018-04-18T05:29:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
304
java
private boolean getBooleanValue(ExpressionState state, SpelNodeImpl operand) { try { Boolean value = operand.getValue(state, Boolean.class); assertValueNotNull(value); return value; } catch (SpelEvaluationException ee) { ee.setPosition(operand.getStartPosition()); throw ee; } }
[ "Qing.Mi@my.cityu.edu.hk" ]
Qing.Mi@my.cityu.edu.hk
2f8941e5f22d4ec35609770e80a36a85cf7359bb
834d1c20b9a8e4f5f2763d841eb3f563c3887932
/src/main/java/kfs/kfsDbiStd/kfsOneStringTable.java
88624cf5cf0c0051d7b093da30458d485242b00e
[ "Apache-2.0" ]
permissive
k0fis/kfsWfl
7adec6fcb1027bc0b14e8face25e29012118e145
95e58f7a0df6843071415096e79434a70ff3b777
refs/heads/master
2021-01-22T06:58:14.752816
2014-11-14T08:33:15
2014-11-14T08:33:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,373
java
package kfs.kfsDbiStd; import kfs.kfsDbi.*; /** * * @author pavedrim */ public class kfsOneStringTable extends kfsDbObject { private final kfsString data; public kfsOneStringTable(kfsDbServerType st, String tableName, String colName, int maxLen) { super(st, tableName); int pos = 0; data = new kfsString(colName, colName, maxLen, pos++); super.setColumns(data); } @Override public String getCreateTable(String schema) { if (getName() == null) { return null; } else { return super.getCreateTable(schema); } } @Override public pjOneString getPojo(kfsRowData rd) { return new pjOneString(rd); } public class pjOneString extends kfsPojoObj<kfsOneStringTable> { public pjOneString(kfsRowData row) { super(kfsOneStringTable.this, row); } public String getData() { return inx.data.getData(rd); } public void setData(String newVal) { inx.data.setData(newVal, rd); } @Override public String toString() { return getData(); } } public class pjOneStringList extends kfsPojoArrayList<kfsOneStringTable, pjOneString> { public pjOneStringList() { super(kfsOneStringTable.this); } } }
[ "k0fis@me.com" ]
k0fis@me.com
bed7bf97327ede7da3d831b68ddf9038a67d6344
fa1408365e2e3f372aa61e7d1e5ea5afcd652199
/src/testcases/CWE191_Integer_Underflow/s02/CWE191_Integer_Underflow__int_getQueryString_Servlet_sub_17.java
9ec0f3a301dc630dfa7e260674dc14e4c065a35e
[]
no_license
bqcuong/Juliet-Test-Case
31e9c89c27bf54a07b7ba547eddd029287b2e191
e770f1c3969be76fdba5d7760e036f9ba060957d
refs/heads/master
2020-07-17T14:51:49.610703
2019-09-03T16:22:58
2019-09-03T16:22:58
206,039,578
1
2
null
null
null
null
UTF-8
Java
false
false
5,536
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__int_getQueryString_Servlet_sub_17.java Label Definition File: CWE191_Integer_Underflow__int.label.xml Template File: sources-sinks-17.tmpl.java */ /* * @description * CWE: 191 Integer Underflow * BadSource: getQueryString_Servlet Parse id param out of the URL query string (without using getParameter()) * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: sub * GoodSink: Ensure there will not be an underflow before subtracting 1 from data * BadSink : Subtract 1 from data, which can cause an Underflow * Flow Variant: 17 Control flow: for loops * * */ package testcases.CWE191_Integer_Underflow.s02; import testcasesupport.*; import javax.servlet.http.*; import java.util.StringTokenizer; import java.util.logging.Level; public class CWE191_Integer_Underflow__int_getQueryString_Servlet_sub_17 extends AbstractTestCaseServlet { public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { int data; /* We need to have one source outside of a for loop in order * to prevent the Java compiler from generating an error because * data is uninitialized */ data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */ /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */ { StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); /* a token will be like "id=33" */ if(token.startsWith("id=")) /* check if we have the "id" parameter" */ { try { data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */ } catch(NumberFormatException exceptNumberFormat) { IO.logger.log(Level.WARNING, "Number format exception reading id from query string", exceptNumberFormat); } break; /* exit while loop */ } } } for (int j = 0; j < 1; j++) { /* POTENTIAL FLAW: if data == Integer.MIN_VALUE, this will overflow */ int result = (int)(data - 1); IO.writeLine("result: " + result); } } /* goodG2B() - use goodsource and badsink */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { int data; /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; for (int j = 0; j < 1; j++) { /* POTENTIAL FLAW: if data == Integer.MIN_VALUE, this will overflow */ int result = (int)(data - 1); IO.writeLine("result: " + result); } } /* goodB2G() - use badsource and goodsink*/ private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable { int data; data = Integer.MIN_VALUE; /* initialize data in case id is not in query string */ /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */ { StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); /* a token will be like "id=33" */ if(token.startsWith("id=")) /* check if we have the "id" parameter" */ { try { data = Integer.parseInt(token.substring(3)); /* set data to the int 33 */ } catch(NumberFormatException exceptNumberFormat) { IO.logger.log(Level.WARNING, "Number format exception reading id from query string", exceptNumberFormat); } break; /* exit while loop */ } } } for (int k = 0; k < 1; k++) { /* FIX: Add a check to prevent an overflow from occurring */ if (data > Integer.MIN_VALUE) { int result = (int)(data - 1); IO.writeLine("result: " + result); } else { IO.writeLine("data value is too small to perform subtraction."); } } } public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable { goodG2B(request, response); goodB2G(request, response); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
[ "bqcuong2212@gmail.com" ]
bqcuong2212@gmail.com
f5151a67eec372b98a9c28da4ef76d351f8627e5
d6b4fd03c14de2c52d2e2617f974b96bb6241740
/kls-dataaccess/src/main/java/com/vsoftcorp/kls/dataaccess/IPacsDAO.java
0f92e6585241bd15381ac8461aeae90f734fabd0
[]
no_license
harivsoft/KLS
9abc57cb86001f36f9fbb8a5490e3b2f59cb3436
abc0394e7ba2925df130b94139791c12801e5bf4
refs/heads/master
2021-01-19T12:40:22.403041
2017-08-31T04:04:04
2017-08-31T04:04:04
100,795,258
0
0
null
null
null
null
UTF-8
Java
false
false
661
java
package com.vsoftcorp.kls.dataaccess; import java.util.List; import com.vsoftcorp.kls.business.entities.Pacs; /** * * @author a9153 * */ public interface IPacsDAO { public void savePacs(Pacs pacs); public void updatePacs(Pacs pacs); public Pacs getPacs(Pacs pacs); public Pacs getPacs(Pacs pacs,boolean isCloseSession); public Pacs getPacs(Integer pacsId); public List<Pacs> getAllPacs(); public List<Pacs> getAllPacsByBranch(Integer branchId); public Pacs getPacsByPacId(Integer pacsId); public List<Pacs> getClosedOfflinePacs(); public List<Pacs> getSycedPacs(); public void updatePacsStatus(List<Integer> pacsIdsList); }
[ "myproject893@gmail.com" ]
myproject893@gmail.com
427f327761e98fffffa38659fa416792e13b719b
6baf601ed8092e3b8f44d2e146c00c119bdf8bd5
/后台代码/CarWashing/src/ty/dao/FeedbackDao.java
422d08cbb81bc8fc52e514b82b8e752cb3cc7589
[]
no_license
viviancui59/CarWashing
35e8f729d346244876f401b72eae41a19bc67a5a
18a64a0b6866c9a41f8c1184f18207a14540ecd3
refs/heads/master
2021-01-19T23:25:29.309341
2017-06-02T12:06:58
2017-06-02T12:06:58
88,978,105
0
0
null
null
null
null
UTF-8
Java
false
false
397
java
package ty.dao; import java.util.List; import ty.entity.Car; import ty.entity.Feedback; import ty.entity.User; public interface FeedbackDao { //插入新用户 boolean insertFeedback(Feedback feedback); //返回所有用户反馈意见 List<Feedback> findAll(int lastid,int pagesize); //返回特定的反馈意见 // Feedback findByFeedbackId(int feedbackid); }
[ "a547143207@qq.com" ]
a547143207@qq.com
483fd33f56f8810bd968bff1d0e36b2a8c4aa781
d66fdd9118baa4da0881ce57f5003aef4821e748
/src/main/java/com/mongodb/dibs/email/NotificationsWatcher.java
7ff423257a14635b41a3dd8c02854a3de5ff2d8e
[ "Apache-2.0" ]
permissive
evanchooly/mongodibs
f85293a807f1b04f28a32a3e306bba56b8737ce0
079683430838cc640b6ad6cb30fcf3407bf07fd3
refs/heads/master
2020-07-04T14:14:00.814517
2015-12-17T16:48:54
2015-12-17T16:48:54
21,694,298
0
0
null
null
null
null
UTF-8
Java
false
false
713
java
package com.mongodb.dibs.email; import com.mongodb.dibs.Smtp; import javax.mail.Flags.Flag; import javax.mail.Message; import javax.mail.MessagingException; class NotificationsWatcher extends EmailWatcher { private final SeamlessConfirmationEmailListener emailListener; NotificationsWatcher(final SeamlessConfirmationEmailListener emailListener) throws MessagingException { super(Smtp.notificationsEmailAddress(), Smtp.notificationsEmailPassword()); this.emailListener = emailListener; } @Override protected void process(final Message message) throws MessagingException { emailListener.deliver(message, false); message.setFlag(Flag.DELETED, true); } }
[ "justin.lee@10gen.com" ]
justin.lee@10gen.com
842f6d62bf8465f7dd0a9def1af0e7e90a209186
6ecf205719a9f0ec50d4dd6892135294c8b9ae01
/ta/ref-app/android/ClickCall/src/com/wx2/clickcall/NativeClickCall.java
6bf41824656112fccedf5adcd9e2cba19efe83ef
[]
no_license
zzchu/wme-ref-app
25a8786d29d001e37e2ce91f0ca928bab2187cff
5cbf042d26c6d91f35a352a71e0d2961c12cd3f6
refs/heads/master
2021-01-01T03:39:18.439856
2016-04-21T07:44:56
2016-04-21T07:44:56
56,753,029
0
1
null
null
null
null
UTF-8
Java
false
false
448
java
package com.wx2.clickcall; import android.util.Log; public class NativeClickCall { static { try { System.loadLibrary("c++_shared"); System.loadLibrary("clickcall"); }catch (Exception e){ Log.w("ClickCall", "Failed to load native library: " + e.toString()); } } public static native void doGCov(int action); public static native void SetEnv(String name,String value); }
[ "zhchu@cisco.com" ]
zhchu@cisco.com
56fa9a444602c84a3e1ffc262e743f5ec3bf67c6
6ba3e07e214878746bbaac1f1f8006c27e81fa6c
/SoundStageWeb/src/main/java/org/soundstage/web/dao/SeatDAO.java
3a0d9ba84dba49b31aef975aab6748d793cffc9f
[]
no_license
Atunullas/SoundStage
e477fe0820a15e4a0c1c6b375835e96f25a3052a
beebcad1ce61d2ffc74384e8d6a3dc82c71ee653
refs/heads/master
2021-01-13T00:55:53.319598
2016-03-14T02:11:17
2016-03-14T02:11:17
48,845,950
1
0
null
null
null
null
UTF-8
Java
false
false
863
java
/* * 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 org.soundstage.web.dao; import java.io.Serializable; import java.util.List; import org.soundstage.web.domain.Seat; /** * * @author atun.ullas */ public interface SeatDAO { Seat createSeatObject(Seat object); void createSeatObjectsList(List<Seat> objects); Seat updateSeatObject(Seat object); Seat findSeatObjectById(Serializable id); public List<Seat> getAllSeatObjects(); public List<Seat> getAllAscendingSortedSeatObjects(String field); public void createOrUpdateSeatObject(Seat object); public void deleteSeatObject(Seat object); public void Seatflush(); public void Seatclear(); }
[ "atunullas@gmail.com" ]
atunullas@gmail.com
0af6e14e71dd51b5b6e625aa6f1f1f3ee2a44e75
9f48b92ffc79d91b13ed75d771ad4b2b8b8c0cbc
/src/main/java/ro/hacktm/oradea/epiata/model/dto/TenderCloseRequestDto.java
05f3755086b55a428a83b19ade0c7628b3dc7fda
[]
no_license
RaDaPo/ePiata-BE
25874fa40bd565a3b7ad21afea2e3f28b15f16e2
5eb0e099dfdf98d7f3299ffcb68d9b3d58c85674
refs/heads/master
2020-05-05T04:42:34.558968
2019-04-09T05:56:58
2019-04-09T05:56:58
179,722,014
0
0
null
null
null
null
UTF-8
Java
false
false
172
java
package ro.hacktm.oradea.epiata.model.dto; import lombok.Data; @Data public class TenderCloseRequestDto { private Long tenderId; private Integer newNeededGrossMass; }
[ "Lucian.Torjoc@swisscom.com" ]
Lucian.Torjoc@swisscom.com
8ecbae8ca07b0735fdfca1f165497f20dd62ae72
12a99ab3fe76e5c7c05609c0e76d1855bd051bbb
/src/main/java/com/alipay/api/domain/NetFlowOfferInfo.java
f4c699883dc1ec7d18c3e891adf51f83c4e1ca53
[ "Apache-2.0" ]
permissive
WindLee05-17/alipay-sdk-java-all
ce2415cfab2416d2e0ae67c625b6a000231a8cfc
19ccb203268316b346ead9c36ff8aa5f1eac6c77
refs/heads/master
2022-11-30T18:42:42.077288
2020-08-17T05:57:47
2020-08-17T05:57:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,340
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 流量充值信息 * * @author auto create * @since 1.0, 2020-06-11 14:54:09 */ public class NetFlowOfferInfo extends AlipayObject { private static final long serialVersionUID = 3757586534682846985L; /** * 流量生效时间 */ @ApiField("effective_time") private String effectiveTime; /** * 流量过期时间 */ @ApiField("expire_time") private String expireTime; /** * 流量套餐名称 */ @ApiField("offer_name") private String offerName; /** * 下单时间 */ @ApiField("order_time") private String orderTime; public String getEffectiveTime() { return this.effectiveTime; } public void setEffectiveTime(String effectiveTime) { this.effectiveTime = effectiveTime; } public String getExpireTime() { return this.expireTime; } public void setExpireTime(String expireTime) { this.expireTime = expireTime; } public String getOfferName() { return this.offerName; } public void setOfferName(String offerName) { this.offerName = offerName; } public String getOrderTime() { return this.orderTime; } public void setOrderTime(String orderTime) { this.orderTime = orderTime; } }
[ "ben.zy@antfin.com" ]
ben.zy@antfin.com
d7d7059997f49a715592fa435bb05fa8e49d49c3
27eee9d5bc2dfdd111e0ed0b46bc2163072bb672
/app/src/main/java/bkdn/cntt/demointent/intent/MainActivity2.java
cc70ba8504c3de31998fa34c26561fcce627f810
[]
no_license
tinhtinh95/buoi6
cad6405d2edbeb423f6b5103cf8b0393d8dc9ef5
f0eaab22710e1fc9b0057eb26692d60055d28269
refs/heads/master
2020-05-23T19:28:29.254848
2017-03-13T04:19:33
2017-03-13T04:19:33
84,783,127
0
0
null
null
null
null
UTF-8
Java
false
false
1,746
java
package bkdn.cntt.demointent.intent; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import bkdn.cntt.demointent.R; /** * Created by Administrator on 08/03/2017. */ public class MainActivity2 extends AppCompatActivity implements View.OnClickListener { private Button mBtnCong,mBtnTru,mBtnNhan,mBtnChia; private float a,b; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tinhtoan); mBtnCong=(Button)findViewById(R.id.btnCong); mBtnTru=(Button)findViewById(R.id.btnTru); mBtnNhan=(Button)findViewById(R.id.btnNhan); mBtnChia=(Button)findViewById(R.id.btnChia); // Bundle bundle=getIntent().getExtras(); // a=bundle.getFloat("a"); // b=bundle.getFloat("b"); a=getIntent().getFloatExtra("a",0); b=getIntent().getFloatExtra("b",0); mBtnCong.setOnClickListener(this); mBtnTru.setOnClickListener(this); mBtnNhan.setOnClickListener(this); mBtnChia.setOnClickListener(this); } @Override public void onClick(View v) { if(v==mBtnCong){ resultForMain(a+b,1); } if(v==mBtnTru){ resultForMain(a-b,2); } if(v==mBtnNhan){ resultForMain(a*b,3); } if(v==mBtnChia){ resultForMain(a/b,4); } } public void resultForMain(float result, int resultcode){ Intent intent=new Intent(); intent.putExtra("result",result); setResult(resultcode,intent); finish(); } }
[ "nttinh995@gmail.com" ]
nttinh995@gmail.com
f78659be2c3c6f14562f651c7678ef7be371fbd1
c1e669c95704db1e89c99d396f59d6806f6786ac
/java-parent/chat-server/chat-server-ddd/src/main/java/top/xkk/chat/interfaces/InetController.java
0fa1cb58d3e02c39d513d85a4a1122c99014cb38
[]
no_license
kaikaixue/JavaStudy
a183cbfeb95a152adc9f0f641f197a5dd28187a4
de5952cb16b2c57f595b4a233f744081fa15f1cf
refs/heads/main
2023-09-02T07:32:10.500036
2021-11-09T15:48:10
2021-11-09T15:48:10
413,481,801
0
1
null
null
null
null
UTF-8
Java
false
false
2,276
java
package top.xkk.chat.interfaces; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import top.xkk.chat.application.InetService; import top.xkk.chat.domain.inet.model.ChannelUserInfo; import top.xkk.chat.domain.inet.model.ChannelUserReq; import top.xkk.chat.domain.inet.model.InetServerInfo; import top.xkk.chat.infrastructure.common.EasyResult; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * @author mqxu */ @Controller public class InetController { private final Logger logger = LoggerFactory.getLogger(InetController.class); @Resource private InetService inetService; @RequestMapping("api/queryNettyServerInfo") @ResponseBody public EasyResult queryNettyServerInfo() { try { return EasyResult.buildEasyResultSuccess(new ArrayList<InetServerInfo>() {{ add(inetService.queryNettyServerInfo()); }}); } catch (Exception e) { logger.info("查询NettyServer失败。", e); return EasyResult.buildEasyResultError(e); } } @RequestMapping("api/queryChannelUserList") @ResponseBody public EasyResult queryChannelUserList(String json, String page, String limit) { try { logger.info("查询通信管道用户信息列表开始。req:{}", json); ChannelUserReq req = JSON.parseObject(json, ChannelUserReq.class); if (null == req) { req = new ChannelUserReq(); } req.setPage(page, limit); Long count = inetService.queryChannelUserCount(req); List<ChannelUserInfo> list = inetService.queryChannelUserList(req); logger.info("查询通信管道用户信息列表完成。list:{}", JSON.toJSONString(list)); return EasyResult.buildEasyResultSuccess(count, list); } catch (Exception e) { logger.info("查询通信管道用户信息列表失败。req:{}", json, e); return EasyResult.buildEasyResultError(e); } } }
[ "2780739366@qq.com" ]
2780739366@qq.com
575710e0088208cd404938957626068323fc751d
5d8eb6f4f93c50b38ceaad7813d5d625faacf37d
/app/src/main/java/lcs/android/site/creation/SiteMap.java
1cc1d10995e74fb83568ab155aa2d7abe681bbef
[]
no_license
sidav/LCS-android
376d692e6d5b2d5568417d14eb56efcb47657783
77d39f7fdc6255133b5510cf1b29794576b605b7
refs/heads/master
2020-04-02T06:10:01.649140
2018-10-22T12:21:11
2018-10-22T12:21:34
154,133,595
0
0
null
null
null
null
UTF-8
Java
false
false
21,316
java
package lcs.android.site.creation; import static lcs.android.game.Game.*; import java.util.EnumSet; import java.util.Set; import lcs.android.basemode.iface.Location; import lcs.android.creature.Creature; import lcs.android.encounters.EmptyEncounter; import lcs.android.game.Game; import lcs.android.game.LcsRandom; import lcs.android.site.map.MapChangeRecord; import lcs.android.site.map.MapTile; import lcs.android.site.map.SpecialBlocks; import lcs.android.site.map.TileSpecial; import lcs.android.site.type.Cosmetics; import lcs.android.site.type.CrackHouse; import lcs.android.site.type.Tenement; import lcs.android.util.LcsRuntimeException; import lcs.android.util.Xml; import lcs.android.util.Xml.Configurable; // import org.eclipse.jdt.annotation.NonNullByDefault; import android.util.Log; public class SiteMap { private static enum Side { BOTTOM, LEFT, RIGHT, TOP } private SiteMap() {} public static final Configurable CONFIG = new Configurable() { @Override public Configurable xmlChild(final String value) { if ("sitemap".equals(value)) { final ConfigSiteMap csm = new ConfigSiteMap(); return csm; } return Xml.UNCONFIGURABLE; } @Override public void xmlFinishChild() { // no action } @Override public void xmlSet(final String key, final String value) { // no action } }; public final static int MAPX = 70; public final static int MAPY = 23; public final static int MAPZ = 10; protected static final LcsRandom SITERNG = new LcsRandom(); private static final Set<Side> COMPLETELYBLOCKED = EnumSet.allOf(Side.class); /* re-create site from seed before squad arrives */ public static void initsite(final Location loc) { // PREP i.currentEncounter(new EmptyEncounter()); for (final Creature p : i.activeSquad()) { p.forceIncapacitated(false); } i.groundLoot().clear(); // MAKE MAP // int oldseed = seed; // seed = loc.mapseed; SITERNG.setSeed(loc.mapSeed()); i.site.siteLevelmap(new MapTile[MAPX][MAPY][MAPZ]); i.topfloor = -1; // allocateFloor(0); buildSite(loc.type().sitepattern); // CLEAR AWAY BLOCKED DOORWAYS clearBlockedDoors(); Log.d(Game.LCS, "SiteMap.initSite cleared blocked doors."); // DELETE NON-DOORS deleteNonDoors(); Log.d(Game.LCS, "SiteMap.initSite cleared non doors."); if (!false) // SAV - Did I mention we have some more things // to // do? { Log.d(Game.LCS, "SiteMap.initSite more to do...."); // ADD RESTRICTIONS // boolean restricted = false; if (loc.type().isRestricted()) { for (int x = 2; x < MAPX - 2; x++) { for (int y = 2; y < MAPY - 2; y++) { for (int z = 0; z < i.topfloor; z++) { i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.RESTRICTED); } } } } // ADD ACCESSORIES // seed = oldseed; for (int x = 2; x < MAPX - 2; x++) { for (int y = 2; y < MAPY - 2; y++) { for (int z = 0; z < i.topfloor; z++) { // don't add loot before we've sorted out restricted // areas /* this lot uses i.rng, so the location varies on each visit */ if (loc.type().commonSpecial() != null && !i.site.siteLevelmap()[x][y][0].flag.contains(TileSpecial.DOOR) && !i.site.siteLevelmap()[x][y][0].blocked() && !i.site.siteLevelmap()[x][y][0].flag.contains(TileSpecial.LOOT) && i.site.siteLevelmap()[x][y][0].restricted() && loc.type().isType(Cosmetics.class) && i.rng.chance(10)) { i.site.siteLevelmap()[x][y][z].special = loc.type().commonSpecial(); } else if (i.site.siteLevelmap()[x][y][0].flag.isEmpty() && (loc.type().hasTables()) && i.rng.chance(10)) { i.site.siteLevelmap()[x][y][z].special = SpecialBlocks.RESTAURANT_TABLE; } } } } final int freez = addFirstSpecial(loc); if (loc.type().secondSpecial() != null) { addSecondSpecial(loc, freez); } } // SAV - End more old map stuff. Log.d(Game.LCS, "SiteMap.initSite more done."); // Clear out restrictions clearRestrictions(); Log.d(Game.LCS, "SiteMap.initSite clear restrictions."); // ADD LOOT addLoot(loc); Log.d(Game.LCS, "SiteMap.initSite add loot."); /******************************************************* Add semi-permanent changes inflicted by LCS and others *******************************************************/ addGraffiti(loc); Log.d(Game.LCS, "SiteMap.initSite add graffiti."); } /* marks the area around the specified tile as explored */ public static void knowmap(final int locx, final int locy, final int locz) { i.site.siteLevelmap()[locx][locy][locz].known(); if (locx > 0) { i.site.siteLevelmap()[locx - 1][locy][locz].known(); } if (locx < MAPX - 1) { i.site.siteLevelmap()[locx + 1][locy][locz].known(); } if (locy > 0) { i.site.siteLevelmap()[locx][locy - 1][locz].known(); } if (locy < MAPY - 1) { i.site.siteLevelmap()[locx][locy + 1][locz].known(); } if (locx > 0 && locy > 0 && (!i.site.siteLevelmap()[locx - 1][locy][locz].blocked() || !i.site.siteLevelmap()[locx][locy - 1][locz] .blocked())) { i.site.siteLevelmap()[locx - 1][locy - 1][locz].known(); } if (locx < MAPX - 1 && locy > 0 && (!i.site.siteLevelmap()[locx + 1][locy][locz].blocked() || !i.site.siteLevelmap()[locx][locy - 1][locz] .blocked())) { i.site.siteLevelmap()[locx + 1][locy - 1][locz].known(); } if (locx > 0 && locy < MAPY - 1 && (!i.site.siteLevelmap()[locx - 1][locy][locz].blocked() || !i.site.siteLevelmap()[locx][locy + 1][locz] .blocked())) { i.site.siteLevelmap()[locx - 1][locy + 1][locz].known(); } if (locx < MAPX - 1 && locy < MAPY - 1 && (!i.site.siteLevelmap()[locx + 1][locy][locz].blocked() || !i.site.siteLevelmap()[locx][locy + 1][locz] .blocked())) { i.site.siteLevelmap()[locx + 1][locy + 1][locz].known(); } } protected static void allocateFloor(final int z) { // this is a massive hit on android: spread it out a bit and only do // each floor as needs be. if (z <= i.topfloor) { return; } do { i.topfloor++; Log.d(Game.LCS, "SiteMap.initSite allocating floor " + i.topfloor + " (SiteBlockSt:" + MAPX * MAPY + ")"); for (int x = 0; x < MAPX; x++) { for (int y = 0; y < MAPY; y++) { i.site.siteLevelmap()[x][y][i.topfloor] = new MapTile(); } } } while (i.topfloor < z); } protected static void buildSite(final String name) { Log.d(Game.LCS, "SiteMap.build_site:" + name); if (Game.type.sitemaps.containsKey(name)) { Game.type.sitemaps.get(name).build(); return; } Log.w(Game.LCS, "SiteMap.build_site failed:" + name); if ("GENERIC_UNSECURE".equals(name)) { throw new LcsRuntimeException("SiteMap.build_site: can't even make GENERIC_UNSECURE"); } buildSite("GENERIC_UNSECURE"); } private static int addFirstSpecial(final Location loc) { int freex = 0, freey = 0; final int freez = 0; // ADD FIRST SPECIAL int count = 100000; do { freex = SITERNG.nextInt(MAPX - 4) + 2; freey = SITERNG.nextInt(MAPY - 4) + 2; if (freex >= MAPX / 2 - 2 && freex <= MAPX / 2 + 2) { freey = SITERNG.nextInt(MAPY - 6) + 4; } count--; } while ((i.site.siteLevelmap()[freex][freey][freez].flag.contains(TileSpecial.DOOR) || i.site.siteLevelmap()[freex][freey][freez].blocked() || i.site.siteLevelmap()[freex][freey][freez].flag.contains(TileSpecial.LOOT) || i.site .siteLevelmap()[freex][freey][freez].special != null) && count > 0); if (loc.type().firstSpecial() != null) { i.site.siteLevelmap()[freex][freey][freez].special = loc.type().firstSpecial(); } return freez; } private static void addGraffiti(final Location loc) { // Some sites need a minimum amount of graffiti int graffitiquota = loc.type().graffitiQuota(); for (final MapChangeRecord j : loc.changes()) { switch (j.flag) { case GRAFFITI_OTHER: // Other tags case GRAFFITI_CCS: // CCS tags case GRAFFITI: // LCS tags graffitiquota--; i.site.siteLevelmap()[j.x][j.y][j.z].flag.add(j.flag); break; case DEBRIS: // Smashed walls, ash i.site.siteLevelmap()[j.x][j.y][j.z].flag.remove(TileSpecial.BLOCK); i.site.siteLevelmap()[j.x][j.y][j.z].flag.remove(TileSpecial.DOOR); i.site.siteLevelmap()[j.x][j.y][j.z].flag.add(j.flag); break; default: i.site.siteLevelmap()[j.x][j.y][j.z].flag.add(j.flag); break; } } // If there isn't enough graffiti for this site type, add some while (graffitiquota > 0) { final int x = SITERNG.nextInt(MAPX - 2) + 1; final int y = SITERNG.nextInt(MAPY - 2) + 1; final int z = (loc.type().isType(Tenement.class)) ? SITERNG.nextInt(6) : 0; if (!i.site.siteLevelmap()[x][y][z].blocked() && (!i.site.siteLevelmap()[x][y][z].restricted() || loc.type().isType(CrackHouse.class)) && !i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.EXIT) && !i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.GRAFFITI) && !i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.GRAFFITI) && !i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.GRAFFITI) && (i.site.siteLevelmap()[x + 1][y][z].blocked() || i.site.siteLevelmap()[x - 1][y][z].blocked() || i.site.siteLevelmap()[x][y + 1][z].blocked() || i.site.siteLevelmap()[x][y - 1][z] .blocked())) { final MapChangeRecord change = new MapChangeRecord(x, y, z, TileSpecial.GRAFFITI_OTHER); loc.changes().add(change); i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.GRAFFITI_OTHER); graffitiquota--; } } } private static void addLoot(final Location loc) { if (!loc.type().hasLoot()) { return; } for (int x = 2; x < MAPX - 2; x++) { for (int y = 2; y < MAPY - 2; y++) { for (int z = 0; z <= i.topfloor; z++) { if (!i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.DOOR) && !i.site.siteLevelmap()[x][y][z].blocked() && i.site.siteLevelmap()[x][y][z].restricted() && i.rng.chance(10)) { // time i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.LOOT); } } } } } private static void addSecondSpecial(final Location loc, final int freez) { int freex; int freey; int count; count = 100000; // ADD SECOND SPECIAL do { freex = SITERNG.nextInt(MAPX - 4) + 2; freey = SITERNG.nextInt(MAPY - 4) + 2; if (freex >= MAPX / 2 - 2 && freex <= MAPX / 2 + 2) { freey = SITERNG.nextInt(MAPY - 6) + 4; } count--; } while ((i.site.siteLevelmap()[freex][freey][freez].flag.contains(TileSpecial.DOOR) || i.site.siteLevelmap()[freex][freey][freez].blocked() || i.site.siteLevelmap()[freex][freey][freez].flag.contains(TileSpecial.LOOT) || i.site .siteLevelmap()[freex][freey][freez].special != null) && count > 0); i.site.siteLevelmap()[freex][freey][freez].special = loc.type().secondSpecial(); } private static void clearBlockedDoors() { Set<Side> block; for (int x = 0; x < MAPX; x++) { for (int y = 0; y < MAPY; y++) { for (int z = 0; z <= i.topfloor; z++) { if (i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.DOOR)) { // Check what sides are blocked around the door block = EnumSet.allOf(Side.class); if (x > 0 && !i.site.siteLevelmap()[x - 1][y][z].blocked()) { block.remove(Side.LEFT); } if (x < MAPX - 1 && !i.site.siteLevelmap()[x + 1][y][z].blocked()) { block.remove(Side.RIGHT); } if (y > 0 && !i.site.siteLevelmap()[x][y - 1][z].blocked()) { block.remove(Side.TOP); } if (y < MAPY - 1 && !i.site.siteLevelmap()[x][y + 1][z].blocked()) { block.remove(Side.BOTTOM); } // Blast open everything around a totally blocked door // (door will later be deleted) if (block.equals(COMPLETELYBLOCKED)) { if (x > 0) { i.site.siteLevelmap()[x - 1][y][z].flag.remove(TileSpecial.BLOCK); } if (x < MAPX - 1) { i.site.siteLevelmap()[x + 1][y][z].flag.remove(TileSpecial.BLOCK); } if (y > 0) { i.site.siteLevelmap()[x][y - 1][z].flag.remove(TileSpecial.BLOCK); } if (y < MAPY - 1) { i.site.siteLevelmap()[x][y + 1][z].flag.remove(TileSpecial.BLOCK); } } // Open up past doors that lead to walls if (!block.contains(Side.TOP)) { if (y < MAPY - 1) { int y1 = y + 1; do { i.site.siteLevelmap()[x][y1][z].flag.remove(TileSpecial.BLOCK); i.site.siteLevelmap()[x][y1][z].flag.remove(TileSpecial.DOOR); y1++; } while (!(i.site.siteLevelmap()[x + 1][y1][z].blocked() || i.site.siteLevelmap()[x + 1][y1][z].flag .contains(TileSpecial.DOOR)) && !(i.site.siteLevelmap()[x - 1][y1][z].blocked() || i.site.siteLevelmap()[x - 1][y1][z].flag .contains(TileSpecial.DOOR))); } else { i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.BLOCK); } } else if (!block.contains(Side.BOTTOM)) { if (y > 0) { int y1 = y - 1; do { i.site.siteLevelmap()[x][y1][z].flag.remove(TileSpecial.BLOCK); i.site.siteLevelmap()[x][y1][z].flag.remove(TileSpecial.DOOR); y1--; } while (!(i.site.siteLevelmap()[x + 1][y1][z].blocked() || i.site.siteLevelmap()[x + 1][y1][z].flag .contains(TileSpecial.DOOR)) && !(i.site.siteLevelmap()[x - 1][y1][z].blocked() || i.site.siteLevelmap()[x - 1][y1][z].flag .contains(TileSpecial.DOOR))); } else { i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.BLOCK); } } else if (!block.contains(Side.LEFT)) { if (x < MAPX - 1) { int x1 = x + 1; do { i.site.siteLevelmap()[x1][y][z].flag.remove(TileSpecial.BLOCK); i.site.siteLevelmap()[x1][y][z].flag.remove(TileSpecial.DOOR); x1++; } while (!(i.site.siteLevelmap()[x1][y + 1][z].blocked() || i.site.siteLevelmap()[x1][y + 1][z].flag .contains(TileSpecial.DOOR)) && !(i.site.siteLevelmap()[x1][y - 1][z].blocked() || i.site.siteLevelmap()[x1][y - 1][z].flag .contains(TileSpecial.DOOR))); } else { i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.BLOCK); } } else if (!block.contains(Side.RIGHT)) { if (x > 0) { int x1 = x - 1; do { i.site.siteLevelmap()[x1][y][z].flag.remove(TileSpecial.BLOCK); i.site.siteLevelmap()[x1][y][z].flag.remove(TileSpecial.DOOR); x1--; } while (!(i.site.siteLevelmap()[x1][y + 1][z].blocked() || i.site.siteLevelmap()[x1][y + 1][z].flag .contains(TileSpecial.DOOR)) && !(i.site.siteLevelmap()[x1][y - 1][z].blocked() || i.site.siteLevelmap()[x1][y - 1][z].flag .contains(TileSpecial.DOOR))); } else { i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.BLOCK); } } } } } } } private static void clearRestrictions() { boolean acted; do { acted = false; for (int x = 2; x < MAPX - 2; x++) { for (int y = 2; y < MAPY - 2; y++) { for (int z = 0; z <= i.topfloor; z++) { // Un-restrict blocks if they have neighboring // unrestricted blocks if (!i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.DOOR) && !i.site.siteLevelmap()[x][y][z].blocked() && i.site.siteLevelmap()[x][y][z].restricted()) { if (!i.site.siteLevelmap()[x - 1][y][z].restricted() && !i.site.siteLevelmap()[x - 1][y][z].blocked() || !i.site.siteLevelmap()[x + 1][y][z].restricted() && !i.site.siteLevelmap()[x + 1][y][z].blocked() || !i.site.siteLevelmap()[x][y - 1][z].restricted() && !i.site.siteLevelmap()[x][y - 1][z].blocked() || !i.site.siteLevelmap()[x][y + 1][z].restricted() && !i.site.siteLevelmap()[x][y + 1][z].blocked()) { i.site.siteLevelmap()[x][y][z].flag.remove(TileSpecial.RESTRICTED); acted = true; continue; } } // Un-restrict and unlock doors if they lead between two // unrestricted sections. If they lead between one // unrestricted section and a restricted section, lock // them instead. else if (i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.DOOR) && !i.site.siteLevelmap()[x][y][z].blocked() && i.site.siteLevelmap()[x][y][z].restricted()) { // Unrestricted on two opposite sides? if (!i.site.siteLevelmap()[x - 1][y][z].restricted() && !i.site.siteLevelmap()[x + 1][y][z].restricted() || !i.site.siteLevelmap()[x][y - 1][z].restricted() && !i.site.siteLevelmap()[x][y + 1][z].restricted()) { // Unlock and unrestrict i.site.siteLevelmap()[x][y][z].flag.remove(TileSpecial.LOCKED); i.site.siteLevelmap()[x][y][z].flag.remove(TileSpecial.RESTRICTED); acted = true; continue; } // Unrestricted on at least one side and I'm not // locked? else if ((!i.site.siteLevelmap()[x - 1][y][z].restricted() || !i.site.siteLevelmap()[x + 1][y][z].restricted() || !i.site.siteLevelmap()[x][y - 1][z].restricted() || !i.site.siteLevelmap()[x][y + 1][z].flag .contains(TileSpecial.RESTRICTED)) && !i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.LOCKED)) { // Lock doors leading to restricted areas i.site.siteLevelmap()[x][y][z].flag.add(TileSpecial.LOCKED); acted = true; continue; } } } } } } while (acted); } private static void deleteNonDoors() { Set<Side> block; for (int x = 0; x < MAPX; x++) { for (int y = 0; y < MAPY; y++) { for (int z = 0; z <= i.topfloor; z++) { if (i.site.siteLevelmap()[x][y][z].flag.contains(TileSpecial.DOOR)) { block = EnumSet.allOf(Side.class); if (x > 0 && !i.site.siteLevelmap()[x - 1][y][z].blocked()) { block.remove(Side.LEFT); } if (x < MAPX - 1 && !i.site.siteLevelmap()[x + 1][y][z].blocked()) { block.remove(Side.RIGHT); } if (y > 0 && !i.site.siteLevelmap()[x][y - 1][z].blocked()) { block.remove(Side.TOP); } if (y < MAPY - 1 && !i.site.siteLevelmap()[x][y + 1][z].blocked()) { block.remove(Side.BOTTOM); } if (!block.contains(Side.TOP) && !block.contains(Side.BOTTOM)) { continue; } if (!block.contains(Side.LEFT) && !block.contains(Side.RIGHT)) { continue; } i.site.siteLevelmap()[x][y][z].flag.remove(TileSpecial.DOOR); i.site.siteLevelmap()[x][y][z].flag.remove(TileSpecial.LOCKED); } } } } } }
[ "vkovun@phoenixit.ru" ]
vkovun@phoenixit.ru
d8b8b185da15e2a3a2a06ce53e37dcd8e589fb46
6fb154f2c9814acd7905261b5b2977ca6bf21679
/src/main/java/com/odinson/chatroom/encoder/MessageEncoder.java
a01e035eebf92f04298c1b1f25b0b0a5c9335b1a
[]
no_license
victoray/chat-room
115ad85ea5cb84e8812df3fe9f3ebf489eb6e824
ee6ba9990230d34c9284c07e0abb8a0409bacf0f
refs/heads/master
2020-07-30T01:46:53.428811
2019-09-22T18:41:44
2019-09-22T18:41:44
210,043,242
0
0
null
null
null
null
UTF-8
Java
false
false
499
java
package com.odinson.chatroom.encoder; import com.alibaba.fastjson.JSON; import com.odinson.chatroom.chat.Message; import javax.websocket.Encoder; import javax.websocket.EndpointConfig; public class MessageEncoder implements Encoder.Text<Message> { @Override public String encode(Message message) { return JSON.toJSONString(message); } @Override public void init(EndpointConfig endpointConfig) { } @Override public void destroy() { } }
[ "viktoray007@gmail.com" ]
viktoray007@gmail.com
faca18e6777c6c6c6d2497f016ca79267acdec78
78911f06d1b93046192f87592b148abc82433043
/group17/240094626/warm-up/src/com/litestruts/exception/StrutsXMLLoaderException.java
4efb8b915264d6653a636bf32b963aeab00dd8af
[]
no_license
Ni2014/coding2017
0730bab13b83aad82b41bb28552a6235e406c534
2732d351bd24084b00878c434e73a8f7f967801e
refs/heads/master
2021-01-17T14:20:20.163788
2017-03-20T03:21:12
2017-03-20T03:21:12
84,085,757
5
18
null
2017-05-04T15:06:23
2017-03-06T14:55:49
Java
UTF-8
Java
false
false
1,620
java
package com.coderising.litestruts.exception; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; public class StrutsXMLLoaderException extends Exception { private static final long serialVersionUID = 5481955299021871754L; private String message; private String stackTrace; private Throwable t; public Throwable getCause() { return this.t; } public String toString() { return getMessage(); } public String getMessage() { return this.message; } public void printStackTrace() { System.err.print(this.stackTrace); } public void printStackTrace(PrintStream paramPrintStream) { printStackTrace(new PrintWriter(paramPrintStream)); } public void printStackTrace(PrintWriter paramPrintWriter) { paramPrintWriter.print(this.stackTrace); } public StrutsXMLLoaderException(String paramString) { super(paramString); this.message = paramString; this.stackTrace = paramString; } public StrutsXMLLoaderException(Throwable paramThrowable) { super(paramThrowable.getMessage()); this.t = paramThrowable; StringWriter localStringWriter = new StringWriter(); paramThrowable.printStackTrace(new PrintWriter(localStringWriter)); this.stackTrace = localStringWriter.toString(); } public StrutsXMLLoaderException(String paramString, Throwable paramThrowable) { super(paramString + "; nested exception is " + paramThrowable.getMessage()); this.t = paramThrowable; StringWriter localStringWriter = new StringWriter(); paramThrowable.printStackTrace(new PrintWriter(localStringWriter)); this.stackTrace = localStringWriter.toString(); } }
[ "michael-ketty@qq.com" ]
michael-ketty@qq.com
583c482cea52a317d8d9f96ea8055a3b20acce1a
271dd45203c05cb7b896bce16f3b785a4f859ce1
/app/src/main/java/com/example/fyp/ContentBasedFiltering.java
1c620a9f221243811b0bc2efbc970384e8c89f94
[]
no_license
Raj14619/Car-Recommendation-System
7ef49e1d3e914d271f04b6c716db0d5e6994e6ba
ffbc2784354df86efe1918b7c60124545d9c32e6
refs/heads/main
2023-05-09T16:11:46.064992
2021-06-02T05:34:46
2021-06-02T05:34:46
372,978,634
2
0
null
null
null
null
UTF-8
Java
false
false
21,548
java
package com.example.fyp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; public class ContentBasedFiltering extends AppCompatActivity { Button RecommendationButton; Boolean raj = false; TextView TextViewRecommendedCar; String userAobjectID; String userAcurrentCarManufacturer; String userAcurrentCarModel; String userAcurrentCarTrim; String userAcurrentCarYearWasMade; String userAcurrentCarWhenCarWasBought; String userAcurrentCarHowMuchWasBoughtFor; String userAIdealCarManufacturer; String userAIdealCarModel; String userAIdealCarTrim; String userAIdealCarYearWasMade; String userAIdealCarWhenToPurchase; String userAIdealCarHowMuchToBuyFor; String userAcurrentCarComfort; String userAcurrentCarSpeedRating; String userAcurrentCarSpaceRating; String userAcurrentCarSafetyRating; String userAcurrentCarSuitabilityForEverydayUseRating; String userAidealCarComfortRating; String userAidealCarSpeedRating ; String userAidealCarSpaceRating ; String userAidealCarSafetyRating ; String userAidealCarSuitabilityForEverydayUseRating; // ArrayList<String> UserBobjectID = new ArrayList<String>(); ArrayList<String> UserBcurrentCarManufacturer = new ArrayList<String>(); ArrayList<String> UserBcurrentCarModel = new ArrayList<String>(); ArrayList<String> UserBcurrentCarTrim = new ArrayList<String>(); ArrayList<String> UserBcurrentCarYearWasMade = new ArrayList<String>(); ArrayList<String> UserBcurrentCarWhenCarWasMade = new ArrayList<String>(); ArrayList<String> UserBcurrentCarWhenCarWasBought = new ArrayList<String>(); ArrayList<String> UserBcurrentCarHowMuchWasBoughtFor = new ArrayList<String>(); ArrayList<String> UserBidealCarManufacturer = new ArrayList<String>(); ArrayList<String> UserBidealCarModel = new ArrayList<String>(); ArrayList<String> UserBIdealCarTrim = new ArrayList<String>(); ArrayList<String> UserBIdealCarYearWasMade = new ArrayList<String>(); ArrayList<String> UserBIdealCarWhenToPurchase = new ArrayList<String>(); ArrayList<String> UserBIdealCarHowMuchToBuyFor = new ArrayList<String>(); ArrayList<String> UserBcurrentCarComfort = new ArrayList<String>(); ArrayList<String> UserBcurrentCarSpeedRating = new ArrayList<String>(); ArrayList<String> UserBcurrentCarSpaceRating = new ArrayList<String>(); ArrayList<String> UserBcurrentCarSafetyRating = new ArrayList<String>(); ArrayList<String> UserBcurrentCarSuitabilityForEverydayUseRating = new ArrayList<String>(); ArrayList<String> UserBidealCarComfortRating = new ArrayList<String>(); ArrayList<String> UserBidealCarSpeedRating = new ArrayList<String>(); ArrayList<String> UserBidealCarSpaceRating = new ArrayList<String>(); ArrayList<String> UserBidealCarSafetyRating = new ArrayList<String>(); ArrayList<String> UserBidealCarSuitabilityForEverydayUseRating = new ArrayList<String>(); // // String BestUserCurrentCarManufacturer = ""; String BestUserCurrentCarModel = ""; String BestUserCurrentCarTrim = ""; String BestUserCurrentCarYearWasMade = ""; String BestUserCurrentCarHowMuchWasBoughtFor = ""; String BestUserCurrentCarWhenCarWasBought = ""; String BestUserIdealCarManufacturer = ""; String BestUserIdealCarModel = ""; String BestUserIdealNextCarTrim = ""; String BestUserIdealCarYearWasMade = ""; String BestUserIdealCarWhenToPurchase = ""; String BestUserIdealCarPrice = ""; String BestusercurrentCarComfort; String BestusercurrentCarSpeedRating; String BestusercurrentCarSpaceRating; String BestusercurrentCarSafetyRating; String BestusercurrentCarSuitabilityForEverydayUseRating; String BestuseridealCarComfortRating; String BestuseridealCarSpeedRating ; String BestuseridealCarSpaceRating ; String BestuseridealCarSafetyRating ; String BestuseridealCarSuitabilityForEverydayUseRating; /**/ double BestUserIdealCarPriceDepreciated = 0; double BestUserCurrentCarPriceDepreciated = 0; double BestUserCurrentCarManufacturerDepreciation = 0; double BestUserIdealCarManufacturerDepreciation = 0; // boolean recommendCurrentCar; boolean didWeFindAMatch = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_content_based_filtering); // TextViewRecommendedCar = (TextView) findViewById(R.id.textView14); RecommendationButton = findViewById(R.id.RecommendationButton); RecommendationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { contentBasedFiltering(); } }); } public void contentBasedFiltering() { getUserAInformation(); getUserBInformation(); // getRecommendations(); Log.d("LINE 99", BestUserCurrentCarManufacturer); } public void getUserAInformation() { // WORKS AS INTENDED ParseUser userA = ParseUser.getCurrentUser(); userAobjectID = userA.getObjectId(); userAcurrentCarManufacturer = userA.getString("currentCarManufacturer"); Log.d("74", userAcurrentCarManufacturer); userAcurrentCarModel = userA.getString("currentCarModel"); Log.d("76", userAcurrentCarModel); userAcurrentCarTrim = userA.getString("currentCarTrim"); Log.d("78", userAcurrentCarTrim); userAcurrentCarYearWasMade = userA.getString("currentCarYearWasMade"); Log.d("80", userAcurrentCarYearWasMade); userAcurrentCarWhenCarWasBought = userA.getString("currentCarWhenCarWasBought"); Log.d("82", userAcurrentCarWhenCarWasBought); userAcurrentCarHowMuchWasBoughtFor = userA.getString("currentCarHowMuchWasBoughtFor"); Log.d("84", userAcurrentCarHowMuchWasBoughtFor); userAIdealCarManufacturer = userA.getString("idealCarManufacturer"); Log.d("86", userAIdealCarManufacturer); userAIdealCarModel = userA.getString("idealCarModel"); Log.d("88", userAIdealCarModel); userAIdealCarTrim = userA.getString("idealNextCarTrim"); Log.d("90", userAIdealCarTrim); userAIdealCarYearWasMade = userA.getString("idealCarYearWasMade"); Log.d("92", userAIdealCarYearWasMade); userAIdealCarWhenToPurchase = userA.getString("idealCarWhenToPurchase"); Log.d("94", userAIdealCarWhenToPurchase); userAIdealCarHowMuchToBuyFor = userA.getString("idealCarHowMuchToBuyFor"); Log.d("96", userAIdealCarHowMuchToBuyFor); userAcurrentCarComfort = userA.getString("idealCarComfortRating"); userAcurrentCarSpeedRating = userA.getString("currentCarSpeedRating"); userAcurrentCarSpaceRating = userA.getString("currentCarSpaceRating"); userAcurrentCarSafetyRating = userA.getString("currentCarSafetyRating"); userAcurrentCarSuitabilityForEverydayUseRating = userA.getString("currentCarSuitabilityForEverydayUseRating"); userAidealCarComfortRating = userA.getString("idealCarComfortRating"); userAidealCarSpeedRating = userA.getString("idealCarSpeedRating"); userAidealCarSpaceRating = userA.getString("idealCarSpaceRating"); userAidealCarSafetyRating = userA.getString("idealCarSafetyRating"); userAidealCarSuitabilityForEverydayUseRating = userA.getString("idealCarSuitabilityForEverydayUseRating"); } public void getUserBInformation() { ParseQuery<ParseUser> query = ParseUser.getQuery(); query.findInBackground(new FindCallback<ParseUser>() { @Override public void done(List<ParseUser> objects, ParseException e) { if (e == null) { if (objects.size() > 0) { for (int i = 0; i < objects.size(); i++) { if (!(objects.get(i).getObjectId().equals(userAobjectID))) { ParseObject p = objects.get(i); UserBobjectID.add(p.getObjectId()); UserBcurrentCarManufacturer.add(p.getString("currentCarManufacturer")); UserBcurrentCarModel.add(p.getString("currentCarModel")); UserBcurrentCarTrim.add(p.getString("currentCarTrim")); UserBcurrentCarYearWasMade.add(p.getString("currentCarYearWasMade")); UserBcurrentCarWhenCarWasMade.add(p.getString("currentCarWhenCarWasMade")); UserBcurrentCarWhenCarWasBought.add(p.getString("currentCarWhenCarWasBought")); UserBcurrentCarHowMuchWasBoughtFor.add(p.getString("currentCarHowMuchWasBoughtFor")); UserBidealCarManufacturer.add(p.getString("idealCarManufacturer")); UserBidealCarModel.add(p.getString("idealCarModel")); UserBIdealCarTrim.add(p.getString("idealNextCarTrim")); UserBIdealCarYearWasMade.add(p.getString("idealCarYearWasMade")); UserBIdealCarWhenToPurchase.add(p.getString("idealCarWhenToPurchase")); UserBIdealCarHowMuchToBuyFor.add(p.getString("idealCarHowMuchToBuyFor")); UserBcurrentCarComfort.add(p.getString("currentCarComfortRating")); UserBcurrentCarSpeedRating.add(p.getString("currentCarSpeedRating")); UserBcurrentCarSpaceRating.add(p.getString("currentCarSpaceRating")); UserBcurrentCarSafetyRating.add(p.getString("currentCarSafetyRating")); UserBcurrentCarSuitabilityForEverydayUseRating.add(p.getString("currentCarSuitabilityForEverydayUseRating")); UserBidealCarComfortRating.add(p.getString("idealCarComfortRating")); UserBidealCarSpeedRating.add(p.getString("idealCarSpeedRating")); UserBidealCarSpaceRating.add(p.getString("idealCarSpaceRating")); UserBidealCarSafetyRating.add(p.getString("idealCarSafetyRating")); UserBidealCarSuitabilityForEverydayUseRating.add(p.getString("idealCarSuitabilityForEverydayUseRating")); Log.d("line 182", "182"); } } } getBestUser(); //outputRecommendedCar(); ShouldWeRecommendCurrentCar(); } } }); } public void getBestUser() { int fitness = 0; int bestFitness = 0; Log.d("204", Integer.toString(UserBcurrentCarManufacturer.size())); for (int i = 0; i < UserBcurrentCarManufacturer.size(); i++) { fitness = 0; Log.d("209", userAIdealCarWhenToPurchase); Log.d("210", UserBIdealCarWhenToPurchase.get(i)); if(userAcurrentCarComfort.equals(UserBcurrentCarComfort.get(i))){ fitness += 100; } if(userAcurrentCarSpaceRating.equals(UserBcurrentCarSpaceRating.get(i))){ fitness += 100; } if(userAcurrentCarSafetyRating.equals(UserBcurrentCarSafetyRating.get(i))){ fitness += 100; } if(userAcurrentCarSuitabilityForEverydayUseRating.equals(UserBcurrentCarSuitabilityForEverydayUseRating.get(i))){ fitness += 100; } if(userAcurrentCarComfort.equals(UserBcurrentCarComfort.get(i))){ fitness+=100; } if(userAidealCarSpeedRating.equals(UserBidealCarSpeedRating.get(i))){ fitness+=100; } if(userAidealCarSpaceRating.equals(UserBidealCarSpaceRating.get(i))){ fitness+=100; } if(userAidealCarSafetyRating.equals(UserBidealCarSafetyRating.get(i))){ fitness+=100; } if(userAidealCarSuitabilityForEverydayUseRating.equals(UserBidealCarSafetyRating.get(i))){ fitness+=100; } if (fitness >= bestFitness) { bestFitness = fitness; didWeFindAMatch = true; BestUserCurrentCarManufacturer = UserBcurrentCarManufacturer.get(i); BestUserCurrentCarModel = UserBcurrentCarModel.get(i); BestUserCurrentCarTrim = UserBcurrentCarTrim.get(i); BestUserCurrentCarYearWasMade = UserBcurrentCarYearWasMade.get(i); BestUserCurrentCarHowMuchWasBoughtFor = UserBcurrentCarHowMuchWasBoughtFor.get(i); BestUserCurrentCarWhenCarWasBought = UserBcurrentCarWhenCarWasBought.get(i); BestUserIdealCarManufacturer = UserBidealCarManufacturer.get(i); BestUserIdealCarModel = UserBidealCarModel.get(i); BestUserIdealNextCarTrim = UserBIdealCarTrim.get(i); BestUserIdealCarYearWasMade = UserBIdealCarYearWasMade.get(i); BestUserIdealCarWhenToPurchase = UserBIdealCarWhenToPurchase.get(i); BestusercurrentCarComfort = UserBcurrentCarComfort.get(i); BestusercurrentCarSpeedRating = UserBcurrentCarSpeedRating.get(i); BestusercurrentCarSpaceRating = UserBcurrentCarSpaceRating.get(i); BestusercurrentCarSafetyRating = UserBcurrentCarSafetyRating.get(i); BestusercurrentCarSuitabilityForEverydayUseRating = UserBcurrentCarSuitabilityForEverydayUseRating.get(i); BestuseridealCarComfortRating = UserBidealCarComfortRating.get(i); BestuseridealCarSpeedRating = UserBidealCarSpeedRating.get(i); BestuseridealCarSpaceRating = UserBidealCarSpaceRating.get(i); BestuseridealCarSafetyRating = UserBidealCarSafetyRating.get(i); BestuseridealCarSuitabilityForEverydayUseRating = UserBidealCarSuitabilityForEverydayUseRating.get(i); Log.d("Line 284", BestUserCurrentCarManufacturer); Log.d("Line 286", BestUserCurrentCarModel); Log.d("Line 288", BestUserCurrentCarTrim); Log.d("Line 290", BestUserCurrentCarYearWasMade); Log.d("Line 292", BestUserCurrentCarHowMuchWasBoughtFor); Log.d("Line 294", BestUserCurrentCarWhenCarWasBought); Log.d("Line 296", BestUserIdealNextCarTrim); Log.d("Line 298", BestUserIdealCarYearWasMade); Log.d("Line 300", BestUserIdealCarWhenToPurchase); } } } public void ShouldWeRecommendCurrentCar (){ Log.d("300", BestUserIdealNextCarTrim); Log.d("300", BestUserIdealCarYearWasMade); //double UserAbudgetMinusUserBcurrentCar = depreciateCarValue(userAIdealCarHowMuchToBuyFor, BestUserCurrentCarHowMuchWasBoughtFor); ParseQuery<ParseObject> query = ParseQuery.getQuery("Cars"); query.whereEqualTo("CarTrim", BestUserIdealNextCarTrim); query.whereEqualTo("CarYearMade", BestUserIdealCarYearWasMade); query.setLimit(1); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (objects.size() > 0) { for (ParseObject object : objects) { BestUserIdealCarPrice = object.getString("CarPrice"); Log.d("yhyh", BestUserIdealCarPrice); } } calculateToFigureCurrentOrIdealCar(); } }); Log.d("shouldok", BestUserCurrentCarHowMuchWasBoughtFor); // double UserAbudgetMinusUserBidealCar = depreciateCarValue(userAIdealCarHowMuchToBuyFor,BestUserIdealCarPrice ); } public void calculateToFigureCurrentOrIdealCar(){ BestUserCurrentCarPriceDepreciated = Integer.valueOf(BestUserCurrentCarHowMuchWasBoughtFor); int BestUserCurrentCarYearBoughtMinusUserAYearToBuy = Integer.valueOf(userAIdealCarWhenToPurchase) - Integer.valueOf(BestUserCurrentCarWhenCarWasBought); if (BestUserCurrentCarManufacturer.equals("FORD") || BestUserCurrentCarManufacturer.equals("AUDI")){ BestUserCurrentCarManufacturerDepreciation = 0.4; Log.d("i is", "361"); }else if(BestUserCurrentCarManufacturer.equals("BMW")){ BestUserCurrentCarManufacturerDepreciation = 0.35; Log.d("i is", "363"); } Log.d("365", BestUserCurrentCarManufacturer); BestUserCurrentCarManufacturerDepreciation = BestUserCurrentCarManufacturerDepreciation/3; for(int i = 0; i < BestUserCurrentCarYearBoughtMinusUserAYearToBuy; i++){ Log.d("i is", Integer.toString(i)); BestUserCurrentCarPriceDepreciated = BestUserCurrentCarPriceDepreciated*(1.00-BestUserCurrentCarManufacturerDepreciation); Log.d("392", String.valueOf(BestUserCurrentCarPriceDepreciated)); } BestUserIdealCarPriceDepreciated = Integer.valueOf(BestUserIdealCarPrice); int BestUserIdealCarYearBoughtMinusUserAYearToBuy = Integer.valueOf(userAIdealCarWhenToPurchase) - 2019; Log.d("1000",BestUserIdealCarManufacturer); if (BestUserIdealCarManufacturer.equals("FORD") || BestUserIdealCarManufacturer.equals("AUDI")) { BestUserIdealCarManufacturerDepreciation = 0.4; Log.d("2000", "2000"); } else if(BestUserIdealCarManufacturer.equals("BMW")){ BestUserIdealCarManufacturerDepreciation = 0.35; Log.d("3000","3000"); } Log.d("390", String.valueOf(BestUserIdealCarManufacturerDepreciation)); BestUserIdealCarManufacturerDepreciation = BestUserIdealCarManufacturerDepreciation/3; for(int i = 0; i < BestUserIdealCarYearBoughtMinusUserAYearToBuy; i++){ BestUserIdealCarPriceDepreciated = BestUserIdealCarPriceDepreciated*(1.00-BestUserIdealCarManufacturerDepreciation); Log.d("391", String.valueOf(BestUserIdealCarPriceDepreciated)); } // Log.d("391", String.valueOf(BestUserIdealCarPriceDepreciated)); // Log.d("392", String.valueOf(BestUserCurrentCarPriceDepreciated)); if(BestUserCurrentCarPriceDepreciated <= Double.valueOf(userAIdealCarHowMuchToBuyFor)){ recommendCurrentCar = true; } else{ recommendCurrentCar = false; } TextView carManufacturerTextView = findViewById(R.id.carManufacturerTextView); TextView carModelTextView = findViewById(R.id.carModelTextView); TextView carTrimTextView = findViewById(R.id.CarTrimTextView); TextView carYearWasMadeTextView = findViewById(R.id.carYearWasMadeTextView); TextView carPriceTextView = findViewById(R.id.carPriceTextView); // TextView carYearToBuyTextView = findViewById(R.id.carYearToBuyTextView); if(didWeFindAMatch == false){ carManufacturerTextView.setText("NO MATCH WAS FOUND"); carModelTextView.setText("NO MATCH WAS FOUND"); carTrimTextView.setText("NO MATCH WAS FOUND"); carYearWasMadeTextView.setText("NO MATCH WAS FOUND"); carPriceTextView.setText("NO MATCH WAS FOUND"); carYearToBuyTextView.setText("NO MATCH WAS FOUND"); } else if(recommendCurrentCar == true){ carManufacturerTextView.setText(BestUserCurrentCarManufacturer); carModelTextView.setText(BestUserCurrentCarModel); carTrimTextView.setText(BestUserCurrentCarTrim); carYearWasMadeTextView.setText(BestUserCurrentCarYearWasMade); carPriceTextView.setText(Double.toString(BestUserCurrentCarPriceDepreciated)); carYearToBuyTextView.setText(userAIdealCarWhenToPurchase); }else { carManufacturerTextView.setText(BestUserIdealCarManufacturer); carModelTextView.setText(BestUserIdealCarModel); carTrimTextView.setText(BestUserIdealNextCarTrim); carYearWasMadeTextView.setText(BestUserIdealCarYearWasMade); carPriceTextView.setText(Double.toString(BestUserIdealCarPriceDepreciated)); carYearToBuyTextView.setText(userAIdealCarWhenToPurchase); } } public void test(String test) { TextViewRecommendedCar.setText(UserBcurrentCarManufacturer.get(0)); Log.d("line 234", Integer.toString(UserBobjectID.size())); for (int i = 0; i < UserBobjectID.size(); i++) { Log.d("line 236", UserBobjectID.get(i)); } } }
[ "33152218+Raj14619@users.noreply.github.com" ]
33152218+Raj14619@users.noreply.github.com
2335245bdbc4269113617f59770fd92f2b4319b2
9b655bd9569cc99146df3afc0cfa8e85b1525cf4
/src/com/test/Main.java
cf84833017ad155232d4a030e3da927b04932981
[]
no_license
kiba945/TestJUnit
8ad36c1de62ca2d471183be4b440472b6eb3f40f
471b7b027abc6ba93a8a4e87b5317c8357c940bc
refs/heads/master
2021-01-06T20:42:58.816649
2015-01-16T10:30:03
2015-01-16T10:30:03
29,344,052
0
0
null
null
null
null
UTF-8
Java
false
false
216
java
package com.test; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Calcul total = new Calcul(); System.out.println("TOTAL : " + total.add(10,20)); } }
[ "patrice945@gmail.com" ]
patrice945@gmail.com
5fa19d5a756eef6ef623fe685587d6d4cc81b97a
f497ce663579fa00cb2bd946dcd1631fabe5e425
/src/main/java/com/zking/ssm/mapper/UserInfoMapper.java
dbea1fc408517c05784c9cd61eb0175d20d822df
[]
no_license
ssmSession/ssm
eb4f2f2d5806faceffbf5956c4d2de51c20d1ed9
eb9128fa67f0f28fa7ca86b572c279b71af6a086
refs/heads/master
2022-12-22T05:22:45.945404
2020-01-18T05:53:00
2020-01-18T05:53:00
227,544,167
0
0
null
2019-12-12T08:09:18
2019-12-12T07:16:10
Java
UTF-8
Java
false
false
382
java
package com.zking.ssm.mapper; import com.zking.ssm.model.Logininfo; import com.zking.ssm.model.Userinfo; import java.util.List; /** * 用户信息 */ public interface UserInfoMapper { /** * 根据login登录的账号信息进行链表查询 * @param logininfoId * @return */ public List<Userinfo> getUserInfoByLoginInfoId (Integer logininfoId); }
[ "254690780@qq.com" ]
254690780@qq.com
b0b085489b776037ef5e21e22598a85b838878ab
318b1bd8c91d933dbe0b377d5683552304dcc9d8
/app/src/main/java/com/abamed/fcisassistant/TopNavigationBehavior.java
7d0223a751eb64b1eab3f20968d313202ba6b297
[]
no_license
ahmednafea/FcisAssistant
efe7b6a4596eeb9642c120d1306567bf27bc944c
f8da88559527ae9069ba8b64c2b0d14500d7a495
refs/heads/master
2020-03-15T21:24:38.258963
2018-06-03T14:18:51
2018-06-03T14:18:51
132,354,459
0
0
null
null
null
null
UTF-8
Java
false
false
1,683
java
package com.abamed.fcisassistant; import android.content.Context; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.design.widget.CoordinatorLayout; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; public class TopNavigationBehavior extends CoordinatorLayout.Behavior<BottomNavigationView> { TopNavigationBehavior() { super(); } public TopNavigationBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, BottomNavigationView child, View dependency) { return dependency instanceof FrameLayout; } @Override public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View directTargetChild, @NonNull View target, int nestedScrollAxes) { return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL; } @Override public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull BottomNavigationView child, @NonNull View target, int dx, int dy, @NonNull int[] consumed) { if (dy < 0) { showBottomNavigationView(child); } else if (dy > 0) { hideBottomNavigationView(child); } } private void hideBottomNavigationView(BottomNavigationView view) { view.animate().translationY(-200); } private void showBottomNavigationView(BottomNavigationView view) { view.animate().translationY(0); } }
[ "32443261+ahmednafea@users.noreply.github.com" ]
32443261+ahmednafea@users.noreply.github.com
4f4e888bec20cec52dd0694cdf112451919be466
ab2f83a2ed230af93433d7ab01d3c0bd9cc391fc
/src/main/java/Classes/Beans/DotsService.java
ff664b269ce5d6ad2d15312f092d8a871f7c2d6e
[]
no_license
jenkeyx/pip4
fcfde93a3c4dee6eb3237b2be339a4d220bfa13c
13b3d349f582dfced09a82a48e86db43b64bdfee
refs/heads/master
2022-10-16T16:41:21.935245
2020-05-22T14:34:45
2020-05-22T14:34:45
234,787,038
0
0
null
null
null
null
UTF-8
Java
false
false
882
java
package Classes.Beans; import Classes.Spring.Data.DotRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DotsService { DotRepo dotRepo; @Autowired public DotsService(DotRepo dotRepo) { this.dotRepo = dotRepo; } public List<Dot> getDotsByUsername(String username) { return dotRepo.findAllByOwner(username); } public void saveDot(Dot dot) { dot.setHit(checkArea(dot)); dotRepo.save(dot); } public static boolean checkArea(Dot dot) { double x = dot.x; double y = dot.y; double r = dot.r; return (x >= 0 && y >= 0 && r * r >= x * x + y * y) || (x <= 0 && y >= 0 && x >= -r / 2 && y <= r) || (x <= 0 && y <= 0 && y >= -x - r / 2); } }
[ "megas1200812@ya.ru" ]
megas1200812@ya.ru
e6891f4291a07b4d4bfa6606a8a0b423ad26ebbb
b52bd06cba411b60f7c2fda6e0408b16da82ab2e
/src/main/java/com/jackoak/Adapter/JackoakMouseWheelListener.java
1c87d75d7317f5875068b6b98d67a7395947d1dc
[]
no_license
jackoak/jackoak.github.io
80c9f7b7680bd2a46232027d5ae109d4216f7ab0
5914354fc403937759971f1d217103f5b89fa881
refs/heads/master
2020-04-16T13:43:24.197883
2019-04-03T08:18:50
2019-04-03T08:18:50
165,639,924
0
0
null
null
null
null
UTF-8
Java
false
false
806
java
package com.jackoak.Adapter; import com.jackoak.Device.Camera; import com.jackoak.base.Context; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; public class JackoakMouseWheelListener implements MouseWheelListener { private double mouseWheel = 2; //步进距离 public JackoakMouseWheelListener(double mouseWheel){ this.mouseWheel = mouseWheel; } @Override public void mouseWheelMoved(MouseWheelEvent e) { Camera camera = Context.getCamera(); if(e.getWheelRotation()==1){//向前滑动 camera.dMove( 1 * mouseWheel * 1); }else if(e.getWheelRotation()== -1){//向后滑动 camera.dMove( 1 * mouseWheel * -1); } System.out.println("camera.getD() : " + camera.getD()); } }
[ "ranqiming@gyyx.cn" ]
ranqiming@gyyx.cn
cf7800b24c3ec3464e96d82fe2efaa960f9ef775
6d8f7eec3ccc440d7c68ea4e17b5298ffd58429e
/src/server/DeleteAccountFrame2.java
42331b8ed54005d8722336724fc99dfa7d177ea2
[]
no_license
TuanAnhPhanDepZai/HePhanTan_TuanAnh
29691772883eaea5cbdb362a54d82fde62b47fc6
13ad17719d75d7e4ede93379903ddb48ac0a6166
refs/heads/master
2020-04-08T03:09:50.740348
2018-11-24T18:54:03
2018-11-24T18:54:03
158,964,362
0
0
null
null
null
null
UTF-8
Java
false
false
9,187
java
/* * 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 server; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import service.DeleteAccountUser; /** * * @author phant */ public class DeleteAccountFrame2 extends javax.swing.JFrame { private ServerThread2 serverThread; private ServerFrameBank2 serverFrameBank; public DeleteAccountFrame2(ServerThread2 serverThread , ServerFrameBank2 serverFrameBank) { this.serverFrameBank = serverFrameBank; this.serverThread = serverThread; initComponents(); } public ServerThread2 getServerThread() { return serverThread; } public void setServerThread(ServerThread2 serverThread) { this.serverThread = serverThread; } public ServerFrameBank2 getServerFrameBank() { return serverFrameBank; } public void setServerFrameBank(ServerFrameBank2 serverFrameBank) { this.serverFrameBank = serverFrameBank; } public JTextField getAccountNameText() { return accountNameText; } public void setAccountNameText(JTextField accountNameText) { this.accountNameText = accountNameText; } public JButton getjButton1() { return jButton1; } public void setjButton1(JButton jButton1) { this.jButton1 = jButton1; } public JButton getjButton2() { return jButton2; } public void setjButton2(JButton jButton2) { this.jButton2 = jButton2; } public JLabel getjLabel1() { return jLabel1; } public void setjLabel1(JLabel jLabel1) { this.jLabel1 = jLabel1; } public JLabel getjLabel2() { return jLabel2; } public void setjLabel2(JLabel jLabel2) { this.jLabel2 = jLabel2; } public JLabel getjLabel3() { return jLabel3; } public void setjLabel3(JLabel jLabel3) { this.jLabel3 = jLabel3; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); accountNameText = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel2.setText("jLabel2"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("XÓA TÀI KHOẢN"); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("TÊN TÀI KHOẢN"); jButton1.setText("XÓA TÀI KHOẢN"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("EXIT"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(89, 89, 89) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap(28, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(accountNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(accountNameText, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(17, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String accountName = accountNameText.getText(); String requestToServer = "xoataikhoan:"+accountName; if (accountName.equals("")) { JOptionPane.showMessageDialog(null, "Bạn phải nhập đầy đủ các trường dữ liệu"); } else { // chuyen thong diep den server con lai, sau do nhan thong diep va phan hoi lai cho chu ngan hang this.getServerThread().sendMessageToServer(requestToServer); // nhan thong diep gui tu server con lai int i = 0; while (true) { // doi server phan hoi // String responseFromServer = this.getServerThread().getMessage(); // System.out.println("message vai : " + this.getServerThread().getMessage()); if (this.getServerThread().getFlag() == 1) { break; } System.out.println("message: " + this.getServerThread().getMessage()); System.out.println("Flag: " + this.getServerThread().getFlag()); i++; System.out.println("i:" + i); } String responseFromServer = this.getServerThread().getMessage(); if (responseFromServer.equals("")) { // truong hop nay la that bai, ta can phan hoi lai cho nguoi dung la khong tao dc account nay va nguyen nhan } else { // truong hop tao tai khoan moi thanh cong, can phai thuc hien thao tac update vao database if (responseFromServer.equals("khongtontaitaikhoan")) { JOptionPane.showMessageDialog(null, "Tài khoản này không tồn tại."); } else { DeleteAccountUser.deleteAccount(accountName); JOptionPane.showMessageDialog(null, "Xóa tài khoản thành công."); this.setVisible(false); serverFrameBank.setVisible(true); } } } }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField accountNameText; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration//GEN-END:variables }
[ "phantuananhkt2204k60@gmail.com" ]
phantuananhkt2204k60@gmail.com
0ae5e7b10ecfbefba8872a4a37f401422ee344e4
59081bce573e8a995b1663be20bd4f4d56222ff2
/banking-stream-impl/src/main/java/com/zafin/bankingdemo/stream/impl/StreamModule.java
d29607b4d1d17829cb243895e9243dfdaa00073d
[]
no_license
lloydchandran-zafinlabs/banking-demo
b2b7b121851469dfa4ad0ef6146fe65a58b503c9
df7ebe4b113353c23f9ebaf9aac4c0c5f1e036b5
refs/heads/master
2020-08-01T04:36:58.348559
2019-09-25T14:31:44
2019-09-25T14:31:44
210,865,649
0
0
null
null
null
null
UTF-8
Java
false
false
749
java
package com.zafin.bankingdemo.stream.impl; import com.google.inject.AbstractModule; import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; import com.zafin.bankingdemo.hello.api.HelloService; import com.zafin.bankingdemo.stream.api.StreamService; /** * The module that binds the StreamService so that it can be served. */ public class StreamModule extends AbstractModule implements ServiceGuiceSupport { @Override protected void configure() { // Bind the StreamService service bindService(StreamService.class, StreamServiceImpl.class); // Bind the HelloService client bindClient(HelloService.class); // Bind the subscriber eagerly to ensure it starts up bind(StreamSubscriber.class).asEagerSingleton(); } }
[ "lloyd.chandran@zafin.com" ]
lloyd.chandran@zafin.com
b024287fbb092faf62de9b07d2fc193a6a14e6a4
f6a1ed0383eb1331072a42a8fb4309e13056495b
/app/src/main/java/com/example/kk/arttraining/ui/homePage/activity/ThemeTeacher.java
5601e95c830596048581d07744d0a554db28bba6
[]
no_license
kanghuicong/ArtTraining
b02250a3a6dd20ef32d0b6f92a378791363a6824
82eb115f2771faaf9eec1fbfa6259158ac52f9e6
refs/heads/master
2021-01-24T01:03:03.553578
2017-05-11T07:16:06
2017-05-11T07:16:06
68,698,436
2
1
null
null
null
null
UTF-8
Java
false
false
3,971
java
package com.example.kk.arttraining.ui.homePage.activity; import android.os.Bundle; import android.os.PersistableBundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.widget.Toast; import com.example.kk.arttraining.R; import com.example.kk.arttraining.utils.UIUtil; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; /** * Created by kanghuicong on 2016/12/6. * QQ邮箱:515849594@qq.com */ public class ThemeTeacher extends FragmentActivity { @InjectView(R.id.tabs) TabLayout tabs; @InjectView(R.id.viewPager) ViewPager viewPager; private List<String> mTitleList = new ArrayList<>(); String type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.homepage_teacher); ButterKnife.inject(this); type = getIntent().getStringExtra("type"); initView(); } private void initView() { if (!type.equals("art")) { mTitleList.add("全部"); mTitleList.add("声乐"); mTitleList.add("器乐"); mTitleList.add("舞蹈"); mTitleList.add("表演"); mTitleList.add("编导"); mTitleList.add("书画"); } else { mTitleList.add("全部"); mTitleList.add("国内名师"); mTitleList.add("海外华人艺术家"); mTitleList.add("国际名师"); } for (int n = 0; n < mTitleList.size(); n++) { tabs.addTab(tabs.newTab().setText(mTitleList.get(n))); } MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager(), mTitleList); viewPager.setAdapter(adapter); tabs.setupWithViewPager(viewPager);//将TabLayout和ViewPager关联起来,viewpager滑动与table一起切换 tabs.setTabsFromPagerAdapter(adapter); } public class MainPagerAdapter extends FragmentPagerAdapter { private List<String> mTitleList; public MainPagerAdapter(FragmentManager fm, List<String> mTitleList) { super(fm); this.mTitleList = mTitleList; } @Override public Fragment getItem(int position) { Fragment fragment; if (position == 0) { if (type.equals("art")) { fragment = new ThemeTeacherArtFragment(); } else { fragment = new ThemeTeacherFragment(); } Bundle bundle = new Bundle(); bundle.putString("type", type); bundle.putString("major", ""); fragment.setArguments(bundle); } else { if (type.equals("art")) { fragment = new ThemeTeacherArtFragment(); } else { fragment = new ThemeTeacherFragment(); } Bundle bundle = new Bundle(); bundle.putString("type", type); bundle.putString("major", mTitleList.get(position)); fragment.setArguments(bundle); } return fragment; } @Override public int getCount() { return mTitleList.size(); } @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) { finish(); } return true; } }
[ "515849594@qq.com" ]
515849594@qq.com
5ffb5a5512c48a121581070d58d9730d5fe44633
a6c6cc9c7bcd0cfbc3cbf5d232bcfb74eb35f96d
/Spring/api-obter-diploma/src/main/java/br/com/meli/apiobterdiploma/model/Diploma.java
3f309ef4b770b58a2f836b39fefaa1909581b325
[]
no_license
ElvisNogueiraMELI/BootcampMELI-wave-2
d14cf6251496e33f497c0dcedd9a9d83bb1574f9
ed4ed2584e1e91a1d4f4838d4bf071c4a706573b
refs/heads/master
2023-06-17T09:32:35.789024
2021-07-20T22:31:51
2021-07-20T22:31:51
381,225,507
1
0
null
null
null
null
UTF-8
Java
false
false
689
java
package br.com.meli.apiobterdiploma.model; public class Diploma { private String nome; private double media; private String mensagem; public Diploma(String nome, double media, String mensagem) { super(); this.nome = nome; this.media = media; this.mensagem = mensagem; } public Diploma() { super(); } public String getAluno() { return nome; } public void setAluno(String nome) { this.nome = nome; } public double getMedia() { return media; } public void setMedia(double media) { this.media = media; } public String getMensagem() { return mensagem; } public void setMensagem(String mensagem) { this.mensagem = mensagem; } }
[ "elvis.nogueira@mercadolivre.com" ]
elvis.nogueira@mercadolivre.com
5268d3907e5e12371db92602f0dd708880c8ad8c
51376945f4a0f5280e8237337c87bb36046547c4
/test/ComplexTest/src/test/java/cz/cuni/mff/HelloWorldTest.java
8c8cb01278827d9b8a774a3c2ba250299b042266
[]
no_license
ahornace/DuplicateFilesFinder
8302803da9e46d4c1fb6374abd72290a9df157bf
043d1cc2a3a2c286818ec47a2d4a96ad1ff55129
refs/heads/master
2020-04-22T10:38:33.587353
2019-02-12T10:53:23
2019-02-12T10:53:23
170,311,824
0
1
null
null
null
null
UTF-8
Java
false
false
55
java
package cz.cuni.mff; public class HelloWorldTest { }
[ "adam.hornacek@icloud.com" ]
adam.hornacek@icloud.com
c222111fd596524a1be85cd9f55a633b2ee1ccb3
7334c6857ad8181ff7beaf4d298567e5d6a3c1e4
/paginationfx/src/main/java/hu/computertechnika/paginationfx/control/PaginationTableView.java
65d072686d553428069e263c38a0b88efdeac736
[ "MIT" ]
permissive
gbalanyi/PaginationFX
6330fa470bbb6a994396940fc70aa2b8f43d13f7
84600092f39c20523bf5e1501a0cd7148d76daaf
refs/heads/master
2020-04-04T10:03:49.705820
2018-11-06T21:36:59
2018-11-06T21:36:59
155,626,937
0
0
null
null
null
null
UTF-8
Java
false
false
17,088
java
/** * Copyright 2018 PaginationFX * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package hu.computertechnika.paginationfx.control; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import hu.computertechnika.paginationfx.PaginationSupport; import hu.computertechnika.paginationfx.data.DataProvider; import hu.computertechnika.paginationfx.filter.AbstractFilter; import hu.computertechnika.paginationfx.skin.PaginationTableViewSkin; import hu.computertechnika.paginationfx.sort.AbstractSort; import hu.computertechnika.paginationfx.sort.SortSupport; import hu.computertechnika.paginationfx.sort.SortType; import javafx.application.Platform; import javafx.beans.DefaultProperty; import javafx.beans.binding.Bindings; import javafx.beans.property.MapProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleMapProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.MapChangeListener; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.geometry.VPos; import javafx.scene.control.Control; import javafx.scene.control.Skin; import javafx.scene.control.SortEvent; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.Region; /** * @author Gábor Balanyi */ @DefaultProperty("tableView") public class PaginationTableView<UT> extends Control implements PaginationSupport, SortSupport<AbstractSort<?>> { private static final String DEFAULT_STYLE_CLASS = "pagination-table-view"; private ChangeListener<? super Number> updatePageSizeListener = (ob, oldVal, newVal) -> this.updatePageSize(); public PaginationTableView() { this.getStyleClass().add(DEFAULT_STYLE_CLASS); this.initAutoPageSize(this.getTableView()); autoPageSizeProperty().addListener((o, oldValue, newValue) -> { if (newValue) { this.initAutoPageSize(this.getTableView()); } else { this.getTableView().fixedCellSizeProperty().removeListener(updatePageSizeListener); this.getTableView().heightProperty().removeListener(updatePageSizeListener); this.getTableView().setFixedCellSize(Region.USE_COMPUTED_SIZE); pageSize.set(0); } }); this.initTableView(this.getTableView()); tableViewProperty().addListener((o, oldValue, newValue) -> { if (oldValue != null) { oldValue.getColumns().removeListener(columnListener); oldValue.getSortOrder().removeListener(sortOrderListener); if (this.isAutoPageSize()) { oldValue.fixedCellSizeProperty().removeListener(updatePageSizeListener); oldValue.heightProperty().removeListener(updatePageSizeListener); } } if (newValue != null) { this.initTableView(newValue); if (this.isAutoPageSize()) { this.initAutoPageSize(newValue); } } }); this.initPaginationNavigator(this.getPaginationNavigator()); paginationNavigatorProperty().addListener((o, oldValue, newValue) -> { if (oldValue != null) { Bindings.unbindBidirectional(this.currentPageIndexProperty(), oldValue.currentPageIndexProperty()); Bindings.unbindBidirectional(this.pageNumberProperty(), oldValue.pageNumberProperty()); } if (newValue != null) { this.initPaginationNavigator(newValue); } }); @SuppressWarnings("unchecked") MapChangeListener<Object, AbstractSort<?>> mapListener = c -> { if (this.getTableView() != null) { AbstractSort<?> sort; if (c.wasAdded()) { sort = c.getValueAdded(); } else { sort = c.getValueRemoved(); } if (this.getTableView().getColumns().contains(c.getKey())) { this.sortChanged((TableColumn<UT, ?>) c.getKey(), sort); } if (!SortType.NONE.equals(sort.getSortType())) { this.loadPage(); } } }; sortsProperty().addListener(mapListener); } @Override protected Skin<?> createDefaultSkin() { return new PaginationTableViewSkin<>(this); } protected boolean sortChanged(TableColumn<UT, ?> tableColumn) { return this.sortChanged(tableColumn, this.sortsProperty().get(tableColumn)); } protected boolean sortChanged(TableColumn<UT, ?> tableColumn, AbstractSort<?> sort) { boolean requireLoadPage = false; if (sort != null) { tableColumn.setSortable(true); if (SortType.ASCENDING.equals(sort.getSortType())) { tableColumn.setSortType(javafx.scene.control.TableColumn.SortType.ASCENDING); requireLoadPage = true; } else if (SortType.DESCENDING.equals(sort.getSortType())) { tableColumn.setSortType(javafx.scene.control.TableColumn.SortType.DESCENDING); requireLoadPage = true; } else { tableColumn.setSortType(null); } } else { tableColumn.setSortable(false); tableColumn.setSortType(null); } return requireLoadPage; } private String styleSheet; @Override public String getUserAgentStylesheet() { if (styleSheet == null) { styleSheet = this.getClass().getResource("paginationtableview.css").toExternalForm(); } return styleSheet; } private ObjectProperty<Boolean> autoPageSize = new SimpleObjectProperty<>(this, "autoPageSize", true); protected void initAutoPageSize(TableView<UT> tableView) { if (tableView.getFixedCellSize() <= 0) { // TODO Get correct .table-cell {-fx-cell-size} CSS value tableView.setFixedCellSize(24D); } tableView.fixedCellSizeProperty().addListener(updatePageSizeListener); tableView.heightProperty().addListener(updatePageSizeListener); } public boolean isAutoPageSize() { return this.autoPageSizeProperty().get(); } public void setAutoPageSize(boolean autoPageSize) { this.autoPageSizeProperty().set(autoPageSize); } public ObjectProperty<Boolean> autoPageSizeProperty() { return autoPageSize; } private ObjectProperty<Integer> pageSize; protected void updatePageSize() { int newPageSize = (int) (this.getTableView().heightProperty().doubleValue() / this.getTableView().getFixedCellSize()) - 1; int newPageIndex; if (newPageSize < this.getPageSize()) { int firstVisibleIndex = this.getPageSize() * this.getCurrentPageIndex(); if (newPageSize > 0) { newPageIndex = firstVisibleIndex / newPageSize; } else { newPageIndex = 0; } } else { int lastVisibleIndex = this.getPageSize() * (this.getCurrentPageIndex() + 1) - 1; newPageIndex = lastVisibleIndex / newPageSize; } this.setPageSize(newPageSize); if (newPageIndex != this.getCurrentPageIndex()) { this.setCurrentPageIndex(newPageIndex); } } public void setPageSize(int pageSize) { this.pageSizeProperty().set(pageSize); } public int getPageSize() { return this.pageSizeProperty().get(); } public ObjectProperty<Integer> pageSizeProperty() { if (pageSize == null) { pageSize = new SimpleObjectProperty<>(this, "pageSize", 1); pageSize.addListener((o, oldValue, newValue) -> this.loadPage()); } return pageSize; } public void loadPage() { if (this.getDataProvider() != null) { new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { List<UT> page = getDataProvider().loadPage(); Platform.runLater(() -> { getTableView().itemsProperty().get().clear(); getTableView().itemsProperty().get().addAll(page); }); return null; } }; } }.start(); } } private ObjectProperty<DataProvider<?, ?, UT, ? extends AbstractFilter<?, ?>, ? extends AbstractSort<?>>> dataProvider; public DataProvider<?, ?, UT, ? extends AbstractFilter<?, ?>, ? extends AbstractSort<?>> getDataProvider() { return this.dataProviderProperty().get(); } public void setDataProvider( DataProvider<?, ?, UT, ? extends AbstractFilter<?, ?>, ? extends AbstractSort<?>> dataProvider) { this.dataProviderProperty().set(Objects.requireNonNull(dataProvider)); } @SuppressWarnings("unchecked") public ObjectProperty<DataProvider<?, ?, UT, ? extends AbstractFilter<?, ?>, ? extends AbstractSort<?>>> dataProviderProperty() { if (dataProvider == null) { dataProvider = new SimpleObjectProperty<>(this, "dataProvider"); dataProvider.addListener((o, oldValue, newValue) -> { if (this.getTableView() != null) { this.getTableView().itemsProperty().get().clear(); } if (oldValue != null) { Bindings.unbindBidirectional(this.currentPageIndexProperty(), oldValue.currentPageIndexProperty()); Bindings.unbindBidirectional(this.pageSizeProperty(), oldValue.pageSizeProperty()); this.pageNumberProperty().unbind(); Bindings.unbindBidirectional(this.sortsProperty(), oldValue.sortsProperty()); } if (newValue != null) { Bindings.bindBidirectional(this.currentPageIndexProperty(), newValue.currentPageIndexProperty()); Bindings.bindBidirectional(this.pageSizeProperty(), newValue.pageSizeProperty()); this.pageNumberProperty().bind(newValue.pageNumberProperty()); Bindings.bindBidirectional(this.sortsProperty(), (MapProperty<Object, AbstractSort<?>>) newValue.sortsProperty()); } }); } return dataProvider; } private ObjectProperty<TableView<UT>> tableView = new SimpleObjectProperty<>(this, "tableView", new TableView<>()); @SuppressWarnings("unchecked") private ChangeListener<javafx.scene.control.TableColumn.SortType> sortListener = (o, oldValue, newValue) -> { AbstractSort<?> sort = this.getSorts() .get(((SimpleObjectProperty<javafx.scene.control.TableColumn.SortType>) o).getBean()); if (sort != null) { boolean requireLoadPage = false; if (javafx.scene.control.TableColumn.SortType.ASCENDING.equals(newValue)) { sort.setSortType(SortType.ASCENDING); requireLoadPage = true; } else if (javafx.scene.control.TableColumn.SortType.DESCENDING.equals(newValue)) { sort.setSortType(SortType.DESCENDING); requireLoadPage = true; } if (requireLoadPage) { this.loadPage(); } } }; private ListChangeListener<TableColumn<UT, ?>> columnListener = c -> { boolean requireLoadPage = false; while (c.next()) { for (TableColumn<UT, ?> tableColumn : c.getAddedSubList()) { requireLoadPage &= this.sortChanged(tableColumn); tableColumn.sortTypeProperty().addListener(sortListener); } for (TableColumn<UT, ?> tableColumn : c.getRemoved()) { tableColumn.sortTypeProperty().removeListener(sortListener); AbstractSort<?> sort = this.getSorts().get(tableColumn); if (sort != null) { // Fire map list change event. The given event call loadPage() if necessary. this.getSorts().remove(tableColumn); } } } if (requireLoadPage) { this.loadPage(); } }; private ListChangeListener<TableColumn<UT, ?>> sortOrderListener = c -> { boolean requireLoadPage = false; while (c.next()) { for (TableColumn<UT, ?> tableColumn : c.getRemoved()) { tableColumn.setSortType(null); AbstractSort<?> sort = this.getSorts().get(tableColumn); if (sort != null) { sort.setSortType(SortType.NONE); requireLoadPage = true; } } } if (requireLoadPage) { this.loadPage(); } }; protected void initTableView(TableView<UT> tableView) { // Disable default TableView sort function tableView.addEventHandler(SortEvent.ANY, e -> e.consume()); tableView.getColumns().addListener(columnListener); tableView.getSortOrder().addListener(sortOrderListener); boolean requireLoadPage = false; for (TableColumn<UT, ?> tableColumn : tableView.getColumns()) { requireLoadPage &= this.sortChanged(tableColumn); tableColumn.sortTypeProperty().addListener(sortListener); } if (requireLoadPage) { this.loadPage(); } } public TableView<UT> getTableView() { return this.tableViewProperty().get(); } public ObjectProperty<TableView<UT>> tableViewProperty() { return tableView; } private ObjectProperty<PaginationNavigator> paginationNavigator = new SimpleObjectProperty<>(this, "paginationNavigator", new PaginationNavigator()); protected void initPaginationNavigator(PaginationNavigator paginationNavigator) { Bindings.bindBidirectional(paginationNavigator.currentPageIndexProperty(), this.currentPageIndexProperty()); Bindings.bindBidirectional(paginationNavigator.pageNumberProperty(), this.pageNumberProperty()); } public PaginationNavigator getPaginationNavigator() { return this.paginationNavigatorProperty().get(); } public ObjectProperty<PaginationNavigator> paginationNavigatorProperty() { return paginationNavigator; } private ObjectProperty<VPos> navigatorPosition; public VPos getNavigatorPosition() { return navigatorPositionProperty().get(); } public void setNavigatorPosition(VPos vpos) { this.navigatorPositionProperty().set(Objects.requireNonNull(vpos)); } public ObjectProperty<VPos> navigatorPositionProperty() { if (navigatorPosition == null) { navigatorPosition = new SimpleObjectProperty<VPos>(this, "navigatorPosition", VPos.BOTTOM) { @Override protected void invalidated() { if (VPos.BASELINE.equals(this.get()) || VPos.CENTER.equals(this.get())) { this.set(VPos.BOTTOM); } } }; } return navigatorPosition; } private ObjectProperty<Boolean> hideNavigator; public void setHideNavigator(boolean hideNavigator) { this.hideNavigatorProperty().set(hideNavigator); } public boolean isHideNavigator() { return hideNavigatorProperty().get(); } public ObjectProperty<Boolean> hideNavigatorProperty() { if (hideNavigator == null) { hideNavigator = new SimpleObjectProperty<>(this, "hideNavigator", false); } return hideNavigator; } // TODO Add paginationFilter methods /* * PaginationSupport methods */ private ObjectProperty<Integer> pageNumber; @Override public int getPageNumber() { return this.pageNumberProperty().get(); } @Override public ObjectProperty<Integer> pageNumberProperty() { if (pageNumber == null) { pageNumber = new SimpleObjectProperty<>(this, "pageNumber", 0); } return pageNumber; } private ObjectProperty<Integer> currentPageIndex; @Override public void setCurrentPageIndex(int currentPageIndex) { this.currentPageIndexProperty().set(currentPageIndex); } @Override public int getCurrentPageIndex() { return this.currentPageIndexProperty().get(); } @Override public ObjectProperty<Integer> currentPageIndexProperty() { if (currentPageIndex == null) { currentPageIndex = new SimpleObjectProperty<>(this, "currentPageIndex", 0); currentPageIndex.addListener((o, oldValue, newValue) -> { if (newValue >= 0 && newValue < this.getPageNumber()) { Platform.runLater(() -> this.loadPage()); } }); } return currentPageIndex; } @Override public void nextPage() { this.setCurrentPageIndex(this.getCurrentPageIndex() + 1); } @Override public void jumpPage(int pageNumber) { this.setCurrentPageIndex(this.getCurrentPageIndex() + pageNumber); } @Override public void previousPage() { this.setCurrentPageIndex(this.getCurrentPageIndex() - 1); } @Override public void firstPage() { this.setCurrentPageIndex(0); } @Override public void lastPage() { this.setCurrentPageIndex(this.getPageNumber()); } /* * SortSupport methods */ private MapProperty<Object, AbstractSort<?>> sorts; @Override public void addSort(Object key, AbstractSort<?> sort) { this.sortsProperty().put(key, sort); } @Override public AbstractSort<?> removeSort(Object key) { return this.sortsProperty().remove(key); } @Override public Map<Object, AbstractSort<?>> getSorts() { return FXCollections.unmodifiableObservableMap(this.sortsProperty()); } @Override public MapProperty<Object, AbstractSort<?>> sortsProperty() { if (sorts == null) { sorts = new SimpleMapProperty<>(this, "sorts", FXCollections.observableMap(new LinkedHashMap<>())); } return sorts; } }
[ "balanyi@computertechnika.hu" ]
balanyi@computertechnika.hu